问:
Why is my docker container getting a root group when running in Kubernetes?
I'm in the process of ensuring all of our containers are not running as root. I'm having a bit of trouble though with group access. The short version, when I build a container, and run it locally, I get the following:

```<code>docker run -it --entrypoint /bin/sh f83823c8ee6c
~ $ id
uid=1000(metadata) gid=1000(metadata)
</code>```

However when I run this same container in our kubernetes clusters I get the following:

```<code>kubectl -n kube-system get pods -l app=metadata | grep -v NAME | awk '{print $1 }' | xargs -I {} kubectl -n kube-system exec  {} -- id
uid=1000(metadata) gid=1000(metadata) groups=0(root),1000(metadata)
</code>```

The fact that the container is assigned multiple groups when running in the cluster is concerning to me and what I'm trying to solve. I expected the same output when running in the k8s cluster and when running with docker directly.

For some extra background on our deployments, and configuration... The Dockerfile this container is built with:

```<code># build stage
FROM golang:1.13-alpine AS build-env
RUN apk add --no-cache --update alpine-sdk curl
ENV REPO_PATH=**redacted**
COPY . $REPO_PATH
WORKDIR $REPO_PATH
RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
RUN make dep
RUN make build

# final stage
FROM alpine:3.7
WORKDIR /app
COPY --from=build-env **redacted**/bin/server /app/
RUN apk add --no-cache --update ca-certificates && \
  addgroup -g 1000 metadata && \
  adduser -D -g "metadata user" -H -h "/app" -G "metadata" -u 1000 metadata && \
  chown -R metadata:metadata /app
USER 1000:1000
ENTRYPOINT /app/server
</code>```

Our kubernetes version is 1.15.6, and I'm aware that RunAsGroup requires a feature gate, our running controller options (we roll our own clusters, do not use one of the cloud providers managed options):

```<code>kubectl -n kube-system get pods -l=k8s-app=kube-controller-manager | tail -1 | awk ' { print $1 }' | xargs -I {} kubectl -n kube-system get pod {} -o=json | jq '.spec.containers[].command'
[
  "/hyperkube",
  "kube-controller-manager",
  "--log-dir=/var/log/kube-controller",
  "--logtostderr=false",
  "--cluster-cidr=172.16.0.0/16",
  "--allocate-node-cidrs=false",
  "--authentication-kubeconfig=/srv/kubernetes/controller/kubeconfig",
  "--authorization-kubeconfig=/srv/kubernetes/controller/kubeconfig",
  "--cloud-provider=aws",
  "--feature-gates=CustomResourceSubresources=true",
  "--feature-gates=ExpandInUsePersistentVolumes=true",
  "--feature-gates=ExpandPersistentVolumes=true",
  "--feature-gates=TaintNodesByCondition=true",
  "--feature-gates=TTLAfterFinished=true",
  "--feature-gates=RunAsGroup=true",
  "--kubeconfig=/srv/kubernetes/controller/kubeconfig",
  "--root-ca-file=/srv/kubernetes/ca.crt",
  "--service-account-private-key-file=/srv/kubernetes/signing.key",
  "--use-service-account-credentials=true"
]
</code>```

The deployment contains the following:

```<code>kubectl -n kube-system get deployment metadata -o=json | jq .spec.template.spec.securityContext
{
  "fsGroup": 1000,
  "runAsGroup": 1000,
  "runAsNonRoot": true,
  "runAsUser": 1000
}
</code>```

答:
You can provide the supplementalGroups under securityContexts section.</p>

```<code> securityContext: {
    "supplementalGroups": [1000]
 }
</code>```

Body:
I'm in the process of ensuring all of our containers are not running as root. I'm having a bit of trouble though with group access. The short version, when I build a container, and run it locally, I get the following:

docker run -it --entrypoint /bin/sh f83823c8ee6c
~ $ id
uid=1000(metadata) gid=1000(metadata)

However when I run this same container in our kubernetes clusters I get the following:

kubectl -n kube-system get pods -l app=metadata | grep -v NAME | awk '{print $1 }' | xargs -I {} kubectl -n kube-system exec  {} -- id
uid=1000(metadata) gid=1000(metadata) groups=0(root),1000(metadata)

The fact that the container is assigned multiple groups when running in the cluster is concerning to me and what I'm trying to solve. I expected the same output when running in the k8s cluster and when running with docker directly.

For some extra background on our deployments, and configuration... The Dockerfile this container is built with:

# build stage
FROM golang:1.13-alpine AS build-env
RUN apk add --no-cache --update alpine-sdk curl
ENV REPO_PATH=**redacted**
COPY . $REPO_PATH
WORKDIR $REPO_PATH
RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
RUN make dep
RUN make build

# final stage
FROM alpine:3.7
WORKDIR /app
COPY --from=build-env **redacted**/bin/server /app/
RUN apk add --no-cache --update ca-certificates && \
  addgroup -g 1000 metadata && \
  adduser -D -g "metadata user" -H -h "/app" -G "metadata" -u 1000 metadata && \
  chown -R metadata:metadata /app
USER 1000:1000
ENTRYPOINT /app/server

Our kubernetes version is 1.15.6, and I'm aware that RunAsGroup requires a feature gate, our running controller options (we roll our own clusters, do not use one of the cloud providers managed options):

kubectl -n kube-system get pods -l=k8s-app=kube-controller-manager | tail -1 | awk ' { print $1 }' | xargs -I {} kubectl -n kube-system get pod {} -o=json | jq '.spec.containers[].command'
[
  "/hyperkube",
  "kube-controller-manager",
  "--log-dir=/var/log/kube-controller",
  "--logtostderr=false",
  "--cluster-cidr=172.16.0.0/16",
  "--allocate-node-cidrs=false",
  "--authentication-kubeconfig=/srv/kubernetes/controller/kubeconfig",
  "--authorization-kubeconfig=/srv/kubernetes/controller/kubeconfig",
  "--cloud-provider=aws",
  "--feature-gates=CustomResourceSubresources=true",
  "--feature-gates=ExpandInUsePersistentVolumes=true",
  "--feature-gates=ExpandPersistentVolumes=true",
  "--feature-gates=TaintNodesByCondition=true",
  "--feature-gates=TTLAfterFinished=true",
  "--feature-gates=RunAsGroup=true",
  "--kubeconfig=/srv/kubernetes/controller/kubeconfig",
  "--root-ca-file=/srv/kubernetes/ca.crt",
  "--service-account-private-key-file=/srv/kubernetes/signing.key",
  "--use-service-account-credentials=true"
]

The deployment contains the following:

kubectl -n kube-system get deployment metadata -o=json | jq .spec.template.spec.securityContext
{
  "fsGroup": 1000,
  "runAsGroup": 1000,
  "runAsNonRoot": true,
  "runAsUser": 1000
}

Body:
You can provide the supplementalGroups under securityContexts section.

 securityContext: {
    "supplementalGroups": [1000]
 }


来源: stackexchange

问:
Javascript changing function trouble
The code below is how it was originally

```<code>   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }
</code>```

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

```<code>function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`
</code>```

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

答:
Here's a simple solution that uses randojs.com for readability.

function getRandomEmail(){
  return rando(["accounting", "sales", "hr"]).value + "@dundermifflin.com";
}

console.log(getRandomEmail());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://randojs.com/1.0.0.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Title: Javascript changing function trouble

Body:
The code below is how it was originally

   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

Body:
Here's a simple solution that uses randojs.com for readability.

function getRandomEmail(){
  return rando(["accounting", "sales", "hr"]).value + "@dundermifflin.com";
}

console.log(getRandomEmail());

<script src="https://randojs.com/1.0.0.js"></script>


问:
Django comments needs a Delete Action for non-superusers
I recently upgraded a large Django install from 1.1 to 1.3. In the Comments app, they added a caveat so only Superusers get the Delete Action.

The moderators, who have permissions to Delete, as a result don't see those Actions. This is really inconvenient for them.

The code in question is in contrib.comments.admin starting on line 28:

```<code>def get_actions(self, request):
    actions = super(CommentsAdmin, self).get_actions(request)
    # Only superusers should be able to delete the comments from the DB.
    if not request.user.is_superuser and 'delete_selected' in actions:
        actions.pop('delete_selected')
