问:
Android Activity lifecycle issue
I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.

For that I used the following Code

```<code> public void onClick(View v) {
     Intent intent = new Intent(this, Cart.class);
     startActivity(intent);
 }
</code>```

In Cart activity when I press a button it comes to activity Home.

For That

```<code> public void onClick(View v) {
     Intent intent = new Intent(this, Home.class);
     startActivity(intent);
 }
</code>```

Activities are changing fine but the onCreate method calls every time the activity starts.

Is that a fine life cycle of Activity or not? If not, how can I solve this?

答:
No, I think that the cycle isn't correct in this case.

With this design, you may end up with a stack of activities which grows constantly, eg: Home -> Cart -> Home -> Cart -> Home -> Cart -> etc...

Pressing the Back button will then cycle back through each item in this stack.

I don't think that's what you want. If the user is at Home, then goes into the Cart, he's likely to press Back to go back to Home. Now the stack only contains Home, pressing Back again will exit, which sounds correct. And given the snippet that you show, I think that the exact same thing should happen when the use presses this button that you mention in Cart.

So, you need to call finish() in Cart, in order to go back to Home. You shouldn't rely on onSaveInstanceState() for restoring the contents of the cart. You could for example use an SQLite database for this.

onCreate() will be called whenever the Cart is launched, but it will only be called once in Home.

But the real thing is that you shouldn't even have that button to go back from the Cart to Home. This is maybe how one does things on iOS, but on Android, we have the Back button for this, users know it, use it, and there's no need for replicating this button on the screen.

Title: Android Activity lifecycle issue

Body:
I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.

For that I used the following Code

 public void onClick(View v) {
     Intent intent = new Intent(this, Cart.class);
     startActivity(intent);
 }

In Cart activity when I press a button it comes to activity Home.

For That

 public void onClick(View v) {
     Intent intent = new Intent(this, Home.class);
     startActivity(intent);
 }

Activities are changing fine but the onCreate method calls every time the activity starts.

Is that a fine life cycle of Activity or not? If not, how can I solve this?


来源: stackexchange

问:
Value of CheckBox not posted to model
I have a page which contains a matrix where a user is linked to different skills.
This is displayed as a page containing checkboxes.
What I would like is to save only the rows that have actually changed.
Therefor I added an "IsChanged" property which gets set to "true" when a user changes the value for a checkbox.

I have the following code:

```<code>@for (var i = 0; i < Model.EmployeeList.Count; i++)
{
    <input type="hidden" asp-for="EmployeeList[i].Id" />
    <input type="checkbox" asp-for="EmployeeList[i].IsChanged" name="IsChanged" id="IsChanged_@Model.EmployeeList[i].Id" />

    <tr>
        <th scope="row">@Model.EmployeeList[i].Name @Model.EmployeeList[i].Surname</th>
        <th scope="row">
            @Model.EmployeeList[i].Location
        </th>
    @for (var j = 0; j < Model.EmployeeList[i].SelectedSkillList.Count; j++)
    {
        <td>
            <label class="label">
                <input asp-for="EmployeeList[i].SelectedSkillList[j].IsSelected" data-changedHidden="IsChanged_@Model.EmployeeList[i].Id" type="checkbox" class="label__checkbox" />
                <span class="label__text">
                    <span class="label__check">
                        <i class="fa fa-check icon"></i>
                    </span>
                </span>
            </label>

            @Html.HiddenFor(x => Model.EmployeeList[i].SelectedSkillList[j].Prefix)
        </td>
    }
    </tr>
}
</code>```

When I check one of the other checkboxes wihtin the @for, the checkbox EmployeeList[i].IsChanged for the given row is checked.
This works fine and I can see that happening on my page.

However when I save the post the data, the value for the IsChanged-checkbox, doesn't get included in the post. It always remains false.

Where did I make a mistake?
Can anyone help me?

```<code><input type="checkbox" name="IsChanged" id="IsChanged_1" data-val="true" data-val-required="The IsChanged field is required." value="true">
<input name="EmployeeList[0].IsChanged" type="hidden" value="false">
</code>```

This is the model :

```<code>        public List<Core.Employee> EmployeeList { get; set; }

    public IEnumerable<MachineTypeSpecs> MachineTypeList { get; set; }

    public CompetenceMatrixModel(IEmployeeData employeeData, IMachineTypeSpecs machineTypeSpecs)
    {
        this._employeeData = employeeData;
        this._machineTypeSpecs = machineTypeSpecs;
    }
</code>```

The Core.Employee contains the IsChanged property.

答: Ok stupid me, removing the name corrected the problem. Thanks to @Craig H</p>

ContentLicense: CC BY-SA 4.0

Title: Value of CheckBox not posted to model

Body:
I have a page which contains a matrix where a user is linked to different skills.
This is displayed as a page containing checkboxes.
What I would like is to save only the rows that have actually changed.
Therefor I added an "IsChanged" property which gets set to "true" when a user changes the value for a checkbox.

I have the following code:

@for (var i = 0; i < Model.EmployeeList.Count; i++)
{
    <input type="hidden" asp-for="EmployeeList[i].Id" />
    <input type="checkbox" asp-for="EmployeeList[i].IsChanged" name="IsChanged" id="IsChanged_@Model.EmployeeList[i].Id" />

        @Model.EmployeeList[i].Name @Model.EmployeeList[i].Surname

            @Model.EmployeeList[i].Location

    @for (var j = 0; j < Model.EmployeeList[i].SelectedSkillList.Count; j++)
    {

                <input asp-for="EmployeeList[i].SelectedSkillList[j].IsSelected" data-changedHidden="IsChanged_@Model.EmployeeList[i].Id" type="checkbox" class="label__checkbox" />

            @Html.HiddenFor(x => Model.EmployeeList[i].SelectedSkillList[j].Prefix)

    }

}

When I check one of the other checkboxes wihtin the @for, the checkbox EmployeeList[i].IsChanged for the given row is checked.
This works fine and I can see that happening on my page.

However when I save the post the data, the value for the IsChanged-checkbox, doesn't get included in the post. It always remains false.

Where did I make a mistake?
Can anyone help me?

<input type="checkbox" name="IsChanged" id="IsChanged_1" data-val="true" data-val-required="The IsChanged field is required." value="true">
<input name="EmployeeList[0].IsChanged" type="hidden" value="false">

This is the model :

        public List<Core.Employee> EmployeeList { get; set; }

    public IEnumerable<MachineTypeSpecs> MachineTypeList { get; set; }

    public CompetenceMatrixModel(IEmployeeData employeeData, IMachineTypeSpecs machineTypeSpecs)
    {
        this._employeeData = employeeData;
        this._machineTypeSpecs = machineTypeSpecs;
    }

The Core.Employee contains the IsChanged property.


问:
Text on spinner is white on a white background
The text on my spinners is white, and I have no idea why.

This is my xml, nothing special

```<code> <Spinner
     android:id="@+id/spinner_date"
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:layout_weight="1" />
</code>```

And my code

```<code>dateSpinner = (Spinner) findViewById(R.id.spinner_date);
selectedDate = calendar.getTime();
List<String> list = new ArrayList<String>();
list.add(formatter.format(selectedDate));
dateAdapter = new ArrayAdapter<String>(mContext,
            android.R.layout.simple_spinner_item, list);
dateSpinner.setAdapter(dateAdapter);
</code>```

What could be the reason that my text is displayed in white?

EDIT:
I've found the reason, I replaced the mContext parameter which was set in my onCreate.

```<code>mContext = getApplicationContext();
</code>```

Now I use d

```<code>ateAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
</code>```

and it works.

答:
I've changed the text color of that spinner's textview without creating a new layout. I know it's been a long time but it's what worked for me, just thought of sharing it. Best part is you can use it on any default adapter.

Here's the code : (this for Activity & requireActivity for Fragments)

1) Java

```<code>arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,groups){
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView listItem = view.findViewById(android.R.id.text1);
            listItem.setTextColor(Color.WHITE);
            listItem.setTextSize(20);
            listItem.setElevation(18);
            return view;
        }
    };
</code>```

2) Kotlin

```<code>arrayAdapter = object : ArrayAdapter<String>(requireActivity(), android.R.layout.simple_spinner_item, spinnerCategoriesList) {
        override fun getView(position: Int, @Nullable convertView: View?, parent: ViewGroup): View {
            val view = super.getView(position, convertView, parent)
            val listItem = view.findViewById<TextView>(android.R.id.text1)
            listItem.setTextColor(Color.BLACK)
            listItem.textSize = 16f
            return view
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The text on my spinners is white, and I have no idea why.

This is my xml, nothing special

 <Spinner
     android:id="@+id/spinner_date"
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:layout_weight="1" />

And my code

dateSpinner = (Spinner) findViewById(R.id.spinner_date);
selectedDate = calendar.getTime();
List<String> list = new ArrayList<String>();
list.add(formatter.format(selectedDate));
dateAdapter = new ArrayAdapter<String>(mContext,
            android.R.layout.simple_spinner_item, list);
dateSpinner.setAdapter(dateAdapter);

What could be the reason that my text is displayed in white?

EDIT:
I've found the reason, I replaced the mContext parameter which was set in my onCreate.

mContext = getApplicationContext();

Now I use d

ateAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);

and it works.

Body:
I've changed the text color of that spinner's textview without creating a new layout. I know it's been a long time but it's what worked for me, just thought of sharing it. Best part is you can use it on any default adapter.

Here's the code : (this for Activity & requireActivity for Fragments)

1) Java

arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,groups){
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView listItem = view.findViewById(android.R.id.text1);
            listItem.setTextColor(Color.WHITE);
            listItem.setTextSize(20);
            listItem.setElevation(18);
            return view;
        }
    };

2) Kotlin

arrayAdapter = object : ArrayAdapter<String>(requireActivity(), android.R.layout.simple_spinner_item, spinnerCategoriesList) {
        override fun getView(position: Int, @Nullable convertView: View?, parent: ViewGroup): View {
            val view = super.getView(position, convertView, parent)
            val listItem = view.findViewById<TextView>(android.R.id.text1)
            listItem.setTextColor(Color.BLACK)
            listItem.textSize = 16f
            return view
        }
    }


问:
Valgrind reporting an invalid read (and write) but the program keeps his execution
I'm trying to solve one of my excercise for an university exam but I'm stuck with a memory error that I can't really figure it out.
I have to alloc and inizialise a matrix of float having as matrix a struct called Mat.

```<code>typedef struct {
  int rows;
  int cols;
  float **row_ptrs;
} Mat;
</code>```

To do so I have to write a function who returns the address of the matrix. The matrix has to be an array of pointer to the rows of the matrix:

```<code>Mat* Mat_alloc(int rows, int cols){
        Mat* matrice = (Mat*)calloc(rows,sizeof(float**));
        float** righe = (float**)calloc(cols,sizeof(float*));
        (*matrice).row_ptrs=righe;
        (*matrice).rows=rows;
        (*matrice).cols=cols;
        *righe = (float*)malloc(sizeof(float));
        float* elem = *righe;
        Mat* sav_ptr = matrice;
        int i,j;
        for(i=0;i<rows;i++){
            printf("questa e' la riga: %d con indirizzo: %x\n\n",i,righe);
            for(j=0;j<cols;j++){
                *elem = 0.0;
                printf("%f io sono l'elemento: %d con indirizzo: %x \n",*elem,j,elem);
                elem++;
                }
            printf("\n");
            righe++;
            j=0;
            }
        return sav_ptr;
    }
</code>```

Also i have to free everything after the function is called and runned, I've wrote this function to do it:

```<code>void Mat_free(Mat *m){
    float** tofree = (*m).row_ptrs;
    free(*tofree);
    free(tofree);
    free(m);
    }
</code>```

When I run the program under valgrind after the first print output i get this:

```<code>==6688== Memcheck, a memory error detector
==6688== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6688== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==6688== Command: ./e1
==6688==
Avvio Mat_alloc...

questa e' la riga: 0 con indirizzo: 4a4c4f0

0.000000 io sono l'elemento: 0 con indirizzo: 4a4c560
==6688== Invalid write of size 4
==6688==    at 0x109311: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==  Address 0x4a4c564 is 0 bytes after a block of size 4 alloc'd
==6688==    at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==6688==    by 0x1092BC: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==
==6688== Invalid read of size 4
==6688==    at 0x109319: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==  Address 0x4a4c564 is 0 bytes after a block of size 4 alloc'd
==6688==    at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==6688==    by 0x1092BC: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==
</code>```

But then I do not get a sigsegv signal and the program keeps on running. What am I getting wrong? I found this even weirder because the free doesn't generate any error and all the block are free'd. Do you guys have any suggestion?

Her's the main function:

```<code>int main(int argc, char **argv) {
      /********************************************************
       *             TEST Mat_alloc/Mat_read                  *
       ********************************************************/
      printf("Avvio Mat_alloc...\n\n");
      Mat *m1 = Mat_alloc(5,5);
      float** try = (*m1).row_ptrs;
      printf("%f\n",**try);
      printf("fatto alloc\n");
      Mat_free(m1);
      printf("fatto free\n");

      return 0;
    }
</code>```

答:
You should allocate memory for mat struct, because you return pointer to that struct.

Try this:

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

typedef struct {
    int rows;
    int cols;
    float **arr;
} Mat;

Mat* Mat_alloc(int rows, int cols){
    // memory allocation for struct Mat
    Mat* matrice = (Mat*)malloc(sizeof(Mat));
    // memory allocation for a given number of rows of our two-dimensional array
    matrice->arr = (float **)malloc(rows * sizeof(float *));
    int i = 0; int j = 0;
    // each row is a one-dimensional array, so we must allocate memory for each element
    for (i = 0; i < rows; ++i)
        matrice->arr[i] = (float *)malloc(cols * sizeof(float));

    (*matrice).rows=rows;
    (*matrice).cols=cols;

    for(i=0;i<rows; ++i){
        printf("questa e' la riga: %d con indirizzo: %p\n\n",i,&matrice->arr[i]);
        for(j=0;j<cols; ++j){
            matrice->arr[i][j] = j;
            printf("%f io sono l'elemento: %d con indirizzo: %p \n",matrice->arr[i][j],j,&matrice->arr[i][j]);
        }
        printf("\n");
    }
    return matrice;
}

void Mat_free(Mat *m){
    int i = 0;
    for(i=0;i< m->rows; ++i) {
        free(m->arr[i]);
    }

    free(m->arr);
    free(m);
}

int main(int argc, char **argv) {
    /********************************************************
     *             TEST Mat_alloc/Mat_read                  *
     ********************************************************/
    printf("Avvio Mat_alloc...\n\n");
    Mat *m1 = Mat_alloc(3,3);
    printf("fatto alloc\n");
    Mat_free(m1);
    printf("fatto free\n");

    return 0;
}
</code>```

Body:
I'm trying to solve one of my excercise for an university exam but I'm stuck with a memory error that I can't really figure it out.
I have to alloc and inizialise a matrix of float having as matrix a struct called Mat.

typedef struct {
  int rows;
  int cols;
  float **row_ptrs;
} Mat;

To do so I have to write a function who returns the address of the matrix. The matrix has to be an array of pointer to the rows of the matrix:

Mat* Mat_alloc(int rows, int cols){
        Mat* matrice = (Mat*)calloc(rows,sizeof(float**));
        float** righe = (float**)calloc(cols,sizeof(float*));
        (*matrice).row_ptrs=righe;
        (*matrice).rows=rows;
        (*matrice).cols=cols;
        *righe = (float*)malloc(sizeof(float));
        float* elem = *righe;
        Mat* sav_ptr = matrice;
        int i,j;
        for(i=0;i<rows;i++){
            printf("questa e' la riga: %d con indirizzo: %x\n\n",i,righe);
            for(j=0;j<cols;j++){
                *elem = 0.0;
                printf("%f io sono l'elemento: %d con indirizzo: %x \n",*elem,j,elem);
                elem++;
                }
            printf("\n");
            righe++;
            j=0;
            }
        return sav_ptr;
    }

Also i have to free everything after the function is called and runned, I've wrote this function to do it:

void Mat_free(Mat *m){
    float** tofree = (*m).row_ptrs;
    free(*tofree);
    free(tofree);
    free(m);
    }

When I run the program under valgrind after the first print output i get this:

==6688== Memcheck, a memory error detector
==6688== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6688== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==6688== Command: ./e1
==6688==
Avvio Mat_alloc...

questa e' la riga: 0 con indirizzo: 4a4c4f0

0.000000 io sono l'elemento: 0 con indirizzo: 4a4c560
==6688== Invalid write of size 4
==6688==    at 0x109311: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==  Address 0x4a4c564 is 0 bytes after a block of size 4 alloc'd
==6688==    at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==6688==    by 0x1092BC: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==
==6688== Invalid read of size 4
==6688==    at 0x109319: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==  Address 0x4a4c564 is 0 bytes after a block of size 4 alloc'd
==6688==    at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==6688==    by 0x1092BC: Mat_alloc (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==    by 0x1091FE: main (in /home/sam/Scrivania/esercitazione 4 TDP/e1)
==6688==

But then I do not get a sigsegv signal and the program keeps on running. What am I getting wrong? I found this even weirder because the free doesn't generate any error and all the block are free'd. Do you guys have any suggestion?

Her's the main function:

int main(int argc, char **argv) {
      /********************************************************
       *             TEST Mat_alloc/Mat_read                  *
       ********************************************************/
      printf("Avvio Mat_alloc...\n\n");
      Mat *m1 = Mat_alloc(5,5);
      float** try = (*m1).row_ptrs;
      printf("%f\n",**try);
      printf("fatto alloc\n");
      Mat_free(m1);
      printf("fatto free\n");

      return 0;
    }

Body:
You should allocate memory for mat struct, because you return pointer to that struct.

Try this:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    int rows;
    int cols;
    float **arr;
} Mat;

Mat* Mat_alloc(int rows, int cols){
    // memory allocation for struct Mat
    Mat* matrice = (Mat*)malloc(sizeof(Mat));
    // memory allocation for a given number of rows of our two-dimensional array
    matrice->arr = (float **)malloc(rows * sizeof(float *));
    int i = 0; int j = 0;
    // each row is a one-dimensional array, so we must allocate memory for each element
    for (i = 0; i < rows; ++i)
        matrice->arr[i] = (float *)malloc(cols * sizeof(float));

    (*matrice).rows=rows;
    (*matrice).cols=cols;

    for(i=0;i<rows; ++i){
        printf("questa e' la riga: %d con indirizzo: %p\n\n",i,&matrice->arr[i]);
        for(j=0;j<cols; ++j){
            matrice->arr[i][j] = j;
            printf("%f io sono l'elemento: %d con indirizzo: %p \n",matrice->arr[i][j],j,&matrice->arr[i][j]);
        }
        printf("\n");
    }
    return matrice;
}

void Mat_free(Mat *m){
    int i = 0;
    for(i=0;i< m->rows; ++i) {
        free(m->arr[i]);
    }

    free(m->arr);
    free(m);
}

int main(int argc, char **argv) {
    /********************************************************
     *             TEST Mat_alloc/Mat_read                  *
     ********************************************************/
    printf("Avvio Mat_alloc...\n\n");
    Mat *m1 = Mat_alloc(3,3);
    printf("fatto alloc\n");
    Mat_free(m1);
    printf("fatto free\n");

    return 0;
}


问:
Difference between v-model and v-bind on Vue.js?
I'm learning Vue with an online course and the instructor gave me an exercise to make an input text with a default value.

I completed it using v-model but, the instructor chose v-bind:value, and I don't understand why.

Can someone give me a simple explanation about the difference between these two and when it's better use each one?

答:
v-model

it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.

v-model is used only for HTML input elements