</code>```

It should instead ask if request.user has delete permissions.

How can I override this without jacking with the actual Django install?

(And if anyone knows why this was changed, I'd be interested to know.)

答:
In the comments app, there is a "Remove selected comments" action. When you apply the  this action, it 'marks' the comment as deleted instead of deleting from the database -- it creates a deleted flag for the comment and sets comment.is_removed = True.

I recommend that you give your moderators the comments.can_moderate permission, and remove comments in that way. If you really want your moderators to be able to delete comments, you could do the following:

subclass the CommentsAdmin in admin.py

override the get_actions method

unregister the CommentsAdmin ModelAdmin, then register your subclass.

To do this, put the following code in one of your apps.

```<code># myapp.admin.py
# The app should come after `django.contrib.comments`
# in your INSTALLED_APPS tuple

from django.contrib.comments.admin import CommentsAdmin

class MyCommentsAdmin(CommentsAdmin):
    def get_actions(self, request):
        actions = super(MyCommentsAdmin, self).get_actions(request)
        if not request.user.has_perm('comments.can_moderate'):
            if 'approve_comments' in actions:
                actions.pop('approve_comments')
            if 'remove_comments' in actions:
                actions.pop('remove_comments')
        return actions

admin.site.unregister(CommentsAdmin)
admin.site.register(MyCommentsAdmin)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I recently upgraded a large Django install from 1.1 to 1.3. In the Comments app, they added a caveat so only Superusers get the Delete Action.

The moderators, who have permissions to Delete, as a result don't see those Actions. This is really inconvenient for them.

The code in question is in contrib.comments.admin starting on line 28:

def get_actions(self, request):
    actions = super(CommentsAdmin, self).get_actions(request)
    # Only superusers should be able to delete the comments from the DB.
    if not request.user.is_superuser and 'delete_selected' in actions:
        actions.pop('delete_selected')

It should instead ask if request.user has delete permissions.

How can I override this without jacking with the actual Django install?

(And if anyone knows why this was changed, I'd be interested to know.)

Body:
In the comments app, there is a "Remove selected comments" action. When you apply the  this action, it 'marks' the comment as deleted instead of deleting from the database -- it creates a deleted flag for the comment and sets comment.is_removed = True.

I recommend that you give your moderators the comments.can_moderate permission, and remove comments in that way. If you really want your moderators to be able to delete comments, you could do the following:

subclass the CommentsAdmin in admin.py

override the get_actions method

unregister the CommentsAdmin ModelAdmin, then register your subclass.

To do this, put the following code in one of your apps.

# myapp.admin.py
# The app should come after `django.contrib.comments`
# in your INSTALLED_APPS tuple

from django.contrib.comments.admin import CommentsAdmin

class MyCommentsAdmin(CommentsAdmin):
    def get_actions(self, request):
        actions = super(MyCommentsAdmin, self).get_actions(request)
        if not request.user.has_perm('comments.can_moderate'):
            if 'approve_comments' in actions:
                actions.pop('approve_comments')
            if 'remove_comments' in actions:
                actions.pop('remove_comments')
        return actions

admin.site.unregister(CommentsAdmin)
admin.site.register(MyCommentsAdmin)


问:
Python - Match a string without whitespace except newline at the end?
I want to test for the entry into the terminal of a single word, i.e. 'Cat' (without anything at the end).

This allows "Cat     ":

```<code>re.match(r'[A-Z]{1}[a-z]{1,15}', x)
</code>```

This doesn't allow even 'Cat' to be entered!:

```<code>re.match(r'[A-Z]{1}[a-z]{1,15}[^\s]', x)
</code>```

What am I doing wrong? To clarify, it asks for an input and the person has to type Cat and hit enter, no spaces at the end. Thanks! :)

答: You can use x.replace(' ', ''). This allow even 'Cat     ' and '      Cat' (or '    Cat    ')

Body:
I want to test for the entry into the terminal of a single word, i.e. 'Cat' (without anything at the end).

This allows "Cat     ":

re.match(r'[A-Z]{1}[a-z]{1,15}', x)

This doesn't allow even 'Cat' to be entered!:

re.match(r'[A-Z]{1}[a-z]{1,15}[^\s]', x)

What am I doing wrong? To clarify, it asks for an input and the person has to type Cat and hit enter, no spaces at the end. Thanks! :)


问:
DatePickerDialog issue with fragments
I have a fragment with editText that is meant to open a date picker. I have done everything seemingly correctly, however I can't figure out why I get the following error.

It has something to do with the fact that I'm working with a fragment.

Could you please help with this error?

EditProfileFragment.java

```<code>import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.archive.pod.R;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

public class EditProfileFragment extends Fragment {

  //Initializing
  private TextInputEditText mDisplayDate;
  private DatePickerDialog.OnDateSetListener mDateSetListener;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_editprofile, container, false);

    //EditText
    mDisplayDate = view.findViewById(R.id.etDateOfBirth);

    //Date picker dialog box
    mDisplayDate.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(
          requireContext(),
          android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
          mDateSetListener,
          year, month, day);

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
      }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker datePicker, int year, int month, int day) {
        month = month + 1;
        String date = month + "/" + day + "/" + year;
        mDisplayDate.setText(date);
      }
    };
    return view;
  }
}
</code>```

Error Log

```<code>/AndroidRuntime: FATAL EXCEPTION: main
Process: com.archive.pod, PID: 20399
java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to com.google.android.material.textfield.TextInputEditText
at com.archive.pod.Profile.EditProfileFragment.onCreateView(EditProfileFragment.java: 33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java: 2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java: 881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java: 1238)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java: 434)
</code>```

Fragment Layout

```<code><merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/userProfilePicture"
                android:src="@drawable/ic_profile_picture_default"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginTop="20dp"
                android:layout_centerHorizontal="true" />

            <ImageButton
                android:id="@+id/changeUserPhoto"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginTop="90dp"
                android:layout_marginLeft="200dp"
                android:layout_marginStart="200dp"
                android:elevation="10dp"
                android:background="@drawable/ic_add_circle"/>

            <RelativeLayout
                android:id="@+id/sectionTitle1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/changeUserPhoto"
                android:layout_marginTop="50dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Primary Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/relLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_below="@+id/sectionTitle1">

                <!-- Full name input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etFullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textNoSuggestions"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/full_name" />

                </com.google.android.material.textfield.TextInputLayout>

                <!-- Email input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etFullname"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/emailAddress"
                        android:inputType="textEmailAddress"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/sectionTitle2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/relLayout1"
                android:layout_marginTop="20dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Private Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/sectionTitle2">

                <!-- Phone number input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etPhoneNumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/phone_number"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

                <!-- Date of birth input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etDateOfBirth"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etPhoneNumber"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/dob"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

        </RelativeLayout>

    </ScrollView>

</merge>
</code>```

答: Use getapplicationcontext() and remove Edittextprofilefragment.this</p>

Title: DatePickerDialog issue with fragments

Body:
I have a fragment with editText that is meant to open a date picker. I have done everything seemingly correctly, however I can't figure out why I get the following error.

It has something to do with the fact that I'm working with a fragment.

Could you please help with this error?

EditProfileFragment.java

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.archive.pod.R;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

public class EditProfileFragment extends Fragment {

  //Initializing
  private TextInputEditText mDisplayDate;
  private DatePickerDialog.OnDateSetListener mDateSetListener;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_editprofile, container, false);

    //EditText
    mDisplayDate = view.findViewById(R.id.etDateOfBirth);

    //Date picker dialog box
    mDisplayDate.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(
          requireContext(),
          android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
          mDateSetListener,
          year, month, day);

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
      }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker datePicker, int year, int month, int day) {
        month = month + 1;
        String date = month + "/" + day + "/" + year;
        mDisplayDate.setText(date);
      }
    };
    return view;
  }
}

Error Log

/AndroidRuntime: FATAL EXCEPTION: main
Process: com.archive.pod, PID: 20399
java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to com.google.android.material.textfield.TextInputEditText
at com.archive.pod.Profile.EditProfileFragment.onCreateView(EditProfileFragment.java: 33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java: 2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java: 881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java: 1238)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java: 434)

Fragment Layout

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/userProfilePicture"
                android:src="@drawable/ic_profile_picture_default"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginTop="20dp"
                android:layout_centerHorizontal="true" />

            <ImageButton
                android:id="@+id/changeUserPhoto"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginTop="90dp"
                android:layout_marginLeft="200dp"
                android:layout_marginStart="200dp"
                android:elevation="10dp"
                android:background="@drawable/ic_add_circle"/>

            <RelativeLayout
                android:id="@+id/sectionTitle1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/changeUserPhoto"
                android:layout_marginTop="50dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Primary Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/relLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_below="@+id/sectionTitle1">

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etFullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textNoSuggestions"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/full_name" />

                </com.google.android.material.textfield.TextInputLayout>

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etFullname"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/emailAddress"
                        android:inputType="textEmailAddress"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/sectionTitle2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/relLayout1"
                android:layout_marginTop="20dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Private Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/sectionTitle2">

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etPhoneNumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/phone_number"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etDateOfBirth"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etPhoneNumber"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/dob"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

        </RelativeLayout>

    </ScrollView>

</merge>


问:
How to automatically scale down a 100% div without showing browser vertical scrollbars?
I have a table with three rows. I have 1 main #container div (height 100%) and inside it is a table with 3 rows. The first and last row have fixed size content. In the second row is a #content div with 100% height and overflow:auto. (actually the table has a lot more rows and the page has more divs, but for the sake of clarity i scalled it down for this question).

If there is more content in #content than fits, a vertical scrollbar should appear next to that div's content. However, a vertical scrollbar appears at the browser window itself. When i set the #content div to a fixed size however, that vertical scrollbar does appear in the correct place.

I must be doing something wrong, or maybe misinterpreting something :) Any ideas? Maybe there's jquery/javascript out there that can monitor the page and when loading/resizing the browser, scales down that particular div?

EDIT: I just created a small example: http://wierdaonline.com/softest.html

In the ideal situation, the whole thing (table) should always be visible in the browser window, without any window scrollbar other than in the #content div.

答: Set overflow: scroll in the div. You shouldn't need Javascript for this.


问:
Why isn't this factorial finding algorithm O(n!) run-time complexity?
I discovered this issue by implemented the algorithm from this post: Example of O(n!)?

I tried counting the operations though, and the algorithm loops 64 times when calculating 4! (which is 24).

Is there something I'm missing? Or does this algorithm really just have a run-time complexity that is not O(n!)

var operations = 0;

function factorial(n) {
    for (let i = 0; i < n; i++) {
        operations++;
        factorial(n - 1);
    }
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 64 operations```

答:
The factorial function should be:

```<code>var operations = 0;

function factorial(n) {
    operation++;
    if (n === 0) return 1;
    return n*factorial(n - 1);
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 24 operations
</code>```

And it's O(n).
The example is about O(n!), which is a time complexity depend on n!, not n! itself.

Body:
The factorial function should be:

var operations = 0;

function factorial(n) {
    operation++;
    if (n === 0) return 1;
    return n*factorial(n - 1);
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 24 operations

And it's O(n).
The example is about O(n!), which is a time complexity depend on n!, not n! itself.


问:
How to let NVDA read Swing / GUI elements
I am using the Eclipse ide for Java development. When I execute the following code, the NVDA only reads ‘This is a frame’. It doesn’t read the button.

import javax.swing.;
    import javax.accessibility.;

```<code>public class MyButton {
    public static void main(String [] args) {
        JFrame f = new JFrame ("This is a frame");
JButton b = new JButton ("This one is a button");
    b.setBounds(50,100,95,30);
//f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
b.setToolTipText("This tooltip makes the button accessible");;
}
}
</code>```

**I have enabled AccessBridge via Ease of Access Center. I’m using Eclipse and NVDA on Windows 10.

答:
Due to a long list of issues, I ended up switching to Eclipse for Java EE. I also updated my NVDA at around the same time. According to the What's New section of the update, they've done some improvements on Java AccessBridge.
I'm not sure if it was the NVDA update or switching to Java EE, but everything is working as it should.</p>

Body:
I am using the Eclipse ide for Java development. When I execute the following code, the NVDA only reads ‘This is a frame’. It doesn’t read the button.

import javax.swing.;
    import javax.accessibility.;

public class MyButton {
    public static void main(String [] args) {
        JFrame f = new JFrame ("This is a frame");
JButton b = new JButton ("This one is a button");
    b.setBounds(50,100,95,30);
//f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
b.setToolTipText("This tooltip makes the button accessible");;
}
}

**I have enabled AccessBridge via Ease of Access Center. I’m using Eclipse and NVDA on Windows 10.


问:
php -v returns dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.7.dylib
I was trying to install Valet and for a mistake I uninstall php from brew, now I reinstall php, if I go to a phpinfo() file on apache I can see

PHP Version 7.1.23

but if I do php -v on console, or something other php command i get:

dyld: Library not loaded:
  /usr/local/opt/readline/lib/libreadline.7.dylib   Referenced from:
  /usr/local/bin/php   Reason: image not found Abort trap: 6

Im on Mac Os Sierra

答:
For me, I had php 5.4 installed, but an upgrade to php 7.3 worked for me.

```<code>brew install php@7.3
</code>```

Then you'll likely need to add the new php version in your path. This basically means that when you load up your shell it knows where find the path to the files that you are using. For me, since I'm using zshrc that command is:

```<code>echo 'export PATH="/usr/local/opt/php@7.3/bin:$PATH"' >> ~/.zshrc
</code>```

For you, if you have all your path and aliases in bash profile then the command would be this instead:

```<code>echo 'export PATH="/usr/local/opt/php@7.3/bin:$PATH"' >> ~/.bash_profile
</code>```

Then, all you need to do is either source your zshrc or your bash_profile file, OR close that tab and open a new one. The source command basically says "hey, make sure you have an updated list of my aliases and path info". This naturally happens when you open a new shell, but you can force that with a command like:

```<code>source ~/.bash_profile
</code>```

And then it worked for me. Good luck.

Body:
For me, I had php 5.4 installed, but an upgrade to php 7.3 worked for me.

brew install php@7.3

Then you'll likely need to add the new php version in your path. This basically means that when you load up your shell it knows where find the path to the files that you are using. For me, since I'm using zshrc that command is:

echo 'export PATH="/usr/local/opt/php@7.3/bin:$PATH"' >> ~/.zshrc

For you, if you have all your path and aliases in bash profile then the command would be this instead:

echo 'export PATH="/usr/local/opt/php@7.3/bin:$PATH"' >> ~/.bash_profile

Then, all you need to do is either source your zshrc or your bash_profile file, OR close that tab and open a new one. The source command basically says "hey, make sure you have an updated list of my aliases and path info". This naturally happens when you open a new shell, but you can force that with a command like:

source ~/.bash_profile

And then it worked for me. Good luck.


问:
localization Faker\Factory does not work in laravel
I have a Post Model with these fields :

```<code>post_id
post_title
post_content
post_content_full
author
</code>```

Now I want to use laravel sedders and model factories to create fake fa_IR localized data and insert to posts table.

For that I wrote this in database/factories/ModelFactory.php:

```<code>$factory->define(App\Post::class, function (Faker\Generator $faker) {
        return [
            'post_title'        => $faker->sentence,
            'post_content'      => $faker->paragraph,
            'post_content_full' => $faker->paragraph(3),
            'author'            => $faker->name
        ];
    });
</code>```

Then I created a PostsTableSeeder class like this :

```<code>use Illuminate\Database\Seeder;

class PostsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run ()
    {
        factory(App\Post::class, 5)->create();
    }
}
</code>```

And in AppServiceProvider.php added below codes to register function :

```<code>$this->app->singleton(FakerGenerator::class, function () {
        return FakerFactory::create('fa_IR');
    });
</code>```

But After running the seed , laravel uses default locale (en_US) and ignores  fa_IR.

I do not know what else to do.

Update:

Even I changed in DEFAULT_LOCALE const vendor/fzaninotto/faker/src/Faker/Factory.php to fa_IR Nothing changed.

答: You need to change the faker locale in your app config file.</p>

Body:
I have a Post Model with these fields :

post_id
post_title
post_content
post_content_full
author

Now I want to use laravel sedders and model factories to create fake fa_IR localized data and insert to posts table.

For that I wrote this in database/factories/ModelFactory.php:

$factory->define(App\Post::class, function (Faker\Generator $faker) {
        return [
            'post_title'        => $faker->sentence,
            'post_content'      => $faker->paragraph,
            'post_content_full' => $faker->paragraph(3),
            'author'            => $faker->name
        ];
    });

Then I created a PostsTableSeeder class like this :

use Illuminate\Database\Seeder;

class PostsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run ()
    {
        factory(App\Post::class, 5)->create();
    }
}

And in AppServiceProvider.php added below codes to register function :

$this->app->singleton(FakerGenerator::class, function () {
        return FakerFactory::create('fa_IR');
    });

But After running the seed , laravel uses default locale (en_US) and ignores  fa_IR.

I do not know what else to do.

Update:

Even I changed in DEFAULT_LOCALE const vendor/fzaninotto/faker/src/Faker/Factory.php to fa_IR Nothing changed.


问:
Constructing Indptr for SciPy Sparse CSC Matrix
I have many lists that represent a sparse matrix (i.e., the columns that have nonzero entries) that I need to represent as a SciPy sparse csc_matrix. However, note that there is only one row in my sparse matrix and so the list simply points to the columns within this row that has nonzero entries. For example:

```<code>sparse_input = [4, 10, 21]  # My lists are much, much longer but very sparse
</code>```

This list tells me which columns within my single row sparse matrix where there are nonzero values. This is what the dense matrix would look like.

```<code>x = np.array([[0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1]])
</code>```

I could use the (data, (row, col)) syntax but since my lists are super long the csc_matrix takes a lot of time and memory to build. So, I was thinking about using the indptr interface but I'm having trouble figuring out how to quickly and automatically build the indptr directly from a given sparse list of nonzero column entries. I tried looking at csr_matrix(x).indptr and I see that the indptr looks like:

```<code>array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       3], dtype=int32)
</code>```

I've read the SciPy docs and the Sparse Matrix Wikipedia page but I can't seem to come up with an efficient method to construct the indptr directly from a list of nonzero columns. It just feels like indptr shouldn't be this long in length considering that there are only three nonzero entries in the sparse matrix.

答:
How about just making the matrices, and exploring their attributs?

```<code>In [144]: from scipy import sparse
In [145]: x = np.array([[0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1]])