```<code>ex: <input type="text" v-model="name" >
</code>```

v-bind

it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element.
v-bind is used to bind html attribute

ex:

<input type="text" v-bind:class="abc" v-bind:value="">

```<code><a v-bind:href="home/abc" > click me </a>
</code>```

Body:
v-model

it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.

v-model is used only for HTML input elements

ex: <input type="text" v-model="name" >

v-bind

it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element.
v-bind is used to bind html attribute

ex:

<input type="text" v-bind:class="abc" v-bind:value="">

<a v-bind:href="home/abc" > click me </a>


问:
Laravel - Merged collection different from Eloquent collection?
I am facing a problem with sorting and returning merged collections.

When i do:

```<code>$ads = Ad::where('status',1)->where('deleted_at',NULL)->paginate(30);
</code>```

it works
but when i merge this with another collection like

```<code>$one = Ad::where('status', 1)->get();
$two = Ad::where('status', 2)->get();
$ads = $one->merge($two);
$ads->paginate(30);
</code>```

it tells me that "paginate method does not exist" as well as "orderBy method does not exist"

are those collections different from the single returned ones?

答:
This is because you are returning a collection from $one and $two and then trying to paginate them, which you can not paginate collections, you can only paginate query builder
now to return query builder from $one and $two remove get(),but now you cant usemerge()on query builders, so you can usewhereIn` to return ads where its status in [1,2]
like this:

```<code>$ads= Ad::whereIn('status', [1,2])->paginate(30);
</code>```

Body:
I am facing a problem with sorting and returning merged collections.

When i do:

$ads = Ad::where('status',1)->where('deleted_at',NULL)->paginate(30);

it works
but when i merge this with another collection like

$one = Ad::where('status', 1)->get();
$two = Ad::where('status', 2)->get();
$ads = $one->merge($two);
$ads->paginate(30);

it tells me that "paginate method does not exist" as well as "orderBy method does not exist"

are those collections different from the single returned ones?

Body:
This is because you are returning a collection from $one and $two and then trying to paginate them, which you can not paginate collections, you can only paginate query builder
now to return query builder from $one and $two remove get(),but now you cant usemerge()on query builders, so you can usewhereIn` to return ads where its status in [1,2]
like this:

$ads= Ad::whereIn('status', [1,2])->paginate(30);


问:
Filter rows over partitions
Suppose I have the following table:

```<code>    +-------+------------+
    | nGroup |   Status   |
    +-------+------------+
    |     1 | DONE       |
    |     1 | UNKNOWN    |
    |     1 | DONE       |
    |     2 | INPROGRESS |
    |     2 | INPROGRESS |
    |     2 | DONE       |
    |     3 | INPROGRESS |
    |     3 | DONE       |
    |     3 | DONE       |
    +-------+------------+
</code>```

If a nGroup has one Status to INPROGRESS, then return only the lines of that group containing the status INPROGRESS.

If all the Status of a nGroup are different from INPROGRESS, then return all the status available for that group.

So for this example, I would get the following output:

```<code>+-------+------------+
| nGroup |   Status   |
+-------+------------+
|     1 | DONE       |
|     1 | UNKNOWN    |
|     1 | DONE       |
|     2 | INPROGRESS |
|     2 | INPROGRESS |
|     3 | INPROGRESS |
+-------+------------+
</code>```

I tried the following query :

```<code>SELECT *
FROM dbo.myTable T1
WHERE Status IN (
  CASE WHEN EXISTS( SELECT 1 FROM myTable T2 WHERE T2.STATUS = 'INPROGRESS' AND T1.nGroup = T2.nGroup) THEN 'INPROGRESS'
  ELSE (SELECT Status FROM myTable T2 WHERE T1.nGroup = T2.nGroup)
  END
)
</code>```

But I get the following error when running it :

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

答:
Hmmm . . . I think you want:</p>

```<code>select t.*
from dbo.myTable t
where t.status <> 'INPROGRESS' or
      exists (select 1
              from dbo.myTable t
              where db.myTable = 'INPROGRESS'
             );
</code>```

Title: Filter rows over partitions

Body:
Suppose I have the following table:

    +-------+------------+
    | nGroup |   Status   |
    +-------+------------+
    |     1 | DONE       |
    |     1 | UNKNOWN    |
    |     1 | DONE       |
    |     2 | INPROGRESS |
    |     2 | INPROGRESS |
    |     2 | DONE       |
    |     3 | INPROGRESS |
    |     3 | DONE       |
    |     3 | DONE       |
    +-------+------------+

If a nGroup has one Status to INPROGRESS, then return only the lines of that group containing the status INPROGRESS.

If all the Status of a nGroup are different from INPROGRESS, then return all the status available for that group.

So for this example, I would get the following output:

+-------+------------+
| nGroup |   Status   |
+-------+------------+
|     1 | DONE       |
|     1 | UNKNOWN    |
|     1 | DONE       |
|     2 | INPROGRESS |
|     2 | INPROGRESS |
|     3 | INPROGRESS |
+-------+------------+

I tried the following query :

SELECT *
FROM dbo.myTable T1
WHERE Status IN (
  CASE WHEN EXISTS( SELECT 1 FROM myTable T2 WHERE T2.STATUS = 'INPROGRESS' AND T1.nGroup = T2.nGroup) THEN 'INPROGRESS'
  ELSE (SELECT Status FROM myTable T2 WHERE T1.nGroup = T2.nGroup)
  END
)

But I get the following error when running it :

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

Body:
Hmmm . . . I think you want:

select t.*
from dbo.myTable t
where t.status <> 'INPROGRESS' or
      exists (select 1
              from dbo.myTable t
              where db.myTable = 'INPROGRESS'
             );


问:
IE8 ignoring background "no-repeat" value
I have a page that uses a background image to do rounded corners, and in IE8 on Windows XP the background image repeats.

(Link Dead)

It looks right in other browsers and even in "Compatability View" in IE8.

Does anyone know how to remove the repetion? I'm stumped!

答:
I had the exact same problem. Turns out one of my tags wasn't well formed. i.e. I had

Changed to

 and got rid of the problem in ie8

Body:
I had the exact same problem. Turns out one of my tags wasn't well formed. i.e. I had <a href="xxx"><div></a></div>

Changed to <a href="xxx"><div></div></a> and got rid of the problem in ie8


问:
How to Count data in for loop nodejs
How to Count data in for loop nodejs</p>

```<code>var service_count = 0;
for (let i = 0; i < res.length; i++) {
    service_count += i;
    console.log('service_charge_count: =====> '+service_count);
}
</code>```

答:
Replace i with service_count, then you can change your code with:

```<code>for(let service_count  = 0; service_count  < res.length; service_count ++){
    console.log('service_charge_count: =====> ' + service_count);
}
</code>```

Or I think that you service_count is res.length, therefore, you can do:

```<code>let service_count = res.length;
console.log(service_count);
</code>```

Title: How to Count data in for loop nodejs

Body:
How to Count data in for loop nodejs

var service_count = 0;
for (let i = 0; i < res.length; i++) {
    service_count += i;
    console.log('service_charge_count: =====> '+service_count);
}

Body:
Replace i with service_count, then you can change your code with:

for(let service_count  = 0; service_count  < res.length; service_count ++){
    console.log('service_charge_count: =====> ' + service_count);
}

Or I think that you service_count is res.length, therefore, you can do:

let service_count = res.length;
console.log(service_count);


问:
Radio Button within a table with Material Design
I'm actually trying to insert a radio button group within a table component of material design and angular 6.

So in the examples of Material design official website there is a table with checkboxes but what I want is to do the same with radio button for each element of the table.

I tried to do it with a *ngFor directive but i can't access the ELEMENT_DATA array even if it's a global const.

```<code>import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'table-selection-example',
  styleUrls: ['table-selection-example.css'],
  templateUrl: 'table-selection-example.html',
})
export class TableSelectionExample {
  displayedColumns = ['select', 'position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  selection = new SelectionModel<PeriodicElement>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
</code>```

```<code>    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Checkbox Column -->
  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef>
      <mat-checkbox (change)="$event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()">
      </mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)">
      </mat-checkbox>
    </td>
  </ng-container>

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <!-- Symbol Column -->
  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"
      (click)="selection.toggle(row)">
  </tr>
</table>
</code>```

So with this code i want to remove the checkboxes and replace it with radio buttons.

what i tried is to put :

```<code><mat-radio-group>
   <mat-radio-button *ngIf="let i of ELEMENT_DATA" value = i></mat-radio-button>
</mat-radio-button>
</code>```

and like I said before I can't access my Array ELEMENT_DATA. I also tried to change it with dataSource.length, but nothing do.

thanks for helping.

答:
you can just add  inside of the td of your table and it would work. but I got no idea how to know which radio button is selected.

                                <ng-container matColumnDef="select">

                    <mat-radio-button disabled>
                    </mat-radio-button>

                    <mat-radio-button (click)="$event.stopPropagation()"
                                      (change)="$event ? selection3.toggle(row) : null"
                                      [checked]="selection3.isSelected(row)"
                                      ></mat-radio-button>

                </ng-container>

```

<p>typescript</p>

```  selection3 = new SelectionModel<Instruments>(false, []);