In [146]: M = sparse.coo_matrix(x)
In [147]: M
Out[147]:
<1x22 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in COOrdinate format>
In [148]: M.row
Out[148]: array([0, 0, 0], dtype=int32)
In [149]: M.col
Out[149]: array([ 4, 10, 21], dtype=int32)
In [150]: M.data
Out[150]: array([1, 1, 1])
</code>```

csr:

```<code>In [152]: Mr = M.tocsr()
In [153]: Mr.indptr
Out[153]: array([0, 3], dtype=int32)
In [155]: Mr.indices
Out[155]: array([ 4, 10, 21], dtype=int32)
In [156]: Mr.data
Out[156]: array([1, 1, 1], dtype=int64)
</code>```

csc:

```<code>In [157]: Mc = M.tocsc()
In [158]: Mc.indptr
Out[158]:
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       3], dtype=int32)
In [159]: Mc.indices
Out[159]: array([0, 0, 0], dtype=int32)
In [160]: Mc.data
Out[160]: array([1, 1, 1], dtype=int64)
</code>```

And the direct nonzero on x:

```<code>In [161]: np.nonzero(x)
Out[161]: (array([0, 0, 0]), array([ 4, 10, 21]))
</code>```

For a 1 row matrix like this, I doubt if you'll save much time by creating the csr indptr directly.  Most of the work will be in the nonzero step.  But feel free to experiement.

===

Some timings

```<code>In [162]: timeit sparse.coo_matrix(x)
95.8 µs ± 110 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [163]: timeit sparse.csr_matrix(x)
335 µs ± 2.59 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [164]: timeit M.tocsr()
115 µs ± 948 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [165]: timeit M.tocsc()
117 µs ± 90.4 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [166]: sparse.csr_matrix?
In [167]: timeit M.tocsc()
117 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [168]: timeit sparse.csc_matrix(x)
335 µs ± 257 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [169]: timeit sparse.coo_matrix(x).tocsr()
219 µs ± 3.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

I'm a little surprised that the csr_matrix is slower than coo followed by conversion.

Now let's try to make the matrix with indptr etc.

```<code>In [170]: timeit np.nonzero(x)
2.52 µs ± 65.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [173]: timeit sparse.csr_matrix((Mr.data, Mr.indices, Mr.indptr))
92.5 µs ± 79.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [174]: %%timeit
     ...: indices = np.nonzero(x)[1]
     ...: data = np.ones_like(indices)
     ...: indptr = np.array([0,len(indices)])
     ...: sparse.csr_matrix((data, indices, indptr))
     ...:
     ...:
161 µs ± 605 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Body:
I have many lists that represent a sparse matrix (i.e., the columns that have nonzero entries) that I need to represent as a SciPy sparse csc_matrix. However, note that there is only one row in my sparse matrix and so the list simply points to the columns within this row that has nonzero entries. For example:

sparse_input = [4, 10, 21]  # My lists are much, much longer but very sparse

This list tells me which columns within my single row sparse matrix where there are nonzero values. This is what the dense matrix would look like.

x = np.array([[0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1]])

I could use the (data, (row, col)) syntax but since my lists are super long the csc_matrix takes a lot of time and memory to build. So, I was thinking about using the indptr interface but I'm having trouble figuring out how to quickly and automatically build the indptr directly from a given sparse list of nonzero column entries. I tried looking at csr_matrix(x).indptr and I see that the indptr looks like:

array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       3], dtype=int32)

I've read the SciPy docs and the Sparse Matrix Wikipedia page but I can't seem to come up with an efficient method to construct the indptr directly from a list of nonzero columns. It just feels like indptr shouldn't be this long in length considering that there are only three nonzero entries in the sparse matrix.

Body:
How about just making the matrices, and exploring their attributs?

In [144]: from scipy import sparse
In [145]: x = np.array([[0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1]])

In [146]: M = sparse.coo_matrix(x)
In [147]: M
Out[147]:
<1x22 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in COOrdinate format>
In [148]: M.row
Out[148]: array([0, 0, 0], dtype=int32)
In [149]: M.col
Out[149]: array([ 4, 10, 21], dtype=int32)
In [150]: M.data
Out[150]: array([1, 1, 1])

csr:

In [152]: Mr = M.tocsr()
In [153]: Mr.indptr
Out[153]: array([0, 3], dtype=int32)
In [155]: Mr.indices
Out[155]: array([ 4, 10, 21], dtype=int32)
In [156]: Mr.data
Out[156]: array([1, 1, 1], dtype=int64)

csc:

In [157]: Mc = M.tocsc()
In [158]: Mc.indptr
Out[158]:
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       3], dtype=int32)
In [159]: Mc.indices
Out[159]: array([0, 0, 0], dtype=int32)
In [160]: Mc.data
Out[160]: array([1, 1, 1], dtype=int64)

And the direct nonzero on x:

In [161]: np.nonzero(x)
Out[161]: (array([0, 0, 0]), array([ 4, 10, 21]))

For a 1 row matrix like this, I doubt if you'll save much time by creating the csr indptr directly.  Most of the work will be in the nonzero step.  But feel free to experiement.

===

Some timings

In [162]: timeit sparse.coo_matrix(x)
95.8 µs ± 110 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [163]: timeit sparse.csr_matrix(x)
335 µs ± 2.59 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [164]: timeit M.tocsr()
115 µs ± 948 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [165]: timeit M.tocsc()
117 µs ± 90.4 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [166]: sparse.csr_matrix?
In [167]: timeit M.tocsc()
117 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [168]: timeit sparse.csc_matrix(x)
335 µs ± 257 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [169]: timeit sparse.coo_matrix(x).tocsr()
219 µs ± 3.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

I'm a little surprised that the csr_matrix is slower than coo followed by conversion.

Now let's try to make the matrix with indptr etc.

In [170]: timeit np.nonzero(x)
2.52 µs ± 65.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [173]: timeit sparse.csr_matrix((Mr.data, Mr.indices, Mr.indptr))
92.5 µs ± 79.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [174]: %%timeit
     ...: indices = np.nonzero(x)[1]
     ...: data = np.ones_like(indices)
     ...: indptr = np.array([0,len(indices)])
     ...: sparse.csr_matrix((data, indices, indptr))
     ...:
     ...:
161 µs ± 605 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)


问:
python + SQLAlchemy: deleting with the Session object
I can't quite figure this out: I'd like to delete all the records from a table on a matching query. Kind of like this.

```<code>engine = sqlalchemy.create_engine(string)
meta = MetaData(bind=engine)
meta.reflect(bind=engine, schema='myschema')