```

if you work in the row section you can always use let row as I did is also handy when you want to put a routerLink on your entire row

Body:
I'm actually trying to insert a radio button group within a table component of material design and angular 6.

So in the examples of Material design official website there is a table with checkboxes but what I want is to do the same with radio button for each element of the table.

I tried to do it with a *ngFor directive but i can't access the ELEMENT_DATA array even if it's a global const.

import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'table-selection-example',
  styleUrls: ['table-selection-example.css'],
  templateUrl: 'table-selection-example.html',
})
export class TableSelectionExample {
  displayedColumns = ['select', 'position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  selection = new SelectionModel<PeriodicElement>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

  <ng-container matColumnDef="select">

      <mat-checkbox (change)="$event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()">
      </mat-checkbox>

      <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)">
      </mat-checkbox>

  </ng-container>

  <ng-container matColumnDef="position">
     No.
     {{element.position}}
  </ng-container>

  <ng-container matColumnDef="name">
     Name
     {{element.name}}
  </ng-container>

  <ng-container matColumnDef="weight">
     Weight
     {{element.weight}}
  </ng-container>

  <ng-container matColumnDef="symbol">
     Symbol
     {{element.symbol}}
  </ng-container>

So with this code i want to remove the checkboxes and replace it with radio buttons.

what i tried is to put :

<mat-radio-group>
   <mat-radio-button *ngIf="let i of ELEMENT_DATA" value = i></mat-radio-button>
</mat-radio-button>

and like I said before I can't access my Array ELEMENT_DATA. I also tried to change it with dataSource.length, but nothing do.

thanks for helping.

Body:
you can just add  inside of the td of your table and it would work. but I got no idea how to know which radio button is selected.

 <table mat-table [dataSource]="dataSource" matSortDisableClear>

                                <ng-container matColumnDef="select">
                  <th mat-header-cell *matHeaderCellDef>
                    <mat-radio-button disabled>
                    </mat-radio-button>
                  </th>
                  <td mat-cell *matCellDef="let row">
                    <mat-radio-button (click)="$event.stopPropagation()"
                                      (change)="$event ? selection3.toggle(row) : null"
                                      [checked]="selection3.isSelected(row)"
                                      ></mat-radio-button>
                  </td>
                </ng-container>
                <tr mat-header-row *matHeaderRowDef="datadisplayedColumns"></tr>

                <tr mat-row *matRowDef="let row; columns: datadisplayedColumns;"></tr>
 </table>

typescript

  selection3 = new SelectionModel<Instruments>(false, []);

if you work in the row section you can always use let row as I did is also handy when you want to put a routerLink on your entire row


问:
Checking Sucsessfull Validation of Form
I have a C# ViewModel, specifying data annotations for automatic validation.
I render the View in Razor code.
I need to check in javascript, client side, if the ALL validations went through, or not.

I Have tried to catch the Submit event of the form. This worked, but is not fired after the validation completed. I recon I need to check for a state, or listen for some event that will fire when validation succeeded.

```<code>    $(document).ready(function () {
        alert("Before Fade");
        $("#LoaderSpinner").fadeOut('hidden');
    });

    $("#HelloForm").submit(function () {
        alert('SUBMITTED THE FORM');
        // Here i need to check if the form validated before activating the spinner
        $("#LoaderSpinner").fadeIn();
    });

</script>
</code>```

A nudge in the right direction would be appreciated.

答:
Try this: </p>

```<code>$('form').submit(function(evt) {
    evt.preventDefault();
    var $form = $(this);
    if($form.valid()) {
        //do stuff here
    }
});
</code>```

Title: Checking Sucsessfull Validation of Form

Body:
I have a C# ViewModel, specifying data annotations for automatic validation.
I render the View in Razor code.
I need to check in javascript, client side, if the ALL validations went through, or not.

I Have tried to catch the Submit event of the form. This worked, but is not fired after the validation completed. I recon I need to check for a state, or listen for some event that will fire when validation succeeded.

    $(document).ready(function () {
        alert("Before Fade");
        $("#LoaderSpinner").fadeOut('hidden');
    });

    $("#HelloForm").submit(function () {
        alert('SUBMITTED THE FORM');
        // Here i need to check if the form validated before activating the spinner
        $("#LoaderSpinner").fadeIn();
    });

</script>

A nudge in the right direction would be appreciated.

Body:
Try this:

$('form').submit(function(evt) {
    evt.preventDefault();
    var $form = $(this);
    if($form.valid()) {
        //do stuff here
    }
});


问:
Reporting Utilization of Individual ResourcePool units
In Anylogic, How can I get statistics such as utilization of individual resource pool units?
As the resourcePool.utilization() function returns the mean utilization for all units in the resource pool.
Is it possible to access the data of each resource pool unit? Any ideas?
Thanks in advance!</p>

答:
Updated Answer

There is an easier way to get the utilization for individual resource units:

Define a custom resource agent type, as explained here

Set this new custom type for your resource pool as New resource unit

Add an empty population of this custom resource type (here named myResources)

In the resource pool under Advanced/Population set this empty population

Now you can access the individual resource pool units' utilization, with x as the index of the unit:

myResources(x).getUtilization()
```

In order to keep track of more complex statistics, you might still need to use the more complicated solution of the original answer.

Original Answer:

You can build something yourself:

Use the On seize and On release code in the ressourcePool to notify your custom ressource Agent that it is active/not active. You can pass a message to the agent or call a function inside the agent.

The ressource agent can save its current state in a variable, statechart or similar.

You can then use the standard statistic module from the Analysis palette to aggregate the information, for example to get the individual agent's  utilization.

Body:
Updated Answer

There is an easier way to get the utilization for individual resource units:

Define a custom resource agent type, as explained here

Set this new custom type for your resource pool as New resource unit

Add an empty population of this custom resource type (here named myResources)

In the resource pool under Advanced/Population set this empty population

Now you can access the individual resource pool units' utilization, with x as the index of the unit:

myResources(x).getUtilization()

In order to keep track of more complex statistics, you might still need to use the more complicated solution of the original answer.

Original Answer:

You can build something yourself:

Use the On seize and On release code in the ressourcePool to notify your custom ressource Agent that it is active/not active. You can pass a message to the agent or call a function inside the agent.

The ressource agent can save its current state in a variable, statechart or similar.

You can then use the standard statistic module from the Analysis palette to aggregate the information, for example to get the individual agent's  utilization.


问:
How to filter a List using Java 8 stream and startwith array of values
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

```<code>List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());
</code>```

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

答:
Another attempt to give a solution could be to use contains , though the actual implementation of startsWith and contains are different but in OP case both will fetch the same result.

```<code>List<String> strList = nameList.stream().filter(s->numberList.stream().anyMatch(s::contains)).collect(Collectors.toList());
</code>```

Output:

[1_John, 9_Susan]

Body:
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

Body:
Another attempt to give a solution could be to use contains , though the actual implementation of startsWith and contains are different but in OP case both will fetch the same result.

List<String> strList = nameList.stream().filter(s->numberList.stream().anyMatch(s::contains)).collect(Collectors.toList());

Output:

[1_John, 9_Susan]


问:
Using webworker inside electron app which use puppeteer
I read web workers API and puppeteer docs about worker. Now I'm trying to use worker within my electron app which use puppeteer webdriver. App was generated with vue-electron boileplate. I want to use worker in node side of electron application.

So far I tried like they show in MDN:

```<code>const Worker = require('worker_threads');
console.log(Worker);
</code>```

this cause error:

Error: Cannot find module 'worker_threads'

I made sure I'm using latest node version by node -v in terminal and I am, version is v12.3.1.

Next I tried to dig something in nodejs / help on github I found this where they suggest to use --experimental-worker. So I did:

```<code>"dev": "node --experimental-worker .electron-vue/dev-runner.js",
</code>```

Still same error. Next I tried to find something in electron issuses on github and I found this topic where they suggest to set environment variable of NODE_OPTIONS=--experimental-worker. So I did (windows 10):

(sorry about polish). Error is still same. I can't find any more tips in network. I definitely need your help guys.

I really want to try this worker_threads because every 300ms I'm getting very big (over 200k elements) array from one of pages and I'm performing filters on this array which cause browser "lags".

Environment:

Windows 10

答: So basically the Worker Thread API just shipped with node versions above v10. The version you're using ( electron 2.x ) ships with node v8.x which doesn't have the feature shipped.

Body:
I read web workers API and puppeteer docs about worker. Now I'm trying to use worker within my electron app which use puppeteer webdriver. App was generated with vue-electron boileplate. I want to use worker in node side of electron application.

So far I tried like they show in MDN:

const Worker = require('worker_threads');
console.log(Worker);

this cause error:

Error: Cannot find module 'worker_threads'

I made sure I'm using latest node version by node -v in terminal and I am, version is v12.3.1.

Next I tried to dig something in nodejs / help on github I found this where they suggest to use --experimental-worker. So I did:

"dev": "node --experimental-worker .electron-vue/dev-runner.js",

Still same error. Next I tried to find something in electron issuses on github and I found this topic where they suggest to set environment variable of NODE_OPTIONS=--experimental-worker. So I did (windows 10):

(sorry about polish). Error is still same. I can't find any more tips in network. I definitely need your help guys.

I really want to try this worker_threads because every 300ms I'm getting very big (over 200k elements) array from one of pages and I'm performing filters on this array which cause browser "lags".

Environment:

Windows 10


问:
How can I make my front end app access my node server apis
I have created a front end app by creat-react-app.

The command "npm run start" can create a webpack-dev-server and serve my

front end app for developing. Here is the problem comes:

My front end app must request some api from a node server I had created before.

By default create-react-app start a webpack-dev-server on port 3000

My node server was started on port 3001

Access port 3001 directly may cause cross-origin problems

How can I gracefully start my developing story from those problems !

答:
There are two ways to solve cross-origin problems in node server,

Using cors node module

First install cors module. npm install cors

and then use it inside your app

```<code>const Express       = require("express");
const BodyParser    = require("body-parser");
const Cors          = require("cors");

const app = Express();
app.use(Cors());

app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());

app.listen(3001, 'localhost', (err) => {
    if(err) {
        console.log(err);
        process.exit(-1);
    }
    console.log("Server listen port 8083");
});
</code>```

simply use following headers

```<code>app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
    next();
});
</code>```

Body:
There are two ways to solve cross-origin problems in node server,

Using cors node module

First install cors module. npm install cors

and then use it inside your app

const Express       = require("express");
const BodyParser    = require("body-parser");
const Cors          = require("cors");

const app = Express();
app.use(Cors());

app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());

app.listen(3001, 'localhost', (err) => {
    if(err) {
        console.log(err);
        process.exit(-1);
    }
    console.log("Server listen port 8083");
});

simply use following headers

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
    next();
});