Base = automap_base(metadata=meta)
Base.prepare(engine, reflect=True)
Classes = Base.classes

Session = sessionmaker(bind=engine)
session = Session()

session.delete(plays.record_id == '123')
</code>```

But that isn't working. What's the idea here? Error I get is:

error in parsing record ID 020087: Class 'sqlalchemy.sql.elements.BinaryExpression' is not mapped

答:
Delete All Records

```<code>#for all records
session.query(Model).delete()
session.commit()
</code>```

Deleted Single Row

If you want to delete specific records then try filter clause in the query.
ex.

```<code>#for specific value
session.query(Model).filter(Model.id==123).delete()
session.commit()
</code>```

Delete Single Record by Object

```<code>record_obj = session.query(Model).filter(Model.id==123).first()
session.delete(record_obj)
session.commit()
</code>```

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

Body:
I can't quite figure this out: I'd like to delete all the records from a table on a matching query. Kind of like this.

engine = sqlalchemy.create_engine(string)
meta = MetaData(bind=engine)
meta.reflect(bind=engine, schema='myschema')

Base = automap_base(metadata=meta)
Base.prepare(engine, reflect=True)
Classes = Base.classes

Session = sessionmaker(bind=engine)
session = Session()

session.delete(plays.record_id == '123')

But that isn't working. What's the idea here? Error I get is:

error in parsing record ID 020087: Class 'sqlalchemy.sql.elements.BinaryExpression' is not mapped

Body:
Delete All Records

#for all records
session.query(Model).delete()
session.commit()

Deleted Single Row

If you want to delete specific records then try filter clause in the query.
ex.

#for specific value
session.query(Model).filter(Model.id==123).delete()
session.commit()

Delete Single Record by Object

record_obj = session.query(Model).filter(Model.id==123).first()
session.delete(record_obj)
session.commit()

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records


问:
TypeError: CleanwebpackPlugin is not a constructor
i'm trying to preview a vue web application through webpack-server-dev.I'm following this guide
https://medium.com/the-web-tub/creating-your-first-vue-js-pwa-project-22f7c552fb34

The guide explains that the plugin is used to delete old and unused files in the dist directory. I have already tried replacing const CleanWebpackPlugin = require('clean-webpack-plugin') with const { CleanWebpackPlugin } = require('clean-webpack-plugin') which some posts suggest. i have also tried looking at the documentation on https://github.com/johnagan/clean-webpack-plugin but without succes as i am pretty new to this.

when i try to npm run dev i get this error

```<code>    new CleanWebpackPlugin(['dist']),
    ^

TypeError: CleanWebpackPlugin is not a constructor
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\webpack.config.js:56:5)
    at handleFunction (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:21:13)
    at prepareOptions (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:9:5)
    at requireConfig (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:119:14)
    at C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:125:17
    at Array.forEach (<anonymous>)
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:123:15)
    at Object.<anonymous> (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-dev-server\bin\webpack-dev-server.js:79:40)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
</code>```

and this is the webpack.config.js file

```<code>const path = require('path')

const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')

module.exports = (env, argv) => ({
  mode: argv && argv.mode || 'development',
  devtool: (argv && argv.mode || 'development') === 'production' ? 'source-map' : 'eval',

  entry: './src/app.js',

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },

  node: false,

  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
        exclude: /\.module\.css$/
      }
    ]
  },

  resolve: {
    extensions: [
      '.js',
      '.vue',
      '.json'
    ],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': path.resolve(__dirname, 'src')
    }
  },

  plugins: [
    new CleanWebpackPlugin(['dist']),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'static', 'index.html'),
      inject: true
    }),
    new CopyWebpackPlugin([{
      from: path.resolve(__dirname, 'static'),
      to: path.resolve(__dirname, 'dist'),
      toType: 'dir'
    }])
  ],

  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 30000,
      maxSize: 0,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
    runtimeChunk: {
      name: entrypoint => `runtime~${entrypoint.name}`
    },
    mangleWasmImports: true,
    removeAvailableModules: true,
    removeEmptyChunks: true,
    mergeDuplicateChunks: true
  },

  devServer: {
    compress: true,
    host: 'localhost',
    https: true,
    open: true,
    overlay: true,
    port: 9000
  }
});

</code>```

this is the error i get when using the right import as explained in the documenation :

```<code>      throw new Error(`clean-webpack-plugin only accepts an options object. See:
      ^

Error: clean-webpack-plugin only accepts an options object. See:
            https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-optional
    at new CleanWebpackPlugin (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\clean-webpack-plugin\dist\clean-webpack-plugin.js:27:13)
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\webpack.config.js:56:5)
    at handleFunction (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:21:13)
    at prepareOptions (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:9:5)
    at requireConfig (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:119:14)
    at C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:125:17
    at Array.forEach (<anonymous>)
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:123:15)
    at Object.<anonymous> (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-dev-server\bin\webpack-dev-server.js:79:40)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
</code>```

if i delete line 56 in webpack.config.js i can run the web application without problems, but i want to understand the source of this issue

答:
CleanWebpackPlugin  v3.0.0

Replaced default export with named export CleanWebpackPlugin

[https://github.com/johnagan/clean-webpack-plugin/releases/tag/v3.0.0]

correct code is:

```<code>// es modules
import { CleanWebpackPlugin } from 'clean-webpack-plugin';

// common js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
</code>```

Body:
i'm trying to preview a vue web application through webpack-server-dev.I'm following this guide
https://medium.com/the-web-tub/creating-your-first-vue-js-pwa-project-22f7c552fb34

The guide explains that the plugin is used to delete old and unused files in the dist directory. I have already tried replacing const CleanWebpackPlugin = require('clean-webpack-plugin') with const { CleanWebpackPlugin } = require('clean-webpack-plugin') which some posts suggest. i have also tried looking at the documentation on https://github.com/johnagan/clean-webpack-plugin but without succes as i am pretty new to this.

when i try to npm run dev i get this error

    new CleanWebpackPlugin(['dist']),
    ^

TypeError: CleanWebpackPlugin is not a constructor
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\webpack.config.js:56:5)
    at handleFunction (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:21:13)
    at prepareOptions (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:9:5)
    at requireConfig (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:119:14)
    at C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:125:17
    at Array.forEach (<anonymous>)
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:123:15)
    at Object.<anonymous> (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-dev-server\bin\webpack-dev-server.js:79:40)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

and this is the webpack.config.js file

const path = require('path')

const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')

module.exports = (env, argv) => ({
  mode: argv && argv.mode || 'development',
  devtool: (argv && argv.mode || 'development') === 'production' ? 'source-map' : 'eval',

  entry: './src/app.js',

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },

  node: false,

  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
        exclude: /\.module\.css$/
      }
    ]
  },

  resolve: {
    extensions: [
      '.js',
      '.vue',
      '.json'
    ],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': path.resolve(__dirname, 'src')
    }
  },

  plugins: [
    new CleanWebpackPlugin(['dist']),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'static', 'index.html'),
      inject: true
    }),
    new CopyWebpackPlugin([{
      from: path.resolve(__dirname, 'static'),
      to: path.resolve(__dirname, 'dist'),
      toType: 'dir'
    }])
  ],

  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 30000,
      maxSize: 0,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
    runtimeChunk: {
      name: entrypoint => `runtime~${entrypoint.name}`
    },
    mangleWasmImports: true,
    removeAvailableModules: true,
    removeEmptyChunks: true,
    mergeDuplicateChunks: true
  },

  devServer: {
    compress: true,
    host: 'localhost',
    https: true,
    open: true,
    overlay: true,
    port: 9000
  }
});

this is the error i get when using the right import as explained in the documenation :

      throw new Error(`clean-webpack-plugin only accepts an options object. See:
      ^

Error: clean-webpack-plugin only accepts an options object. See:
            https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-optional
    at new CleanWebpackPlugin (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\clean-webpack-plugin\dist\clean-webpack-plugin.js:27:13)
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\webpack.config.js:56:5)
    at handleFunction (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:21:13)
    at prepareOptions (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\prepareOptions.js:9:5)
    at requireConfig (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:119:14)
    at C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:125:17
    at Array.forEach (<anonymous>)
    at module.exports (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-cli\bin\utils\convert-argv.js:123:15)
    at Object.<anonymous> (C:\Users\Eson\Desktop\pwa-vue-app-1\node_modules\webpack-dev-server\bin\webpack-dev-server.js:79:40)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)

if i delete line 56 in webpack.config.js i can run the web application without problems, but i want to understand the source of this issue

Body:
CleanWebpackPlugin  v3.0.0

Replaced default export with named export CleanWebpackPlugin

[https://github.com/johnagan/clean-webpack-plugin/releases/tag/v3.0.0]

correct code is:

// es modules
import { CleanWebpackPlugin } from 'clean-webpack-plugin';

// common js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');


问:
Change moment.js locale on the fly in Angular 8
THE TITLE is what I need. I have a language picker drop down in my app and so far I've been using it to dynamically (without refreshing the page) change the language in the app. When I tried to do that using moment.js' moment.locale(string), it doesn't update the view like the rest of the app.

```<code>setLocale(locale?: string) {
    if (!locale) locale = localStorage.getItem("locale") || "en-US";
    localStorage.setItem("locale", locale);
    this.adapter.setLocale(locale); //for date picker (nothing to do with moment.js)
    moment.locale(locale); // for moment.js ------------------- only works after refresh
    this.translate.use(locale); //rest of the app
}
</code>```

That's the method invoked when a language is selected from the drop down, but dates rendered by moment.js are not updated but until page refresh.

Is there a way to do this? Hack? Workaround?

Thanks

答:
@Pipe({
  name: 'dynamicMoment'
})
export class MomentPipe implements PipeTransform {
  /**
   * MomentPipe constructor
   * @param {TranslateService} translate
   */
  constructor(private translate: TranslateService) {
  }

  /**
   * Make moment dynamic
   * @param {string} value
   * @param {string} format
   * @returns {any}
   */
  transform(value: string, format?: string): any {
    // make the moment format configurable
    format = format ? format : 'MMMM Do YYYY';
    // get the initial value
    const initVal = moment(value).locale(moment.locale()).format(format);
    // insert the value into a new behaviour subject. If the language changes, the behaviour subject will be
    // updated
    const momentObs = new BehaviorSubject<string>(initVal);
    this.translate.onLangChange.subscribe(() => {
      // format the new date according to the new locale
      const val = moment(value).locale(moment.locale()).format(format);
      momentObs.next(val);
    });
    return momentObs; // needs to be piped into the async pipe
  }

}```

Body:
THE TITLE is what I need. I have a language picker drop down in my app and so far I've been using it to dynamically (without refreshing the page) change the language in the app. When I tried to do that using moment.js' moment.locale(string), it doesn't update the view like the rest of the app.

setLocale(locale?: string) {
    if (!locale) locale = localStorage.getItem("locale") || "en-US";
    localStorage.setItem("locale", locale);
    this.adapter.setLocale(locale); //for date picker (nothing to do with moment.js)
    moment.locale(locale); // for moment.js ------------------- only works after refresh
    this.translate.use(locale); //rest of the app
}

That's the method invoked when a language is selected from the drop down, but dates rendered by moment.js are not updated but until page refresh.

Is there a way to do this? Hack? Workaround?

Thanks


问:
Laravel routing for deleting one record
I'm new to Laravel (but not developing) and am following along in the free Laravel 6 from Scratch course at Laracasts. I can't afford to subscribe to Laracasts so I can't ask questions there.

I've been following along as the instructor build an app that listed a bunch of articles, displayed a single article, created and saved a new article, and edited an existing article and saved it back to the database. Now I'm trying to delete an individual record but I can't quite get it right.

On the page where I display a single record, I give the user the option of editing the record or of deleting the record via two separate links. The Edit process works fine: it displays the record, allows me to change it (assuming I pass the validations), and then saves it to the database correctly.

The delete process fails. Since I am already displaying the record to the user and have presumably satisfied themselves that it IS the record they want to delete, I want to simply go to the destroy() method of my controller. But I'm obviously doing it wrong. I think the code in the controller is correct so it may be the routes that are messed up. The course doesn't show you how to do a delete and of the videos and stack overflow articles I've seen use different techniques, none of which I fully understand. I'm hoping someone can tell me what I'm doing wrong. There can't be more than 1 or 2 lines that are wrong....

Here's the message I get when I click on the Delete button when I am displaying Article #6:

```<code>Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/articles/6/delete
</code>```

Here's my routing:

```<code>Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy');
</code>```

Here's the page that displays the article and let's the user click Edit or Delete links:

```<code>@extends ('layout');

@section ('content');

<div id="wrapper">
<div id="page" class="container">
    <div id="content">
        <div class="title">
            <h2>{{ $article->title }}</h2>
            <span class="byline">{{ $article->author}}</span></div>
        <p><img src="{{ $article->photopath}}" alt="" class="image image-full" /> </p>
        <p>{{ $article->body }}
        <p><a class="article-link" href="/articles/{{ $article->id }}/edit">Edit This Article</a>
        <a class="article-link" href="/articles/{{ $article->id }}/delete">Delete This Article</a></p>
    </div>
</div>
</div>
@endsection
</code>```

Lastly, here's my ArticlesController:

```<code><?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->paginate(2);
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

public function create()
{
    return view('articles.create');
}

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/'.$article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function delete(Article $article)
{
    return view('articles.delete', ['article' => $article]);
}

public function destroy(Article $article)
{
    $article = Article::find($article->id);
    $article->delete();
    return redirect('/articles');
}
}
</code>```

答:
Facade\Ignition\Exceptions\ViewException Route [article.destroy] not defined. (View: C:\Laravel\proj01\resources\views\articles\show.blade.php)

Make sure you have your routes named

when you use anything like : route('some.route.name') there should be a route named accordingly.

In your web i don't see that you named your routes.

Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy')->name('article.destroy');
```

Notice the ->name('article.destroy');

Title: Laravel routing for deleting one record

Body:
I'm new to Laravel (but not developing) and am following along in the free Laravel 6 from Scratch course at Laracasts. I can't afford to subscribe to Laracasts so I can't ask questions there.

I've been following along as the instructor build an app that listed a bunch of articles, displayed a single article, created and saved a new article, and edited an existing article and saved it back to the database. Now I'm trying to delete an individual record but I can't quite get it right.

On the page where I display a single record, I give the user the option of editing the record or of deleting the record via two separate links. The Edit process works fine: it displays the record, allows me to change it (assuming I pass the validations), and then saves it to the database correctly.

The delete process fails. Since I am already displaying the record to the user and have presumably satisfied themselves that it IS the record they want to delete, I want to simply go to the destroy() method of my controller. But I'm obviously doing it wrong. I think the code in the controller is correct so it may be the routes that are messed up. The course doesn't show you how to do a delete and of the videos and stack overflow articles I've seen use different techniques, none of which I fully understand. I'm hoping someone can tell me what I'm doing wrong. There can't be more than 1 or 2 lines that are wrong....

Here's the message I get when I click on the Delete button when I am displaying Article #6:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/articles/6/delete

Here's my routing:

Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy');

Here's the page that displays the article and let's the user click Edit or Delete links:

@extends ('layout');

@section ('content');

{{ $article->title }}

            {{ $article->author}}

photopath}}" alt="" class="image image-full" />

{{ $article->body }}

id }}/edit">Edit This Article
        id }}/delete">Delete This Article

@endsection

Lastly, here's my ArticlesController:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->paginate(2);
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

public function create()
{
    return view('articles.create');
}

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/'.$article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function delete(Article $article)
{
    return view('articles.delete', ['article' => $article]);
}

public function destroy(Article $article)
{
    $article = Article::find($article->id);
    $article->delete();
    return redirect('/articles');
}
}

Body:
Facade\Ignition\Exceptions\ViewException Route [article.destroy] not defined. (View: C:\Laravel\proj01\resources\views\articles\show.blade.php)

Make sure you have your routes named

when you use anything like : route('some.route.name') there should be a route named accordingly.

In your web i don't see that you named your routes.

Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy')->name('article.destroy');

Notice the ->name('article.destroy');


问:
How do I deploy nuget packages in Travis CI?
I have a nuget package that runs Travis CI for its builds.  Here is my yml:

```<code>language: csharp
solution: TreasureGen.sln
install:
  - nuget restore TreasureGen.sln
  - nuget install NUnit.Runners -OutputDirectory testrunner
script:
  - xbuild TreasureGen.sln /p:TargetFrameworkVersion="v4.5" /p:Configuration=Stress
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Unit/bin/Stress/TreasureGen.Tests.Unit.dll
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Integration.IoC/bin/Stress/TreasureGen.Tests.Integration.IoC.dll
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Integration.Tables/bin/Stress/TreasureGen.Tests.Integration.Tables.dll
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Integration.Stress/bin/Stress/TreasureGen.Tests.Integration.Stress.dll
</code>```

Ideally, when this runs on the master branch, if it is successful, it would then deploy the nuget packages as needed.  There are already Nuget projects in the solution, which contain Package.nuspec and NuGet.config files for each package.  I have tried getting it to deploy myself and have not had much success - typically I run into problems with the authentication, but not exclusively.  I was wondering if anyone here has deployed nuget packages like this in Travis and how they did it.

答:
I was trying to solve the .travis.yml problem with an aspnetcore web site.  The dotnet CLI now supports commands for nuget push and executing unit testing.  I also determined that the approach of having .travis.yml just call an external bash script makes things a like lot easier:

.travis.yml

```<code>language: csharp
solution: ./SolutionName.sln
mono: none
dotnet: 3.1
script:
- chmod +x ./deploy.sh
- ./deploy.sh
</code>```

deploy.sh

```<code>#!/bin/bash
set -ev

dotnet build -c $BUILD_CONFIG ./SolutionName.sln

if [ $? -eq 0 ]
then
        if [ "$BUILD_CONFIG" = "debug" ];
        then
                dotnet test ./TestProject/TestProject.csproj -v normal --no-build
        else
                echo Skip testing on non-debug build
        fi
fi

if [ $? -eq 0 ]
then
        if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_BRANCH}" = "master" ];
        then
                dotnet nuget push ./NugetProject/bin/$BUILD_CONFIG/NugetProject.*.nupkg --api-key $NUGET_API_KEY --source $NUGET_SOURCE --skip-duplicate
        else
                echo Skip nuget for non-master build
        fi