问:
Use SSL certificate in azure function app with nodejs
I uploaded a .pfx certificate to my function app.
How do I load this certificate so I can use it in my Nodejs code?
If I put it in the project directory I am able to use it and it works fine but I would like to avoid to have it in the project.

Thanks.

答:
In Azure portal, you can follow the figures below to upload your private certificate .pfx file and next to do the SSL binding.

Fig 1. Select your Function App and move to Platform features tab to click SSL button.

Fig 2. Then, select Private Certificates (.pfx) tab to click Upload Certificate
 button and next to upload your .pfxfile in the right dialog window.

Fig 3. Move to Bindings tab and click Add SSL Binding button to select your uploaded cert in the right dialog window.

Then, you can refer to the offical document Configure TLS mutual authentication for Azure App Service to know how to configure and enable SSL authenticatication feature in your Node.js code, see its Node.js sample.

There are other offical documents also may helps.

Use an SSL certificate in your application code in Azure App Service

Tutorial: Bind an existing custom SSL certificate to Azure App Service

Buy and configure an SSL certificate for Azure App Service


问:
Excel - Split cell with a delimiter and if delimiter not found get complete cell value to another cell
I have an excel file with data where I want a Split cell with a delimiter and if the delimiter is not found then copy that cell value to another cell

e.g.

ABC Ltd.

ABC Ltd. - Ind

PQR Ltd. - USA

LMN Corp.

Output - delimiter "-"

ColumnA       ColumnB

ABC Ltd.   ABC Ltd.

ABC Ltd.    Ind

PQR Ltd.     USA

LMN Corp.    LMN Corp.

However, I'm using below formula but not getting what I want.

=TRIM(LEFT(B2,FIND("-",B2)-1))

=TRIM(REPLACE(B2,1,FIND("-",B2),""))

答:
You need to put in error handling for the case where B2 doesn't contain a '-'

```<code>=IFERROR(TRIM(LEFT(B2,FIND("-",B2)-1)),TRIM(B2))
</code>```

and

```<code>=IFERROR(TRIM(REPLACE(B2,1,FIND("-",B2),"")),TRIM(B2))
</code>```

Body:
You need to put in error handling for the case where B2 doesn't contain a '-'

=IFERROR(TRIM(LEFT(B2,FIND("-",B2)-1)),TRIM(B2))

and

=IFERROR(TRIM(REPLACE(B2,1,FIND("-",B2),"")),TRIM(B2))


问:
I configured the TestNG tests in parallel, but it is not working
How can I debug this?