fi
</code>```

Hope this helps someone using .NET Core 2.2 and higher.

Body:
I have a nuget package that runs Travis CI for its builds.  Here is my yml:

language: csharp
solution: TreasureGen.sln
install:
  - nuget restore TreasureGen.sln
  - nuget install NUnit.Runners -OutputDirectory testrunner
script:
  - xbuild TreasureGen.sln /p:TargetFrameworkVersion="v4.5" /p:Configuration=Stress
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Unit/bin/Stress/TreasureGen.Tests.Unit.dll
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Integration.IoC/bin/Stress/TreasureGen.Tests.Integration.IoC.dll
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Integration.Tables/bin/Stress/TreasureGen.Tests.Integration.Tables.dll
  - mono ./testrunner/NUnit.ConsoleRunner.*/tools/nunit3-console.exe ./TreasureGen.Tests.Integration.Stress/bin/Stress/TreasureGen.Tests.Integration.Stress.dll

Ideally, when this runs on the master branch, if it is successful, it would then deploy the nuget packages as needed.  There are already Nuget projects in the solution, which contain Package.nuspec and NuGet.config files for each package.  I have tried getting it to deploy myself and have not had much success - typically I run into problems with the authentication, but not exclusively.  I was wondering if anyone here has deployed nuget packages like this in Travis and how they did it.

Body:
I was trying to solve the .travis.yml problem with an aspnetcore web site.  The dotnet CLI now supports commands for nuget push and executing unit testing.  I also determined that the approach of having .travis.yml just call an external bash script makes things a like lot easier:

.travis.yml

language: csharp
solution: ./SolutionName.sln
mono: none
dotnet: 3.1
script:
- chmod +x ./deploy.sh
- ./deploy.sh

deploy.sh

#!/bin/bash
set -ev

dotnet build -c $BUILD_CONFIG ./SolutionName.sln

if [ $? -eq 0 ]
then
        if [ "$BUILD_CONFIG" = "debug" ];
        then
                dotnet test ./TestProject/TestProject.csproj -v normal --no-build
        else
                echo Skip testing on non-debug build
        fi
fi

if [ $? -eq 0 ]
then
        if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_BRANCH}" = "master" ];
        then
                dotnet nuget push ./NugetProject/bin/$BUILD_CONFIG/NugetProject.*.nupkg --api-key $NUGET_API_KEY --source $NUGET_SOURCE --skip-duplicate
        else
                echo Skip nuget for non-master build
        fi
fi

Hope this helps someone using .NET Core 2.2 and higher.


问:
How do logical && and || operators along with increment and decrement work?
Evaluate the following expressions. Find x,y,z values in each case. Assuming x=1 and y=5 initially, what do you observe:

z=++x && ++y;

z=--x && --y;

z=++x || ++y;

z=--x || --y;

How are logical operators affecting the values?

答:
I believe "what do you observe" is very explicit in that you should see something. That almost certainly means writing the code and examining what happens.

In any case, the logical operators treat 0 as false, anything else as true. The output of those operators is 0 for false and 1 for true.

Also keep in mind that the pre-increment and -decrement operators change the value before use.

And, finally, be aware that && and || are short-circuiting operators which means the second sub-expression may not always be evaluated. For example:

```<code>int x = 1 ; int y = 5 ; int z = --x && --y;
</code>```

will leave y equal to 5, because the --x is zero/false so we know that the whole expression will be false - there's no need to evaluate the second sub-expression.

That should be enough to figure out what the results are, based on your pre-conditions for x and y.

As a hint, let's look at the first one. ++x and ++y will be 2 and 6 respectively so both true. Hence true && true will give true, ending up as 1.

And now, since you have written some code (as per your comment asking about what you considered strange behaviour of the -- and ++ operators in some cases), here's my sample code which shows the operations:

```<code>#include <stdio.h>