Follow SuiteTest.xml (TestNG is this way - Fix in the snippet "thread-count =" 2 "parallel =" tests "):

```<code><?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="SuiteTest" thread-count="2" parallel="tests">

<!-- classes tests methods  -->

    <test name="Firefox Test">

        <parameter name="browser" value="FIREFOX" />

        <classes>

            <class name="test.CN01_CT01_IncluirConteudoMP3" />

            <class name="test.CN01_CT02_IncluirConteudoMP4" />

        </classes>

    </test>

</suite>
</code>```

Class DriveFactory:

```<code>public class DriverFactory {

    static String path = System.getProperty("user.dir");

    private static ThreadLocal<WebDriver> threadDriver = new ThreadLocal<WebDriver>() {

        @Override

        protected synchronized WebDriver initialValue() {

            return initDriver();

        }

    };

    private DriverFactory() {

    }

    public static WebDriver getDriver() {

        return threadDriver.get();

    }

    public static WebDriver initDriver() {

        WebDriver driver = null;

        switch (Propriedades.browser) {

        case CHROME:

            //executeChrome(BasePage.url);

            break;

        case FIREFOX:

            String driverpathFirefox = path + File.separator + "drivers" + File.separator + "geckodriver.exe";

            System.setProperty("webdriver.gecko.driver", driverpathFirefox);

            driver = new FirefoxDriver();

            getDriver().get(BasePage.url);

            break;

        }

        driver.manage().window().maximize();

        return driver;

    }

    public static void killDriver() {

        WebDriver driver = getDriver();

        if (driver != null) {
            driver.quit();
            driver = null;
        }

        if (threadDriver != null) {
            threadDriver.remove();
            }

    }
}
</code>```

Testing classes (Very simple to summarize the question):

```<code>public class CN01_CT02_IncluirConteudoMP4 extends BaseTest {

    @Test

    public void CN01_CT02_IncluirConteudoMp4(){

        assertEquals("123", "123");

    }

}

public class CN01_CT01_IncluirConteudoMP3 extends BaseTest {

    @Test

    public void CN01_CT01_IncluirConteudoMp3() throws InterruptedException, AWTException{

        assertEquals("123", "123456");

    }

}
</code>```

BaseTest Class (Here I log in, log out and close the browser):

```<code>public class BaseTest {

    protected static ExtentReports extent;

    public static String testName;

    @Parameters({ "browser" })

    @BeforeMethod

    public void BeforeTest(Method method, Browsers browser) throws IOException, BiffException {

        Propriedades.browser = browser;

        String browserStr = browser.toString();

        //TestName

        testName = method.getName() + "-" + browserStr;

        // Login

        LoginPage.realizarLogin();

        //Start report

        extent = ExtentReport.StartReport(testName);

    }

    @AfterMethod

    public void finaliza(ITestResult result) throws IOException {

        ExtentReport.ResultTest(result, testName);

        // Logout

        LoginPage.realizarLogout();

        // Closed Browser

        if (Propriedades.FECHAR_BROWSER) {

            killDriver();

        }

    }

    @AfterSuite

    public static void finalizaTudo(){

        DriverFactory.killDriver();

        extent.flush();

    }

}
</code>```

Pom.xml:

```<code><build>

    <testSourceDirectory>src</testSourceDirectory>

    <plugins>

        <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-surefire-plugin</artifactId>

            <version>2.18.1</version>

            <configuration>

                <includes>

                    <include>/suites/SuiteTest.xml</include>

                </includes>

                <parallel>tests</parallel>

                <threadCount>1</threadCount>

            </configuration>

        </plugin>

    </plugins>

</build>

        <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        </dependency>

        (..)
</code>```

I have the BasePage class that only instantiates the DSL, this one at a time has the actions on the screen elements.

When running via Eclipse (Suite.xml - Run -> TestNG), the system opens several browsers and is not performing certain actions.

答:
Your test violates Parallel Testing Best Practices and your tests will not be parallel at all due to synchronized nature of the WebDriver usage.

The workaround would be to run your tests using a separate JVM instance for each tests, in pom.xml add the next lines:

```<code><forkCount>2</forkCount>
<reuseForks>false</reuseForks>
</code>```

A better approach would be re-writing your test to get rid of static modifiers and synchronized methods.

More information: Fork Options and Parallel Test Execution

Body:
How can I debug this?

Follow SuiteTest.xml (TestNG is this way - Fix in the snippet "thread-count =" 2 "parallel =" tests "):

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="SuiteTest" thread-count="2" parallel="tests">

    <test name="Firefox Test">

        <parameter name="browser" value="FIREFOX" />

        <classes>

            <class name="test.CN01_CT01_IncluirConteudoMP3" />

            <class name="test.CN01_CT02_IncluirConteudoMP4" />

        </classes>

    </test>

</suite>

Class DriveFactory:

public class DriverFactory {

    static String path = System.getProperty("user.dir");

    private static ThreadLocal<WebDriver> threadDriver = new ThreadLocal<WebDriver>() {

        @Override

        protected synchronized WebDriver initialValue() {

            return initDriver();

        }

    };

    private DriverFactory() {

    }

    public static WebDriver getDriver() {

        return threadDriver.get();

    }

    public static WebDriver initDriver() {

        WebDriver driver = null;

        switch (Propriedades.browser) {

        case CHROME:

            //executeChrome(BasePage.url);

            break;

        case FIREFOX:

            String driverpathFirefox = path + File.separator + "drivers" + File.separator + "geckodriver.exe";

            System.setProperty("webdriver.gecko.driver", driverpathFirefox);

            driver = new FirefoxDriver();

            getDriver().get(BasePage.url);

            break;

        }

        driver.manage().window().maximize();

        return driver;

    }

    public static void killDriver() {

        WebDriver driver = getDriver();

        if (driver != null) {
            driver.quit();
            driver = null;
        }

        if (threadDriver != null) {
            threadDriver.remove();
            }

    }
}

Testing classes (Very simple to summarize the question):

public class CN01_CT02_IncluirConteudoMP4 extends BaseTest {

    @Test

    public void CN01_CT02_IncluirConteudoMp4(){

        assertEquals("123", "123");

    }

}

public class CN01_CT01_IncluirConteudoMP3 extends BaseTest {

    @Test

    public void CN01_CT01_IncluirConteudoMp3() throws InterruptedException, AWTException{

        assertEquals("123", "123456");

    }

}

BaseTest Class (Here I log in, log out and close the browser):

public class BaseTest {

    protected static ExtentReports extent;

    public static String testName;

    @Parameters({ "browser" })

    @BeforeMethod

    public void BeforeTest(Method method, Browsers browser) throws IOException, BiffException {

        Propriedades.browser = browser;

        String browserStr = browser.toString();

        //TestName

        testName = method.getName() + "-" + browserStr;

        // Login

        LoginPage.realizarLogin();

        //Start report

        extent = ExtentReport.StartReport(testName);

    }

    @AfterMethod

    public void finaliza(ITestResult result) throws IOException {

        ExtentReport.ResultTest(result, testName);

        // Logout

        LoginPage.realizarLogout();

        // Closed Browser

        if (Propriedades.FECHAR_BROWSER) {

            killDriver();

        }

    }

    @AfterSuite

    public static void finalizaTudo(){

        DriverFactory.killDriver();

        extent.flush();

    }

}

Pom.xml:

<build>

    <testSourceDirectory>src</testSourceDirectory>

    <plugins>

        <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-surefire-plugin</artifactId>

            <version>2.18.1</version>

            <configuration>

                <includes>

                    <include>/suites/SuiteTest.xml</include>

                </includes>

                <parallel>tests</parallel>

                <threadCount>1</threadCount>

            </configuration>

        </plugin>

    </plugins>

</build>

        <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        </dependency>

        (..)

I have the BasePage class that only instantiates the DSL, this one at a time has the actions on the screen elements.

When running via Eclipse (Suite.xml - Run -> TestNG), the system opens several browsers and is not performing certain actions.

Body:
Your test violates Parallel Testing Best Practices and your tests will not be parallel at all due to synchronized nature of the WebDriver usage.

The workaround would be to run your tests using a separate JVM instance for each tests, in pom.xml add the next lines:

<forkCount>2</forkCount>
<reuseForks>false</reuseForks>

A better approach would be re-writing your test to get rid of static modifiers and synchronized methods.

More information: Fork Options and Parallel Test Execution


问:
How to get MST properties from vbscript
So, I am creating a vbscript that will read an MSI and MST file. The idea is that if the user that will run the script is testing an MSI with an MST file involved, the script should create a "report" of the new properties that this MST have.

I am able to get the properties from a regular MSI, the problem is when I am trying to get into the MST section. While doing research I found out about the _TransformView Table and this should help me to obtain this information but I think I am not sure I know how to handle that table.

```<code>Const msiTransformErrorViewTransform = 256

Const msiOpenDB = 2

Dim FS, TS, WI, DB, View, Rec

Set WI = CreateObject("WindowsInstaller.Installer")

Set DB = WI.OpenDatabase(msiPath,msiOpenDB)

DB.ApplyTransform mstPath, msiTransformErrorViewTransform

If Err.number Then
    Exit Function
End If

For i = 0 To 24 'Number of properties on the arrPropertyList

    Set View = DB.OpenView("Select `Value` From Property WHERE `Property` = " & "'" & arrPropertyList(i) & "'")
    View.Execute
    Set Rec = View.Fetch
    If Not Rec Is Nothing Then
        objLog.WriteLine arrPropertyList(i) & " = " & Rec.StringData(1)
    End If

Next
</code>```

That code will display the msi properties that I have added on the arrPropertyList. The thing is that I am looking for the MST properties and I am only getting the MSI ones. I know that I should change the Query to access the _TransformView Table when calling the DB.OpenView but not sure how can I get to this information! Any knowledge you can share would be welcome.

答:
It works slightly differently to what you think.  Run the following to see what I mean (maybe force the VBS to run with Cscript.exe from a command prompt if you're expecting a lot of output):

```<code>'create 2 constants - one for when we want to just query the MSI (read) and one for when we want to make changes (write)

Const msiOpenDatabaseModeReadOnly = 0
Const msiOpenDatabaseModeTransact = 1
Const msiTransformErrorViewTransform = 256

'create WindowsInstaller.Installer object
Dim oInstaller : Set oInstaller = CreateObject("WindowsInstaller.Installer")

'open the MSI (the first argument supplied to the vbscript)
Dim oDatabase : Set oDatabase = oInstaller.OpenDatabase("C:\Temp\Temp.msi",msiOpenDatabaseModeReadOnly)

oDatabase.ApplyTransform "C:\Temp\Temp.mst", msiTransformErrorViewTransform

'create a view of the registry we want to see
Dim sql : sql = "SELECT * FROM `_TransformView`"
Dim regView : Set regView = oDatabase.OpenView(sql)

'execute the query
regView.Execute

'fetch the first row of data (if there is one!)
Dim regRecord : Set regRecord = regView.Fetch

'whilst we've returned a row and therefore regRecord is not Nothing
While Not regRecord Is Nothing

    'print out the registry key
    wscript.echo "Table: " & regRecord.StringData(1)
    wscript.echo "Column: " & regRecord.StringData(2)
    wscript.echo "Row: " & regRecord.StringData(3)
    wscript.echo "Data: " & regRecord.StringData(4)
    wscript.echo "Current: " & regRecord.StringData(5)
    wscript.echo "***"

    'go and fetch the next row of data
    Set regRecord = regView.Fetch
Wend

regView.Close
Set regView = Nothing
Set regRecord = Nothing
Set oDatabase = Nothing
Set oInstaller = Nothing
</code>```

So if you only wanted to see changes in the Property table, you would change the SQL query to:

```<code>Dim sql : sql = "SELECT * FROM `_TransformView` WHERE `Table` = 'Property'"
</code>```

As well as storing the column names of the changed entries, the 'Column' column in the '_TransformView' table also stores whether the value was inserted, removed etc by using the values:
INSERT, DELETE, CREATE, or DROP.

You can find lots of VBScript Windows Installer tutorials for reference - don't forget to set your objects to Nothing otherwise you'll leave handles open.  And of course use the link you provided for further reference.

Title: How to get MST properties from vbscript

Body:
So, I am creating a vbscript that will read an MSI and MST file. The idea is that if the user that will run the script is testing an MSI with an MST file involved, the script should create a "report" of the new properties that this MST have.

I am able to get the properties from a regular MSI, the problem is when I am trying to get into the MST section. While doing research I found out about the _TransformView Table and this should help me to obtain this information but I think I am not sure I know how to handle that table.

Const msiTransformErrorViewTransform = 256

Const msiOpenDB = 2

Dim FS, TS, WI, DB, View, Rec

Set WI = CreateObject("WindowsInstaller.Installer")

Set DB = WI.OpenDatabase(msiPath,msiOpenDB)

DB.ApplyTransform mstPath, msiTransformErrorViewTransform

If Err.number Then
    Exit Function
End If

For i = 0 To 24 'Number of properties on the arrPropertyList

    Set View = DB.OpenView("Select `Value` From Property WHERE `Property` = " & "'" & arrPropertyList(i) & "'")
    View.Execute
    Set Rec = View.Fetch
    If Not Rec Is Nothing Then
        objLog.WriteLine arrPropertyList(i) & " = " & Rec.StringData(1)
    End If

Next

That code will display the msi properties that I have added on the arrPropertyList. The thing is that I am looking for the MST properties and I am only getting the MSI ones. I know that I should change the Query to access the _TransformView Table when calling the DB.OpenView but not sure how can I get to this information! Any knowledge you can share would be welcome.

Body:
It works slightly differently to what you think.  Run the following to see what I mean (maybe force the VBS to run with Cscript.exe from a command prompt if you're expecting a lot of output):

'create 2 constants - one for when we want to just query the MSI (read) and one for when we want to make changes (write)

Const msiOpenDatabaseModeReadOnly = 0
Const msiOpenDatabaseModeTransact = 1
Const msiTransformErrorViewTransform = 256

'create WindowsInstaller.Installer object
Dim oInstaller : Set oInstaller = CreateObject("WindowsInstaller.Installer")

'open the MSI (the first argument supplied to the vbscript)
Dim oDatabase : Set oDatabase = oInstaller.OpenDatabase("C:\Temp\Temp.msi",msiOpenDatabaseModeReadOnly)

oDatabase.ApplyTransform "C:\Temp\Temp.mst", msiTransformErrorViewTransform

'create a view of the registry we want to see
Dim sql : sql = "SELECT * FROM `_TransformView`"
Dim regView : Set regView = oDatabase.OpenView(sql)

'execute the query
regView.Execute

'fetch the first row of data (if there is one!)
Dim regRecord : Set regRecord = regView.Fetch

'whilst we've returned a row and therefore regRecord is not Nothing
While Not regRecord Is Nothing

    'print out the registry key
    wscript.echo "Table: " & regRecord.StringData(1)
    wscript.echo "Column: " & regRecord.StringData(2)
    wscript.echo "Row: " & regRecord.StringData(3)
    wscript.echo "Data: " & regRecord.StringData(4)
    wscript.echo "Current: " & regRecord.StringData(5)
    wscript.echo "***"

    'go and fetch the next row of data
    Set regRecord = regView.Fetch
Wend

regView.Close
Set regView = Nothing
Set regRecord = Nothing
Set oDatabase = Nothing
Set oInstaller = Nothing

So if you only wanted to see changes in the Property table, you would change the SQL query to:

Dim sql : sql = "SELECT * FROM `_TransformView` WHERE `Table` = 'Property'"

As well as storing the column names of the changed entries, the 'Column' column in the '_TransformView' table also stores whether the value was inserted, removed etc by using the values:
INSERT, DELETE, CREATE, or DROP.

You can find lots of VBScript Windows Installer tutorials for reference - don't forget to set your objects to Nothing otherwise you'll leave handles open.  And of course use the link you provided for further reference.


问:
What's the fastest way to test the validity of a large number of well-formed URLs
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs

I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).

Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.

Can it be done?

答:
I'm assuming you want to do it in Python based on your tags.  In that case, I'd use httplib.  Optionally, somehow group the URLs by host so you can make multiple requests in one connection for those URLs that have the same host.  Use the HEAD request.</p>

```<code>conn = httplib.HTTPConnection("example.com")
conn.request("HEAD", "/index.html")
resp = conn.getresponse()
print resp.status
</code>```

OwnerDisplayName: Salim Fadhley

ContentLicense: CC BY-SA 2.5

Body:
I'm assuming you want to do it in Python based on your tags.  In that case, I'd use httplib.  Optionally, somehow group the URLs by host so you can make multiple requests in one connection for those URLs that have the same host.  Use the HEAD request.

conn = httplib.HTTPConnection("example.com")
conn.request("HEAD", "/index.html")
resp = conn.getresponse()
print resp.status

OwnerDisplayName: Jeff


问:
Zend Framework - Add new input element using javascript
I'm working on a project using Zend Framework.

I'm creating a form on which users can add a set of elements by pressing a + sign.

Zend framework uses subforms and decorators to get array of values from a form.

These will show when the page is displayed

How does the new fields created with Javascript integrate in that model?

答:
One suggestion would be to define all input fields that you want to provide using zend form.

But when the form is displayed you could hide certain fields and make them visible by clicking on +.

I think this is the most simple approach because for adding decorators and stuff you would need to change php files on client side and this is not possible.

Another suggestion, you could define several forms. Clicking on + redirectes the user to another form with an added field.


问:
Symfony Encore multiple asset manifests
I have a question regarding Encore in Symfony 3.4 and asset versioning.

In my webpack.config.jsI have two configurations.
First is for JS files, the other one for compiling .less.

Each configuration is reset by Encore.reset()

Output bundles are generating manifest with versioning via .enableVersioning, so I have two manifest.json in

```<code>web/js/manifest.json
web/stylesheets/manifest.json
</code>```

According to docs, to have my assets loaded via manifest I need to declare it in config.yml

```<code>   assets:
        base_path: "%myapp.http.site_assets_suffix%"
        stylesheets:
            json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
</code>```

If I want to link to style.css generated by webpack, I use

```<code>asset("stylesheets/style.css")
</code>```

But in my application I have two manifests and I think this can't be changed due to two Encore configurations.

I've tried adding something in likes of

```<code>packages:
     stylesheets:
                json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
     js:
                json_manifest_path: "%kernel.project_dir%/web/assets/js/manifest.json"
</code>```

because I saw that somewhere, but unfortunately this won't work at all.

I've thought about combining two manifests into one in last webpack entry point, but this can be time consuming.

Is there any other solution than combining manfiests or combining js + less compilation into one big Encore task?

答:
I've found a solution

```<code>assets:
    base_path: 'path%'
    packages:
        noversion:
            version: false
            version_format: "%%1$s"
            base_path: "path%"
        stylesheets:
            json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
        js:
            json_manifest_path: "%kernel.project_dir%/web/assets/js/manifest.json"
        admin:
            json_manifest_path: "%kernel.project_dir%/web/assets/js/admin/manifest.json"
</code>```

And then in .twig files, you need to call it as

```<code>    <script src="{{ asset('assets/DIRNAME/WEBPACK_ENTRY_NAME_HERE', ASSET_PACKAGE_NAME_HERE) }}"></script>
</code>```

In my case

```<code><script src="{{ asset('assets/js/backend.js', 'js') }}"></script>

</code>```

Where WEBPACK_ENTRY_NAME is the name of the Webpack/Encore bundle from webpack.config.js, in my case

```<code>.setOutputPath('./web/assets/js')
    .setPublicPath('/assets/js')
    .addEntry('backend',
</code>```

Sorry for delayed answer, but I forgot about it.

Title: Symfony Encore multiple asset manifests

Body:
I have a question regarding Encore in Symfony 3.4 and asset versioning.

In my webpack.config.jsI have two configurations.
First is for JS files, the other one for compiling .less.

Each configuration is reset by Encore.reset()

Output bundles are generating manifest with versioning via .enableVersioning, so I have two manifest.json in

web/js/manifest.json
web/stylesheets/manifest.json

According to docs, to have my assets loaded via manifest I need to declare it in config.yml

   assets:
        base_path: "%myapp.http.site_assets_suffix%"
        stylesheets:
            json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"

If I want to link to style.css generated by webpack, I use

asset("stylesheets/style.css")

But in my application I have two manifests and I think this can't be changed due to two Encore configurations.

I've tried adding something in likes of

packages:
     stylesheets:
                json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
     js:
                json_manifest_path: "%kernel.project_dir%/web/assets/js/manifest.json"

because I saw that somewhere, but unfortunately this won't work at all.

I've thought about combining two manifests into one in last webpack entry point, but this can be time consuming.

Is there any other solution than combining manfiests or combining js + less compilation into one big Encore task?

Body:
I've found a solution

assets:
    base_path: 'path%'
    packages:
        noversion:
            version: false
            version_format: "%%1$s"
            base_path: "path%"
        stylesheets:
            json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
        js:
            json_manifest_path: "%kernel.project_dir%/web/assets/js/manifest.json"
        admin:
            json_manifest_path: "%kernel.project_dir%/web/assets/js/admin/manifest.json"

And then in .twig files, you need to call it as

    <script src="{{ asset('assets/DIRNAME/WEBPACK_ENTRY_NAME_HERE', ASSET_PACKAGE_NAME_HERE) }}"></script>

In my case

<script src="{{ asset('assets/js/backend.js', 'js') }}"></script>

Where WEBPACK_ENTRY_NAME is the name of the Webpack/Encore bundle from webpack.config.js, in my case

.setOutputPath('./web/assets/js')
    .setPublicPath('/assets/js')
    .addEntry('backend',

Sorry for delayed answer, but I forgot about it.


问:
How to not continually repeat a background scenario for Cucumber features that depend on that background scenario
I'm writing some end-to-end tests for my application using Cucumber and Selenium. I'm keeping every scenario totally independent of one another, as advised on the Cucumber website. However, my application has session based authentication, so every time a new scenario is run, it will required a login process in order to first access the site. Right now my approach is to put the login scenario as a background scenario for all other scenarios, like so:

```<code>  Background: User is Logged In
    Given I am on the login screen
    When I enter my login details
    And I click submit
    Then I should be logged in
</code>```

However, this feels like a lot of duplicated 'code'. Moreover, having each scenario run independently requires a new WebDriver instance being created and a browser being run for each scenario, which feels a bit inefficient?

Can anyone advise firstly on how I can avoid duplicating the background scenario in every other scenario (if possible)  and secondly if having a separate WebDriver instance for each scenario is the correct approach?

答:
This example is in Ruby. You can group up the steps used for Login in login_steps.rb file.

In the .feature file you'll need to write a step like "Given the user is logged in". You can pass in login data in this step as well, if you want. Then in the login_steps.rb file, you create:

```<code>Given(/^the user is logged in$/) do
  step('I am on the login screen')
  step('I enter my login details')
  step('I click submit')
  step('I should be logged in')
end
</code>```

I'm sure you can find the equivalent in any other language. Now you can write a the background like:

```<code>Background: Given the user is logged in
</code>```

and it will be used before each scenario of that specific .feature file

As for the Webdriver, as far as I'm aware, you create a session when the test starts and you quit when it ends.

Hope it helps!

Body:
I'm writing some end-to-end tests for my application using Cucumber and Selenium. I'm keeping every scenario totally independent of one another, as advised on the Cucumber website. However, my application has session based authentication, so every time a new scenario is run, it will required a login process in order to first access the site. Right now my approach is to put the login scenario as a background scenario for all other scenarios, like so:

  Background: User is Logged In
    Given I am on the login screen
    When I enter my login details
    And I click submit
    Then I should be logged in

However, this feels like a lot of duplicated 'code'. Moreover, having each scenario run independently requires a new WebDriver instance being created and a browser being run for each scenario, which feels a bit inefficient?

Can anyone advise firstly on how I can avoid duplicating the background scenario in every other scenario (if possible)  and secondly if having a separate WebDriver instance for each scenario is the correct approach?

Body:
This example is in Ruby. You can group up the steps used for Login in login_steps.rb file.

In the .feature file you'll need to write a step like "Given the user is logged in". You can pass in login data in this step as well, if you want. Then in the login_steps.rb file, you create:

Given(/^the user is logged in$/) do
  step('I am on the login screen')
  step('I enter my login details')
  step('I click submit')
  step('I should be logged in')
end

I'm sure you can find the equivalent in any other language. Now you can write a the background like:

Background: Given the user is logged in

and it will be used before each scenario of that specific .feature file

As for the Webdriver, as far as I'm aware, you create a session when the test starts and you quit when it ends.

Hope it helps!


答:
By adding i to your variable, you're adding in the first loop 0, in the second loop 1, in the third loop 2. So you're not counting anything.

```<code>var service_count=0;
for(let i=0;i<res.length;i++){
    service_count++;
}
console.log('service_charge_count: =====> '+service_count);
</code>```

By that you'll see how many iterations has had the loop. If the final value of service_count is the length of the variable res you can do this:

```<code>var service_count = res.length;
console.log('service_charge_count: =====> '+service_count);
</code>```

Title: How to Count data in for loop nodejs

Body:
How to Count data in for loop nodejs

var service_count = 0;
for (let i = 0; i < res.length; i++) {
    service_count += i;
    console.log('service_charge_count: =====> '+service_count);
}

Body:
By adding i to your variable, you're adding in the first loop 0, in the second loop 1, in the third loop 2. So you're not counting anything.

var service_count=0;
for(let i=0;i<res.length;i++){
    service_count++;
}
console.log('service_charge_count: =====> '+service_count);

By that you'll see how many iterations has had the loop. If the final value of service_count is the length of the variable res you can do this:

var service_count = res.length;
console.log('service_charge_count: =====> '+service_count);


问:
Can't loop through laravel collection array
stuck on collection array

I am getting the specfic array. but can't loop throught in blade

this is my controller:

```<code>public function appliedJob($id)
{

   $apllied = AplliedJob::with('user','job')->find($id);

    return view('dashboardviews.page.apllied-job',compact('apllied'));
 }
</code>```

this my model:

```<code>   class AplliedJob extends Model
   {

   use Notifiable;
   protected $fillable = [
    'name', 'email', 'message','aplied_cv',
   ];
   protected  $table='appllied_jobs';
   //protected $primaryKey = 'user_id';

   protected $primaryKey = 'user_id';

   public function user()
   {
    return $this->belongsTo('App\User','user_id');
   }
   public function job()
   {

   return $this->belongsTo('App\Job','job_id');
   }

   }
</code>```

this the array I am getting I want to access relation# [job] but it
       throws an error

```<code>   AplliedJob {#257 ▼
   #fillable: array:4 [▶]
   #table: "appllied_jobs"
   #primaryKey: "user_id"
   #connection: "mysql"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:9 [▶]
   #original: array:9 [▶]
   #changes: []
   #casts: []
   #dates: []
   #dateFormat: null
   #appends: []
   #dispatchesEvents: []
   #observables: []
   #relations: array:2 [▼
   "user" => User {#263 ▼
   #fillable: array:4 [▶]
   #table: "users"
   #hidden: array:2 [▶]
   #casts: array:1 [▶]
   #connection: "mysql"
   #primaryKey: "id"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:9 [▶]
   #original: array:9 [▶]
   #changes: []
   #dates: []
   #dateFormat: null
   #appends: []
   #dispatchesEvents: []
   #observables: []
   #relations: []
   #touches: []
   +timestamps: true
   #visible: []
   #guarded: array:1 [▶]
   #rememberTokenName: "remember_token"
   }
   "job" => Job {#261 ▼
   #fillable: array:4 [▶]
   #table: "jobs"
   #connection: "mysql"
   #primaryKey: "id"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:10 [▼
    "id" => 1
    "user_id" => 2
    "jb_name" => "web developer"
    "jb_type" => "software"
    "jb_salary" => "12000"
    "jb_exp" => "12"
    "jb_description" => "djghnbjkguyfgykgvkvbuykgbkub g uiygjghpiu p;"
    "jb_loc" => "lahore"
    "created_at" => "2019-05-15 01:18:46"
    "updated_at" => "2019-05-15 01:18:46"
     ]
     #original: array:10 [▶]
     #changes: []
     #casts: []
     #dates: []
     #dateFormat: null
     #appends: []
     #dispatchesEvents: []
     #observables: []
     #relations: []
     #touches: []
     +timestamps: true
     #hidden: []
     #visible: []
     #guarded: array:1 [▶]
      }
     ]
     #touches: []
     +timestamps: true
     #hidden: []
     #visible: []
     #guarded: array:1 [▶]
      }
</code>```

i have tried this but it gives an exception

```<code>     @foreach($apllied as $aplil)

     {{$aplil->job->jb_name}}

     @endforeach
</code>```

this the error I am getting and can't figure out what am I doing wrong

```<code>     ErrorException (E_ERROR)
     Trying to get property 'job' of non-object (View:
    D:\xampp\htdocs\locojobs\resources\views\dashboardviews\page\apllied-
    job.blade.php)
</code>```

答:
Try to use get() or paginate() instead of find(), because the find() returns single value.

Try the below code,

```<code>public function appliedJob($id)
{

   $apllied = AplliedJob::with('user')->with('job')->get();

    return view('dashboardviews.page.apllied-job',compact('apllied'));
}
</code>```

Body:
stuck on collection array

I am getting the specfic array. but can't loop throught in blade

this is my controller:

public function appliedJob($id)
{

   $apllied = AplliedJob::with('user','job')->find($id);

    return view('dashboardviews.page.apllied-job',compact('apllied'));
 }

this my model:

   class AplliedJob extends Model
   {

   use Notifiable;
   protected $fillable = [
    'name', 'email', 'message','aplied_cv',
   ];
   protected  $table='appllied_jobs';
   //protected $primaryKey = 'user_id';

   protected $primaryKey = 'user_id';

   public function user()
   {
    return $this->belongsTo('App\User','user_id');
   }
   public function job()
   {

   return $this->belongsTo('App\Job','job_id');
   }

   }

this the array I am getting I want to access relation# [job] but it
       throws an error

   AplliedJob {#257 ▼
   #fillable: array:4 [▶]
   #table: "appllied_jobs"
   #primaryKey: "user_id"
   #connection: "mysql"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:9 [▶]
   #original: array:9 [▶]
   #changes: []
   #casts: []
   #dates: []
   #dateFormat: null
   #appends: []
   #dispatchesEvents: []
   #observables: []
   #relations: array:2 [▼
   "user" => User {#263 ▼
   #fillable: array:4 [▶]
   #table: "users"
   #hidden: array:2 [▶]
   #casts: array:1 [▶]
   #connection: "mysql"
   #primaryKey: "id"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:9 [▶]
   #original: array:9 [▶]
   #changes: []
   #dates: []
   #dateFormat: null
   #appends: []
   #dispatchesEvents: []
   #observables: []
   #relations: []
   #touches: []
   +timestamps: true
   #visible: []
   #guarded: array:1 [▶]
   #rememberTokenName: "remember_token"
   }
   "job" => Job {#261 ▼
   #fillable: array:4 [▶]
   #table: "jobs"
   #connection: "mysql"
   #primaryKey: "id"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:10 [▼
    "id" => 1
    "user_id" => 2
    "jb_name" => "web developer"
    "jb_type" => "software"
    "jb_salary" => "12000"
    "jb_exp" => "12"
    "jb_description" => "djghnbjkguyfgykgvkvbuykgbkub g uiygjghpiu p;"
    "jb_loc" => "lahore"
    "created_at" => "2019-05-15 01:18:46"
    "updated_at" => "2019-05-15 01:18:46"
     ]
     #original: array:10 [▶]
     #changes: []
     #casts: []
     #dates: []
     #dateFormat: null
     #appends: []
     #dispatchesEvents: []
     #observables: []
     #relations: []
     #touches: []
     +timestamps: true
     #hidden: []
     #visible: []
     #guarded: array:1 [▶]
      }
     ]
     #touches: []
     +timestamps: true
     #hidden: []
     #visible: []
     #guarded: array:1 [▶]
      }

i have tried this but it gives an exception

     @foreach($apllied as $aplil)

     {{$aplil->job->jb_name}}

     @endforeach

this the error I am getting and can't figure out what am I doing wrong

     ErrorException (E_ERROR)
     Trying to get property 'job' of non-object (View:
    D:\xampp\htdocs\locojobs\resources\views\dashboardviews\page\apllied-
    job.blade.php)

Body:
Try to use get() or paginate() instead of find(), because the find() returns single value.

Try the below code,

public function appliedJob($id)
{

   $apllied = AplliedJob::with('user')->with('job')->get();

    return view('dashboardviews.page.apllied-job',compact('apllied'));
}


问:
Custom Tensorflow operation taking a list of mutable input tensors
I'm trying to program a custom Tensorflow operation in C++. This operation should take a list of tensors as input and modify their content. I thought to use the example of the Assign operation, which is registered as follows in the Tensorflow code:

```<code>REGISTER_OP("Assign")
    .Input("ref: Ref(T)")
    .Input("value: T")
    .Output("output_ref: Ref(T)")
    .Attr("T: type")
    ...
</code>```

For reference, input(0) of the Assign operation (ref) is the tensor to assign to, and input(1) (value) is its new value. The output tensor (output_ref) is simply a reference to the input(0) propagated.

In its definition, the Assign operation also has the following code to check that the first input is a mutable tensor:

```<code>OP_REQUIRES(context, IsRefType(context->input_type(0)),
errors::InvalidArgument("lhs input needs to be a ref type"));
</code>```

Contrary to the Assign operation, my custom operation should take a list of mutable tensors (rather than a single tensor) who's content will be modified by the operation.

I tried registering my operation the following way:

```<code>REGISTER_OP("MyCustomOperation")
    .Input("refs: list(Ref(T))")
    .Attr("T: type")
    ...
</code>```

But when loading the library, Tensorflow gives me the following error:

```<code>tensorflow.python.framework.errors_impl.InvalidArgumentError: Reference to unknown attr 'list' from Input("refs: list(Ref(T))") for Op MyCustomOperation
</code>```

I also tried refs: list(T) with the attribute T: Ref(type), but this doesn't work either (Tensorflow prints the error Trouble parsing type string at 'Ref(type)' from Attr("T: Ref(type)")).

So I switched to the following registration:

```<code>REGISTER_OP("MyCustomOperation")
    .Input("refs: list(Ref(T))")
    .Attr("T: type")
    ...
</code>```

With this definition however, the IsRefType assertion fails. Note that I'm passing a list of tf.RefVariable at Python level, which I assume are mutable.

How can I make my operation properly expect a list of mutable tensors?

答:
After some investigation, I found an example of an operation that does that. Here  is the solution for passing a list of mutable tensors:</p>

```<code>REGISTER_OP("MyCustomOperation")
    .Input("refs: Ref(N * T)")
    .Attr("T: type")
    .Attr("N: int")
    ...
</code>```

Body:
I'm trying to program a custom Tensorflow operation in C++. This operation should take a list of tensors as input and modify their content. I thought to use the example of the Assign operation, which is registered as follows in the Tensorflow code:

REGISTER_OP("Assign")
    .Input("ref: Ref(T)")
    .Input("value: T")
    .Output("output_ref: Ref(T)")
    .Attr("T: type")
    ...

For reference, input(0) of the Assign operation (ref) is the tensor to assign to, and input(1) (value) is its new value. The output tensor (output_ref) is simply a reference to the input(0) propagated.

In its definition, the Assign operation also has the following code to check that the first input is a mutable tensor:

OP_REQUIRES(context, IsRefType(context->input_type(0)),
errors::InvalidArgument("lhs input needs to be a ref type"));

Contrary to the Assign operation, my custom operation should take a list of mutable tensors (rather than a single tensor) who's content will be modified by the operation.

I tried registering my operation the following way:

REGISTER_OP("MyCustomOperation")
    .Input("refs: list(Ref(T))")
    .Attr("T: type")
    ...

But when loading the library, Tensorflow gives me the following error:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Reference to unknown attr 'list' from Input("refs: list(Ref(T))") for Op MyCustomOperation

I also tried refs: list(T) with the attribute T: Ref(type), but this doesn't work either (Tensorflow prints the error Trouble parsing type string at 'Ref(type)' from Attr("T: Ref(type)")).

So I switched to the following registration:

REGISTER_OP("MyCustomOperation")
    .Input("refs: list(Ref(T))")
    .Attr("T: type")
    ...

With this definition however, the IsRefType assertion fails. Note that I'm passing a list of tf.RefVariable at Python level, which I assume are mutable.

How can I make my operation properly expect a list of mutable tensors?

Body:
After some investigation, I found an example of an operation that does that. Here  is the solution for passing a list of mutable tensors:

REGISTER_OP("MyCustomOperation")
    .Input("refs: Ref(N * T)")
    .Attr("T: type")
    .Attr("N: int")
    ...