int main() {
    int x, y, z;

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=++x && ++y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=--x && --y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=++x || ++y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=--x || --y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

   return 0;
}
</code>```

The output of that is:

```<code>oldx = 1, oldy= 5, newx= 2, newy = 6, z = 1
oldx = 1, oldy= 5, newx= 0, newy = 5, z = 0
oldx = 1, oldy= 5, newx= 2, newy = 5, z = 1
oldx = 1, oldy= 5, newx= 0, newy = 4, z = 1
</code>```

Body:
I believe "what do you observe" is very explicit in that you should see something. That almost certainly means writing the code and examining what happens.

In any case, the logical operators treat 0 as false, anything else as true. The output of those operators is 0 for false and 1 for true.

Also keep in mind that the pre-increment and -decrement operators change the value before use.

And, finally, be aware that && and || are short-circuiting operators which means the second sub-expression may not always be evaluated. For example:

int x = 1 ; int y = 5 ; int z = --x && --y;

will leave y equal to 5, because the --x is zero/false so we know that the whole expression will be false - there's no need to evaluate the second sub-expression.

That should be enough to figure out what the results are, based on your pre-conditions for x and y.

As a hint, let's look at the first one. ++x and ++y will be 2 and 6 respectively so both true. Hence true && true will give true, ending up as 1.

And now, since you have written some code (as per your comment asking about what you considered strange behaviour of the -- and ++ operators in some cases), here's my sample code which shows the operations:

#include <stdio.h>

int main() {
    int x, y, z;

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=++x && ++y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=--x && --y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=++x || ++y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=--x || --y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

   return 0;
}

The output of that is:

oldx = 1, oldy= 5, newx= 2, newy = 6, z = 1
oldx = 1, oldy= 5, newx= 0, newy = 5, z = 0
oldx = 1, oldy= 5, newx= 2, newy = 5, z = 1
oldx = 1, oldy= 5, newx= 0, newy = 4, z = 1


问:
Auth login is not working for new users in laravel 6
Auth login is not working for the new users in laravel 6 socialite. but the user data is saved in a database. I mean to say When a new user tries to register using laravel socialite(Twitter, Facebook), he/she not auto-login but data saved in the database. I want the user to auto login when he/she register using socialites.   </p>

```<code>class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;

public function __construct()
{
 //   $this->middleware('guest')->except('logout');
}

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function handleProviderCallback($provider)
{
 try {
    $social_user = Socialite::driver($provider)->user();
    $authuser = $this->findOrCreateUser($social_user,$provider);

    Auth::login($authuser,true);
    return redirect('/');
  } catch(\Exception $e){

   return redirect('/');
}

}
public function findOrCreateUser($social_user,$provider){

    $authuser = SocialProvider::where('provider_id', $social_user->id)->first();

    if(!$authuser){

          $username = slugify($social_user->getName())."-".mt_rand(10000, 99999);
          $password = rand(1000000000, 99999999999);

          $user = User::firstOrCreate(['email' => $social_user->getEmail()],
          [
              'username'=> $username,
              'name'=> $social_user->getName(),
              'picture'=> $social_user->getAvatar(),
              'password' => Hash::make($password),
              'ip_address'=> get_user_ip(),
          ]);

      $user->socialProviders()->create(

        ['provider_id'=>$social_user->getId(), 'provider'=>$provider]

      );
      return $user;

    }else{

      $user_id = $authuser->user_id;

      $userdata = Constant_model::getDataOneColumn('users',"id",$user_id);

      $user = User::firstOrCreate(['email'=> $userdata[0]->email],
        ['ip_address'=> $userdata[0]->ip_address,
        'username'=> $userdata[0]->username,
        'name'=> $userdata[0]->name,
        'picture'=> $userdata[0]->picture,
        ],

    );

      return $user;

    }
}

public function logout(){

  Auth::logout();
  return redirect('/');
}

}
</code>```

答:
Try this. Reference https://www.tutsmake.com/laravel-6-facebook-login-tutorial-example</p>

```<code>public function redirect($provider)
 {
     return Socialite::driver($provider)->redirect();
 }

 public function callback($provider)
 {
   $getInfo = Socialite::driver($provider)->user();
   $user = $this->createUser($getInfo,$provider);
   auth()->login($user);
   return redirect()->to('/home');
 }

 public function createUser($getInfo,$provider)
 {
   $user = User::where('provider_id', $getInfo->id)->first();
   if (!$user) {
      $user = User::create([
         'name'     => $getInfo->name,
         'email'    => $getInfo->email,
         'provider' => $provider,
         'provider_id' => $getInfo->id
     ]);
   }
   return $user;
 }
</code>```

Body:
Auth login is not working for the new users in laravel 6 socialite. but the user data is saved in a database. I mean to say When a new user tries to register using laravel socialite(Twitter, Facebook), he/she not auto-login but data saved in the database. I want the user to auto login when he/she register using socialites.

class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;

public function __construct()
{
 //   $this->middleware('guest')->except('logout');
}

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function handleProviderCallback($provider)
{
 try {
    $social_user = Socialite::driver($provider)->user();
    $authuser = $this->findOrCreateUser($social_user,$provider);

    Auth::login($authuser,true);
    return redirect('/');
  } catch(\Exception $e){

   return redirect('/');
}

}
public function findOrCreateUser($social_user,$provider){

    $authuser = SocialProvider::where('provider_id', $social_user->id)->first();

    if(!$authuser){

          $username = slugify($social_user->getName())."-".mt_rand(10000, 99999);
          $password = rand(1000000000, 99999999999);

          $user = User::firstOrCreate(['email' => $social_user->getEmail()],
          [
              'username'=> $username,
              'name'=> $social_user->getName(),
              'picture'=> $social_user->getAvatar(),
              'password' => Hash::make($password),
              'ip_address'=> get_user_ip(),
          ]);

      $user->socialProviders()->create(

        ['provider_id'=>$social_user->getId(), 'provider'=>$provider]

      );
      return $user;

    }else{

      $user_id = $authuser->user_id;

      $userdata = Constant_model::getDataOneColumn('users',"id",$user_id);

      $user = User::firstOrCreate(['email'=> $userdata[0]->email],
        ['ip_address'=> $userdata[0]->ip_address,
        'username'=> $userdata[0]->username,
        'name'=> $userdata[0]->name,
        'picture'=> $userdata[0]->picture,
        ],

    );

      return $user;

    }
}

public function logout(){

  Auth::logout();
  return redirect('/');
}

}

Body:
Try this. Reference https://www.tutsmake.com/laravel-6-facebook-login-tutorial-example

public function redirect($provider)
 {
     return Socialite::driver($provider)->redirect();
 }

 public function callback($provider)
 {
   $getInfo = Socialite::driver($provider)->user();
   $user = $this->createUser($getInfo,$provider);
   auth()->login($user);
   return redirect()->to('/home');
 }

 public function createUser($getInfo,$provider)
 {
   $user = User::where('provider_id', $getInfo->id)->first();
   if (!$user) {
      $user = User::create([
         'name'     => $getInfo->name,
         'email'    => $getInfo->email,
         'provider' => $provider,
         'provider_id' => $getInfo->id
     ]);
   }
   return $user;
 }


问:
Perl array vs list
I have two data structures in Perl:

An array:

```<code>my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}
</code>```

Giving me the following output:

```<code>1
2
3
</code>```

And a list:

```<code>my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}
</code>```

Giving the following output:

```<code>ARRAY(0x9c90818)
</code>```

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

答:
The square brackets create an anonymous array, populate the array with the contents of the brackets, and return a reference to that array. In other words,

```<code>[ "1", "2", "3" ]
</code>```

is basically the same as

```<code>do { my @anon = ("1", "2", "3"); \@anon }
</code>```

So the code should look like

```<code>my $array_ref = [ "1", "2", "3" ];

for (@$array_ref) {  # Short for @{ $array_ref }
    print "$_\n";
}
</code>```

or

```<code>my @array_of_refs = ([ "1", "2", "3" ]);

for my $array_ref (@array_of_refs) {
    for (@$array_ref) {
        print "$_\n";
    }
}
</code>```

Title: Perl array vs list

Body:
I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

Giving me the following output:

1
2
3

And a list:

my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}

Giving the following output:

ARRAY(0x9c90818)

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

Body:
The square brackets create an anonymous array, populate the array with the contents of the brackets, and return a reference to that array. In other words,

[ "1", "2", "3" ]

is basically the same as

do { my @anon = ("1", "2", "3"); \@anon }

So the code should look like

my $array_ref = [ "1", "2", "3" ];

for (@$array_ref) {  # Short for @{ $array_ref }
    print "$_\n";
}

or

my @array_of_refs = ([ "1", "2", "3" ]);

for my $array_ref (@array_of_refs) {
    for (@$array_ref) {
        print "$_\n";
    }
}