问:
C++ converting string to time_t question
Im trying to convert a string such as "12 August 2011" into time_t or that seconds elapsed, or whatever so I can use it to compare a list of dates.

At the moment, I have tried the following but the output seems to equal false! Also, the seconds elapsed seem to keep changing?

Is this correct?

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>

using namespace std;

int main()
{

    struct tm tmlol, tmloltwo;
    time_t t, u;

    t = mktime(&tmlol);
    u = mktime(&tmloltwo);
    //char test[] = "01/01/2008";string test = "01/01/2008";

    strptime("10 February 2010", "%d %b %Y", &tmlol);
    strptime("10 February 2010", "%d %b %Y", &tmloltwo);

    t = mktime(&tmlol);
    u = mktime(&tmloltwo);

    cout << t << endl;
    cout << u << endl;

    if (u>t)
    {
        cout << "true" << endl;
    }
    else if (u==t)
    {
        cout << "same" << endl;
    }
    else
    {
        cout << "false" << endl;
    }

    cout << (u-t);
}
</code>```

答:
You should initialize the structs before use.  Try this:</p>

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>

using namespace std;

int main()
{
    struct tm tmlol, tmloltwo;
    time_t t, u;

    // initialize declared structs
    memset(&tmlol, 0, sizeof(struct tm));
    memset(&tmloltwo, 0, sizeof(struct tm));

    strptime("10 February 2010", "%d %b %Y", &tmlol);
    strptime("10 February 2010", "%d %b %Y", &tmloltwo);

    t = mktime(&tmlol);
    u = mktime(&tmloltwo);

    cout << t << endl;
    cout << u << endl;

    if (u>t)
    {
        cout << "true" << endl;
    }
    else if (u==t)
    {
        cout << "same" << endl;
    }
    else
    {
        cout << "false" << endl;
    }

    cout << (u-t) << endl;

    return 0;
}
</code>```

Body:
Im trying to convert a string such as "12 August 2011" into time_t or that seconds elapsed, or whatever so I can use it to compare a list of dates.

At the moment, I have tried the following but the output seems to equal false! Also, the seconds elapsed seem to keep changing?

Is this correct?

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>

using namespace std;

int main()
{

    struct tm tmlol, tmloltwo;
    time_t t, u;

    t = mktime(&tmlol);
    u = mktime(&tmloltwo);
    //char test[] = "01/01/2008";string test = "01/01/2008";

    strptime("10 February 2010", "%d %b %Y", &tmlol);
    strptime("10 February 2010", "%d %b %Y", &tmloltwo);

    t = mktime(&tmlol);
    u = mktime(&tmloltwo);

    cout << t << endl;
    cout << u << endl;

    if (u>t)
    {
        cout << "true" << endl;
    }
    else if (u==t)
    {
        cout << "same" << endl;
    }
    else
    {
        cout << "false" << endl;
    }

    cout << (u-t);
}

Body:
You should initialize the structs before use.  Try this:

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>

using namespace std;

int main()
{
    struct tm tmlol, tmloltwo;
    time_t t, u;

    // initialize declared structs
    memset(&tmlol, 0, sizeof(struct tm));
    memset(&tmloltwo, 0, sizeof(struct tm));

    strptime("10 February 2010", "%d %b %Y", &tmlol);
    strptime("10 February 2010", "%d %b %Y", &tmloltwo);

    t = mktime(&tmlol);
    u = mktime(&tmloltwo);

    cout << t << endl;
    cout << u << endl;

    if (u>t)
    {
        cout << "true" << endl;
    }
    else if (u==t)
    {
        cout << "same" << endl;
    }
    else
    {
        cout << "false" << endl;
    }

    cout << (u-t) << endl;

    return 0;
}


来源: stackexchange

问:
Hybrid sorting using insertion sort and merge sort
I wish to implement a hybrid algorithm that switches from insertion sort to merge sort once the input array size becomes too big.

This is my main function (I fixed my input array size at 30 currently as I wish to test my merge sort function) :

```<code>    public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i < a.length; i++){
            if(a[i-1] > a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }
</code>```

Insertion sort is called when the array size is <20, else merge sort is called:

```<code>    public static void imsort(int [] slot, int b, int e, int size) {

        //if smaller than 20, use insertion sort
        if (e-b<=20) {
            insertionSort(slot, e);  //e is the length of slot[]
            System.out.println("imsort entered!");
        }

        else {
            mergesort(b, e, slot);

            System.out.println("mergesort entered!");
        }
    }
</code>```

There is a Index 30 out of bounds error for my merge sort function currently.

```<code>    public static int merge(int n, int m, int[] slot) {
        int mid = (n+m)/2;
        int a = n, b = mid+1, i, tmp, cmp=0, comp=0;

        //sanity check
        if (m-n <= 0) return -1000;

        while (a <= mid && b <= m) {
            cmp = compare(slot[a], slot[b]);
            comp++;

            if (cmp > 0) { //slot[a] > slot[b]
                tmp = slot[b++];
                for (i = ++mid; i > a; i--)
                    slot[i] = slot[i-1];
                    slot[a++] = tmp;
            }

            else if (cmp < 0) //slot[a] < slot[b]
                    a++;

            else {
                //slot[a] == slot[b]
                if (a == mid && b == m) break;
                tmp = slot[b++];
                a++;
                for (i = ++mid; i > a; i--)
                slot[i] = slot[i-1]; slot[a++] = tmp;
            }
        } // end of while loop;

        return comp;
    } // end of merge
</code>```
```<code>    public static int mergesort(int s, int e, int[] slot) {
        //int comp =0;
        int mid = (s+e)/2;
        int right=0, left=0;

        if(e-s>0) {
            //comp++;
            left = mergesort(s,mid, slot);
            //comp++;
            right = mergesort(mid+1,e, slot);
        }
        return right + left + merge(s,e,slot);
    }
</code>```

I am unsure of the error in my merge / mergesort function. Can I get some further advice?

答:
First, let me congratulate on a very good post for someone new. You didn't post the line of code where the error is happening and code isn't complete, so I filled in some blanks and executed it:

```<code>import java.util.Arrays;
import java.util.Random;

public class Test {

    public static int[] genrandarray(int n)
    {
        int[] a = new int[n];
        Random r = new Random();
        for(int i=0;i<n;i++) a[i] = r.nextInt();
        return a;
    }

    public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i < a.length; i++){
            if(a[i-1] > a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }

    public static void imsort(int [] slot, int b, int e, int size) {

        //if smaller than 20, use insertion sort
        if (e-b<=20) {
            Arrays.sort(slot, 0, e);
           System.out.println("imsort entered!");
        }

        else {
            mergesort(b, e, slot);

            System.out.println("mergesort entered!");
        }
    }

    public static int merge(int n, int m, int[] slot) {
        int mid = (n+m)/2;
        int a = n, b = mid+1, i, tmp, cmp=0, comp=0;

        //sanity check
        if (m-n <= 0) return -1000;

        while (a <= mid && b <= m) {
            cmp = slot[a] - slot[b];
            comp++;

            if (cmp > 0) { //slot[a] > slot[b]
                tmp = slot[b++];
                for (i = ++mid; i > a; i--)
                    slot[i] = slot[i-1];
                    slot[a++] = tmp;
            }

            else if (cmp < 0) //slot[a] < slot[b]
                    a++;

            else {
                //slot[a] == slot[b]
                if (a == mid && b == m) break;
                tmp = slot[b++];
                a++;
                for (i = ++mid; i > a; i--)
                slot[i] = slot[i-1]; slot[a++] = tmp;
            }
        } // end of while loop;

        return comp;
    } // end of merge

    public static int mergesort(int s, int e, int[] slot) {
        //int comp =0;
        int mid = (s+e)/2;
        int right=0, left=0;

        if(e-s>0) {
            //comp++;
            left = mergesort(s,mid, slot);
            //comp++;
            right = mergesort(mid+1,e, slot);
        }
        return right + left + merge(s,e,slot);
    }
}
</code>```

The error is caused by setting variable a to n in your merge function and then in the line cmp = slot[a] - slot[b]. Because arrays go from 0 to n-1, n will cause an out of bounds exception.

ContentLicense: CC BY-SA 4.0

Body:
I wish to implement a hybrid algorithm that switches from insertion sort to merge sort once the input array size becomes too big.

This is my main function (I fixed my input array size at 30 currently as I wish to test my merge sort function) :

    public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i  a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }

Insertion sort is called when the array size is <20, else merge sort is called:

    public static void imsort(int [] slot, int b, int e, int size) {

        //if smaller than 20, use insertion sort
        if (e-b<=20) {
            insertionSort(slot, e);  //e is the length of slot[]
            System.out.println("imsort entered!");
        }

        else {
            mergesort(b, e, slot);

            System.out.println("mergesort entered!");
        }
    }

There is a Index 30 out of bounds error for my merge sort function currently.

    public static int merge(int n, int m, int[] slot) {
        int mid = (n+m)/2;
        int a = n, b = mid+1, i, tmp, cmp=0, comp=0;

        //sanity check
        if (m-n <= 0) return -1000;

        while (a <= mid && b <= m) {
            cmp = compare(slot[a], slot[b]);
            comp++;

            if (cmp > 0) { //slot[a] > slot[b]
                tmp = slot[b++];
                for (i = ++mid; i > a; i--)
                    slot[i] = slot[i-1];
                    slot[a++] = tmp;
            }

            else if (cmp < 0) //slot[a] < slot[b]
                    a++;

            else {
                //slot[a] == slot[b]
                if (a == mid && b == m) break;
                tmp = slot[b++];
                a++;
                for (i = ++mid; i > a; i--)
                slot[i] = slot[i-1]; slot[a++] = tmp;
            }
        } // end of while loop;

        return comp;
    } // end of merge

    public static int mergesort(int s, int e, int[] slot) {
        //int comp =0;
        int mid = (s+e)/2;
        int right=0, left=0;

        if(e-s>0) {
            //comp++;
            left = mergesort(s,mid, slot);
            //comp++;
            right = mergesort(mid+1,e, slot);
        }
        return right + left + merge(s,e,slot);
    }

I am unsure of the error in my merge / mergesort function. Can I get some further advice?

Body:
First, let me congratulate on a very good post for someone new. You didn't post the line of code where the error is happening and code isn't complete, so I filled in some blanks and executed it:

import java.util.Arrays;
import java.util.Random;

public class Test {

    public static int[] genrandarray(int n)
    {
        int[] a = new int[n];
        Random r = new Random();
        for(int i=0;i<n;i++) a[i] = r.nextInt();
        return a;
    }

    public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i < a.length; i++){
            if(a[i-1] > a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }

    public static void imsort(int [] slot, int b, int e, int size) {

        //if smaller than 20, use insertion sort
        if (e-b<=20) {
            Arrays.sort(slot, 0, e);
           System.out.println("imsort entered!");
        }

        else {
            mergesort(b, e, slot);

            System.out.println("mergesort entered!");
        }
    }

    public static int merge(int n, int m, int[] slot) {
        int mid = (n+m)/2;
        int a = n, b = mid+1, i, tmp, cmp=0, comp=0;

        //sanity check
        if (m-n <= 0) return -1000;

        while (a <= mid && b <= m) {
            cmp = slot[a] - slot[b];
            comp++;

            if (cmp > 0) { //slot[a] > slot[b]
                tmp = slot[b++];
                for (i = ++mid; i > a; i--)
                    slot[i] = slot[i-1];
                    slot[a++] = tmp;
            }

            else if (cmp < 0) //slot[a] < slot[b]
                    a++;

            else {
                //slot[a] == slot[b]
                if (a == mid && b == m) break;
                tmp = slot[b++];
                a++;
                for (i = ++mid; i > a; i--)
                slot[i] = slot[i-1]; slot[a++] = tmp;
            }
        } // end of while loop;

        return comp;
    } // end of merge

    public static int mergesort(int s, int e, int[] slot) {
        //int comp =0;
        int mid = (s+e)/2;
        int right=0, left=0;

        if(e-s>0) {
            //comp++;
            left = mergesort(s,mid, slot);
            //comp++;
            right = mergesort(mid+1,e, slot);
        }
        return right + left + merge(s,e,slot);
    }
}

The error is caused by setting variable a to n in your merge function and then in the line cmp = slot[a] - slot[b]. Because arrays go from 0 to n-1, n will cause an out of bounds exception.


问:
Django file upload: permission problem, error 13
I'm creating a django module to upload files, and i'm following this django documentation:  FileUploads

But when it executes

destination=destination = open('/media/name.txt','wb+')

it throws this error:

[Errno 13] Permission denied: '/media/name.txt'

My settings are:

a folder 'media' in root of django project

in settings.py MEDIA_ROOT is /home/user/...django_project_folder/media/ and MEDIA_URL is  http://127.0.0.1:8000/media/

folder media has 777 as permissions, and executing ls -l media's owner is the same that runs the project (checked through lsof -i command)

Due these settings, i consider very strange this error.

Some help?

答:
try:

```<code>open('media/name.txt','wb+')
</code>```

insead of:

```<code>open('/media/name.txt','wb+')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
try:

open('media/name.txt','wb+')

insead of:

open('/media/name.txt','wb+')


问:
Display the background image as tiles at Xamarin.Forms
I am using Xamarin.Forms to develop an application for Android.
I am using the Xamarin.
I want to display the background as tiles.
I have prepared an image of 100x100 pixels.
\Android\MyApp\MyApp.Android\Resources\drawable\background.jpg

```<code><?xml version="1.0" encoding="utf-8" ? >
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:viewmodels="clr-namespace:MyApp.ViewModels"
    x:DataType="viewmodels:LoginViewModel"
    mc:Ignorable="d"
    x:Class="MyApp.Views.LoginPage"
    Shell.NavBarIsVisible="False"
    BackgroundImage="background.jpg"
>
</code>```

This way, the background.jpg will be enlarged and displayed.
I want to display it repeatedly in tiles.

答:
```<code>You can display it repeatedly in tiles through below steps.
1.Create a drawable xml file on your Android project:
    <?xml version="1.0" encoding="utf-8" ?>
    <bitmap  xmlns:android="http://schemas.android.com/apk/res/android"
             android:tileMode="repeat"
             android:src="@drawable/clock" >
    </bitmap>
2.After that create below two effect classes on your shared project:
    //base class
    namespace AppTiles
{
    public class BaseEffect : RoutingEffect
    {
        public const string EffectNamespace = "AppTiles";

        public BaseEffect(String effectId) : base($"{EffectNamespace}.
 {effectId}")
        {
        }
    }
}
//effect class
    namespace AppTiles
{
    public class CoverEffect : BaseEffect
    {
        public CoverEffect() : base(nameof(CoverEffect))
        {
        }
    }
}
3.Create a effect class in your Android project
[assembly: ResolutionGroupName("AppTiles") ]
[assembly: ExportEffect(typeof(AppTiles.Droid.CoverEffect),
nameof(CoverEffect))]

namespace AppTiles.Droid
{
    public class CoverEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            UpdateBackground();
        }

        protected override void OnDetached()
        {
        }

        private void UpdateBackground()
        {
            Android.Views.View mView = Container as Android.Views.View;

            if (mView != null)
            {
                mView.Background = ContextCompat.GetDrawable(mView.Context, Resource.Drawable.XMLFile1);
            }
        }
    }
}
4.Add below xmal in shared main page code behind:
  <StackLayout Orientation="Vertical" Spacing="0">

        <StackLayout.Effects>
            <effects:CoverEffect/>
        </StackLayout.Effects>

    </StackLayout>

Below is the screenshot:
</code>```

Body:
I am using Xamarin.Forms to develop an application for Android.
I am using the Xamarin.
I want to display the background as tiles.
I have prepared an image of 100x100 pixels.
\Android\MyApp\MyApp.Android\Resources\drawable\background.jpg

<?xml version="1.0" encoding="utf-8" ? >
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:viewmodels="clr-namespace:MyApp.ViewModels"
    x:DataType="viewmodels:LoginViewModel"
    mc:Ignorable="d"
    x:Class="MyApp.Views.LoginPage"
    Shell.NavBarIsVisible="False"
    BackgroundImage="background.jpg"
>

This way, the background.jpg will be enlarged and displayed.
I want to display it repeatedly in tiles.


问:
Docopt accepts multi args in middle?
I want my script accepts command line args like "cp" command does:

```<code>'''
Usage:
cp.py <source>... <directory>
cp.py -t <directory> <source>...
cp.py -s <source>... -t <directory>
'''
</code>```

Those command line

```<code>$ python cp.py src/path/1 src/path/2 target/path
$ python cp.py -t target/path src/path/1 src/path/2
$ python cp.py -s src/path/1 src/path/2 -t target/path
</code>```

will get the same result:

```<code>{'<source>':['src/path/1', 'src/path/2'],'<directory>': 'target/path'}
</code>```

Thx very much. And sorry for my English:)

答:
Arriving at a similar need and reviewing the question many years later, I'm seeing that the issue referred by the accepted response is still open.

However, I've found out that now there's an alternative library docpie which implements the same principle of parsing the docstring for the cli, yet supports cp syntax. Due to its extreme similarity (and subsequently relative compatibility) to docopt, here's an explicit list of differences.

Title: Docopt accepts multi args in middle?

Body:
I want my script accepts command line args like "cp" command does:

'''
Usage:
cp.py <source>... <directory>
cp.py -t <directory> <source>...
cp.py -s <source>... -t <directory>
'''

Those command line

$ python cp.py src/path/1 src/path/2 target/path
$ python cp.py -t target/path src/path/1 src/path/2
$ python cp.py -s src/path/1 src/path/2 -t target/path

will get the same result:

{'<source>':['src/path/1', 'src/path/2'],'<directory>': 'target/path'}

Thx very much. And sorry for my English:)


问:
What would be the radio equivalent of this ngModel text input form, using spring boot mvc and angular?
I was taking a tutorial on making an employee CRUD model that uses spring boot and mysql server for the backend and angular for the front end. On the Create part it had this form-group (the gender part I was adding new fields).

```<code>    <div class="form-group">
            <label>
                Gender </label>
            <input type="text" class="form-control" id="gender" required [(ngModel)]="employee.gender" name="gender">
        </div>
</code>```

And that would work when submitting it (ie. creating the employee). But I can't figure out how to turn it into a radio button and submit it (it just gets stuck on the create page). This is what I tried to make when following a radio button example.

```<code><div class="form-group">

            <label for [(ngModel)]="employee.gender">Gender:</label>
            <div>
                <input id="male" type="radio" value="male" name="gender" formControlName="gender">
                <label for="male">Male</label>
            </div>

            <div>
                <input id="female" type="radio" value="female" name="gender" formControlName="gender">
                <label for="female">Female</label>
            </div>
        </div>
</code>```

My understanding could use more work, but I'm trying to learn. Any help is appreciated. Thanks

答:
In Angular, there are two different approaches when it comes to working with Forms:

Template-driven forms

Reactive forms

In case of Template-driven forms we make use of ngModel for data binding, whereas in case of Reactive forms we work with FormControls.

The 1st example shared in the question is using Template-driven approach, and the radio button equivalent code with two options to choose from, would be:

  Gender:

    <input id="male" type="radio" value="male" name="gender" [(ngModel)]="employee.gender">
    Male

    <input id="female" type="radio" value="female" name="gender" [(ngModel)]="employee.gender">
    Female

```

In case of Reactive forms approach, you can simply replace [(ngModel)]="employee.gender" with formControlName="gender" provided you have defined a FormControl named gender within your FormGroup.

Body:
I was taking a tutorial on making an employee CRUD model that uses spring boot and mysql server for the backend and angular for the front end. On the Create part it had this form-group (the gender part I was adding new fields).

                Gender
            <input type="text" class="form-control" id="gender" required [(ngModel)]="employee.gender" name="gender">

And that would work when submitting it (ie. creating the employee). But I can't figure out how to turn it into a radio button and submit it (it just gets stuck on the create page). This is what I tried to make when following a radio button example.

            Gender:

                <input id="male" type="radio" value="male" name="gender" formControlName="gender">
                Male

                <input id="female" type="radio" value="female" name="gender" formControlName="gender">
                Female

My understanding could use more work, but I'm trying to learn. Any help is appreciated. Thanks

Body:
In Angular, there are two different approaches when it comes to working with Forms:

Template-driven forms

Reactive forms

In case of Template-driven forms we make use of ngModel for data binding, whereas in case of Reactive forms we work with FormControls.

The 1st example shared in the question is using Template-driven approach, and the radio button equivalent code with two options to choose from, would be:

<div class="form-group">
  <label>Gender:</label>
  <div>
    <input id="male" type="radio" value="male" name="gender" [(ngModel)]="employee.gender">
    <label for="male">Male</label>
  </div>

  <div>
    <input id="female" type="radio" value="female" name="gender" [(ngModel)]="employee.gender">
    <label for="female">Female</label>
  </div>
</div>

In case of Reactive forms approach, you can simply replace [(ngModel)]="employee.gender" with formControlName="gender" provided you have defined a FormControl named gender within your FormGroup.


问:
How can i resolve System.Object error when running app service in Azure?
I have successfully deployed and can run my app service in Azure.
But i get the error:

```<code> d:\home\site\wwwroot\Views\Shared\_Layout.cshtml(42):
 The type 'System.Object' is defined in an assembly that is not referenced.
 You must add a reference to assembly 'System.Runtime, Version=4.0.0.0,
</code>```

I have looked at the error logs , but there is nothing really informative that can help.
Where can i look to try and resolve this ?

```<code>   <Reference Include="System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b02f8f7f22d50a8a, processorArchitecture=MSIL">
  <HintPath>..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll</HintPath>
  <Private>True</Private>
  <Private>True</Private>
</Reference>
</code>```

here is what is in packages

```<code><package id="System.Runtime" version="4.3.0" targetFramework="net472" />
</code>```

答:
I have tried to repro with the given packages in .csproj file, got the same issue.
-In .csproj file
Added below snippet

<Reference Include="System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b02f8f7f22d50a8a, processorArchitecture=MSIL">
 <HintPath>..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll</HintPath>
 <Private>True</Private>
 <Private>True</Private>
</Reference>
```
<p>I am getting the error,</p>
<p>-In .<em><strong>csproj</strong></em> file , Add</p>
<pre class="lang-cs prettyprint-override"><code>  <Reference Include="System.Runtime"/>
</code>```

Delete the existing System.Runtime reference from bin folder.

Add System.Runtime package in web.config file.

<compilation targetFramework="*.*" debug="true" >
  <assemblies>
   <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </assemblies>
</compilation>
```

Body:
I have successfully deployed and can run my app service in Azure.
But i get the error:

 d:\home\site\wwwroot\Views\Shared\_Layout.cshtml(42):
 The type 'System.Object' is defined in an assembly that is not referenced.
 You must add a reference to assembly 'System.Runtime, Version=4.0.0.0,

I have looked at the error logs , but there is nothing really informative that can help.
Where can i look to try and resolve this ?

   <Reference Include="System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b02f8f7f22d50a8a, processorArchitecture=MSIL">
  <HintPath>..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll</HintPath>
  <Private>True</Private>
  <Private>True</Private>
</Reference>

here is what is in packages

<package id="System.Runtime" version="4.3.0" targetFramework="net472" />

Body:
I have tried to repro with the given packages in .csproj file, got the same issue.
-In .csproj file
Added below snippet

<Reference Include="System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b02f8f7f22d50a8a, processorArchitecture=MSIL">
 <HintPath>..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll</HintPath>
 <Private>True</Private>
 <Private>True</Private>
</Reference>

I am getting the error,

-In .csproj file , Add

  <Reference Include="System.Runtime"/>

Delete the existing System.Runtime reference from bin folder.

Add System.Runtime package in web.config file.

<compilation targetFramework="*.*" debug="true" >
  <assemblies>
   <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </assemblies>
</compilation>


问:
How to use Azurite for Integration test in Blobs
Azurite does not connect with my local project for saving blobs inside local emulator.
I am trying to connect Azurite with my Integration test in blob storage? any guide</p>

答:
if you need a way to write integration test for blobs (Upload,Delete , get) you can use Azureit for that.
Azureit is inbuid in VS 2022, so can install Azurite and use it by mentioning your connection string as "ConnectionString": "UseDevelopmentStorage=true;"
up and run the Azureit. you can find application in
Visual Studio\2022\Professional\Common7\IDE\Extensions\Microsoft\Azure Storage Emulator (run as admin)
C:\Program Files\Microsoft


问:
How to see the latest version of the package in package.json?
Using PhpStorm 2021.1.4 In composer.json of my project with current version of any package I see latest version of this package, but package.json does not show this option.

This is what I see in composer.json:

But what I see in package.json:

Is it configurable somehow ?

答: Inside Intellij Idea & WebStorm/PhpStorm you can go to package.json and hover+Cmd key (windows Ctrl key) the package name and a nice tooltip with the latest version will pop up, for example:


问:
Submit Adaptive Cards in MSTeams with Outgoing Webhook
I am following Add Outgoing Webhooks to show an adaptive card with text prompt:

```<code>{
    "type": "message",
    "attachments": [
        {
            "contentType": "application/vnd.microsoft.card.adaptive",
            "content": {
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.3",
    "body": [
        {
            "type": "TextBlock",
            "size": "Medium",
            "weight": "Bolder",
            "text": " Input.Text elements",
            "horizontalAlignment": "Center",
            "wrap": true
        },
        {
            "type": "TextBlock",
            "text": "Comments",
            "wrap": true
        },
        {
            "type": "Input.Text",
            "isMultiline": true,
            "id": "MultiLineVal"
        }
    ],
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Submit",
            "data": {
                "id": "1234567890"
            }
        },
        {
            "type": "Action.ShowCard",
            "title": "Show Card",
            "card": {
                "type": "AdaptiveCard",
                "body": [
                    {
                        "type": "TextBlock",
                        "text": "Enter comment",
                        "wrap": true
                    },
                    {
                        "type": "Input.Text",
                        "id": "CommentVal"
                    }
                ],
                "actions": [
                    {
                        "type": "Action.Submit",
                        "title": "OK"
                    }
                ],
                "$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
            }
        }
    ]
}
        }
    ]
}
</code>```

The card json is generated from standard input template on https://adaptivecards.io/designer/

The bot is configured with https://teamsbot.free.beeceptor.com/test4 as an outgoing webhook:

Messaging the bot works, I see the request on https://beeceptor.com/console/teamsbot, it returns the mock and I get the card showing in teams.

When I click "Submit" I get Something went wrong. Please try again. error:

There is no new requests on beeceptor, and I see 2 consecutive 400 error in the chrome devtools:

```<code>curl 'https://uk.ng.msg.teams.microsoft.com/v1/agents/f9f5e125-xxxx-xxxx-xxxx-9a9a8dcb1824/invoke' \
  -H 'authority: uk.ng.msg.teams.microsoft.com' \
  ... many irrelevant headers ...
  -H 'accept: json' \
  -H 'x-ms-client-version: 1415/1.0.0.2022020411' \
  -H 'x-ms-user-type: null' \
  -H 'authentication: skypetoken=eyJhbGciOiJSUzI...very long token ... zZy_S4a0zp8m_a72SMuew' \
  -H 'origin: https://teams.microsoft.com' \
  -H 'referer: https://teams.microsoft.com/' \
  --data-raw '{"value":{"id":"1234567890"},"conversation":{"id":"19:F32YIP...long id...@thread.tacv2;messageid=1644066509347"},"clientMessageId":"3673456194497933931","serverMessageId":"1644067693444","messageType":"RichText/Media_Card","name":"messageback","imdisplayname":"Azure Admin","complianceData":{"action":{"type":"Action.Submit","title":"Submit"}}}'
</code>```

results with 400 response with following body:

```<code>{"errorCode":201,"message":"The resource URL agentMri is misformatted."}
</code>```

The request is followed by the very similar one:

```<code>curl 'https://uk.ng.msg.teams.microsoft.com/v1/agents/f9f5e125-xxxx-xxxx-xxxx-9a9a8dcb1824/invoke' \
  -H 'authority: uk.ng.msg.teams.microsoft.com' \
  ... same irrelevant headers ...
  -H 'accept: json' \
  -H 'x-ms-client-version: 1415/1.0.0.2022020411' \
  -H 'x-ms-user-type: null' \
  -H 'authentication: skypetoken=eyJhbGciOiJSUz ... same token ...tzZy_S4a0zp8m_a72SMuew' \
  -H 'origin: https://teams.microsoft.com' \
  -H 'referer: https://teams.microsoft.com/' \
  --data-raw '{"value":{"id":"1234567890","MultiLineVal":"My comment"},"conversation":{"id":"19:F32YIP...same id..1@thread.tacv2;messageid=1644066509347"},"clientMessageId":"3673456194497933931","serverMessageId":"1644067693444","messageType":"RichText/Media_Card","name":"messageback","imdisplayname":"Azure Admin","complianceData":{"action":{"type":"Action.Submit","title":"Submit"}}}'
</code>```

Response is the same 400:

```<code>{"errorCode":201,"message":"The resource URL agentMri is misformatted."}
</code>```

The only difference I could spot is the --data-raw '{"value":{"id":"1234567890","MultiLineVal":"My comment"}," part. The second request has "MultiLineVal":"My comment". It is exactly what I would like to see on the beeceptor side, but it never reached the API.

It's not quite clear what is agentMri, where and how it is misformatted, and what to change in the adaptive card to make the form submitted to the same webhook domain. I am not sure if this agentMri "misformattion" is related, but it was the only http request from Teams that contained the string I entered in the adaptive card.

答:
Outgoing Webhooks can't use any card actions except for openURL.

Document ref: Key features of Outgoing Webhook:

Standard HTTP message exchange
Responses appear in the same chain as the original request message and can include any Bot Framework message content. For example, rich text, images, cards, and emojis. Although Outgoing Webhooks can use cards, they can't use any card actions except for openURL.

Body:
I am following Add Outgoing Webhooks to show an adaptive card with text prompt:

{
    "type": "message",
    "attachments": [
        {
            "contentType": "application/vnd.microsoft.card.adaptive",
            "content": {
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.3",
    "body": [
        {
            "type": "TextBlock",
            "size": "Medium",
            "weight": "Bolder",
            "text": " Input.Text elements",
            "horizontalAlignment": "Center",
            "wrap": true
        },
        {
            "type": "TextBlock",
            "text": "Comments",
            "wrap": true
        },
        {
            "type": "Input.Text",
            "isMultiline": true,
            "id": "MultiLineVal"
        }
    ],
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Submit",
            "data": {
                "id": "1234567890"
            }
        },
        {
            "type": "Action.ShowCard",
            "title": "Show Card",
            "card": {
                "type": "AdaptiveCard",
                "body": [
                    {
                        "type": "TextBlock",
                        "text": "Enter comment",
                        "wrap": true
                    },
                    {
                        "type": "Input.Text",
                        "id": "CommentVal"
                    }
                ],
                "actions": [
                    {
                        "type": "Action.Submit",
                        "title": "OK"
                    }
                ],
                "$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
            }
        }
    ]
}
        }
    ]
}

The card json is generated from standard input template on https://adaptivecards.io/designer/

The bot is configured with https://teamsbot.free.beeceptor.com/test4 as an outgoing webhook:

Messaging the bot works, I see the request on https://beeceptor.com/console/teamsbot, it returns the mock and I get the card showing in teams.

When I click "Submit" I get Something went wrong. Please try again. error:

There is no new requests on beeceptor, and I see 2 consecutive 400 error in the chrome devtools:

curl 'https://uk.ng.msg.teams.microsoft.com/v1/agents/f9f5e125-xxxx-xxxx-xxxx-9a9a8dcb1824/invoke' \
  -H 'authority: uk.ng.msg.teams.microsoft.com' \
  ... many irrelevant headers ...
  -H 'accept: json' \
  -H 'x-ms-client-version: 1415/1.0.0.2022020411' \
  -H 'x-ms-user-type: null' \
  -H 'authentication: skypetoken=eyJhbGciOiJSUzI...very long token ... zZy_S4a0zp8m_a72SMuew' \
  -H 'origin: https://teams.microsoft.com' \
  -H 'referer: https://teams.microsoft.com/' \
  --data-raw '{"value":{"id":"1234567890"},"conversation":{"id":"19:F32YIP...long id...@thread.tacv2;messageid=1644066509347"},"clientMessageId":"3673456194497933931","serverMessageId":"1644067693444","messageType":"RichText/Media_Card","name":"messageback","imdisplayname":"Azure Admin","complianceData":{"action":{"type":"Action.Submit","title":"Submit"}}}'

results with 400 response with following body:

{"errorCode":201,"message":"The resource URL agentMri is misformatted."}

The request is followed by the very similar one:

curl 'https://uk.ng.msg.teams.microsoft.com/v1/agents/f9f5e125-xxxx-xxxx-xxxx-9a9a8dcb1824/invoke' \
  -H 'authority: uk.ng.msg.teams.microsoft.com' \
  ... same irrelevant headers ...
  -H 'accept: json' \
  -H 'x-ms-client-version: 1415/1.0.0.2022020411' \
  -H 'x-ms-user-type: null' \
  -H 'authentication: skypetoken=eyJhbGciOiJSUz ... same token ...tzZy_S4a0zp8m_a72SMuew' \
  -H 'origin: https://teams.microsoft.com' \
  -H 'referer: https://teams.microsoft.com/' \
  --data-raw '{"value":{"id":"1234567890","MultiLineVal":"My comment"},"conversation":{"id":"19:F32YIP...same id..1@thread.tacv2;messageid=1644066509347"},"clientMessageId":"3673456194497933931","serverMessageId":"1644067693444","messageType":"RichText/Media_Card","name":"messageback","imdisplayname":"Azure Admin","complianceData":{"action":{"type":"Action.Submit","title":"Submit"}}}'

Response is the same 400:

{"errorCode":201,"message":"The resource URL agentMri is misformatted."}

The only difference I could spot is the --data-raw '{"value":{"id":"1234567890","MultiLineVal":"My comment"}," part. The second request has "MultiLineVal":"My comment". It is exactly what I would like to see on the beeceptor side, but it never reached the API.

It's not quite clear what is agentMri, where and how it is misformatted, and what to change in the adaptive card to make the form submitted to the same webhook domain. I am not sure if this agentMri "misformattion" is related, but it was the only http request from Teams that contained the string I entered in the adaptive card.


问:
Get Pixel color of UIImage
How can I get the RGB value of a particular pixel in a UIImage?</p>

答:
Try this very simple code:

I used to detect a wall in my maze game (the only info that I need is the alpha channel, but I included the code to get the other colors for you):

```<code>- (BOOL)isWallPixel:(UIImage *)image xCoordinate:(int)x yCoordinate:(int)y {

    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int pixelInfo = ((image.size.width  * y) + x ) * 4; // The image is png

    //UInt8 red = data[pixelInfo];         // If you need this info, enable it
    //UInt8 green = data[(pixelInfo + 1)]; // If you need this info, enable it
    //UInt8 blue = data[pixelInfo + 2];    // If you need this info, enable it
    UInt8 alpha = data[pixelInfo + 3];     // I need only this info for my maze game
    CFRelease(pixelData);

    //UIColor* color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f]; // The pixel color info

    if (alpha) return YES;
    else return NO;

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Get Pixel color of UIImage

Body:
Try this very simple code:

I used to detect a wall in my maze game (the only info that I need is the alpha channel, but I included the code to get the other colors for you):

- (BOOL)isWallPixel:(UIImage *)image xCoordinate:(int)x yCoordinate:(int)y {

    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int pixelInfo = ((image.size.width  * y) + x ) * 4; // The image is png

    //UInt8 red = data[pixelInfo];         // If you need this info, enable it
    //UInt8 green = data[(pixelInfo + 1)]; // If you need this info, enable it
    //UInt8 blue = data[pixelInfo + 2];    // If you need this info, enable it
    UInt8 alpha = data[pixelInfo + 3];     // I need only this info for my maze game
    CFRelease(pixelData);

    //UIColor* color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f]; // The pixel color info

    if (alpha) return YES;
    else return NO;

}


问:
Split ARRAY into chunks as they appear in sequence
I got an array of objects which I need to make into three chunks in the sequence as they are in the original array. For eg.

```<code>let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];
</code>```

This array needs to be split like this:

```<code>let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};
</code>```

答:
Maybe this approach would be useful

const data = [{1:1}, {2:2}, {3:3}, {4:4}, {5:5}, {6:6}, {7:7}, {8:8}, {9:9}, {10:10}];

const chunk = (arr, n) => arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

const chunks = chunk(data, 3);
const rotated = chunks[0].map((_, colIndex) => chunks.map(row => row[colIndex]));
const result = rotated.map((arr, index) =>
  ({ [index]: arr.filter(Boolean) }));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

Body:
I got an array of objects which I need to make into three chunks in the sequence as they are in the original array. For eg.

let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];

This array needs to be split like this:

let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};

Body:
Maybe this approach would be useful

const data = [{1:1}, {2:2}, {3:3}, {4:4}, {5:5}, {6:6}, {7:7}, {8:8}, {9:9}, {10:10}];

const chunk = (arr, n) => arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

const chunks = chunk(data, 3);
const rotated = chunks[0].map((_, colIndex) => chunks.map(row => row[colIndex]));
const result = rotated.map((arr, index) =>
  ({ [index]: arr.filter(Boolean) }));

console.log(result);

.as-console-wrapper{min-height: 100%!important; top: 0}


问:
Highcharts Pie Chart - slice color dependent of category
I would like to make the color of the slices dependend of the category['A','B','C','D']. Example, if the category 'B' is in the dataset, it should always be orange. My example doesn't work because I use the keys attribute in combination with data and it should be category. I don't seem to find a way doing this if at all possible?

```<code>{
series: [{
keys: ['y', 'color'],
data: [
  ['A', 'red'],
  ['B', 'orange'],
  ['C', '#abcf44'],
  ['D', '#acb222']
]
}]
</code>```

}

Dataset:

Category          %
A               10%
B               30%
C               10%
D               30%

Dataset
Example pie

答:
You can define your data as an array of objects with defined name, color and y properties:

```<code>  series: [{
    type: 'pie',
    data: [{
      name: 'A',
      color: 'red',
      y: 10
    }, {
      name: 'C',
      color: 'orange',
      y: 30
    }, {
      name: 'D',
      color: '#abcf44',
      y: 10
    }]
  }]
</code>```

Live demo: http://jsfiddle.net/BlackLabel/jenfgwdk/

API Reference: https://api.highcharts.com/highcharts/series.pie.data

Body:
I would like to make the color of the slices dependend of the category['A','B','C','D']. Example, if the category 'B' is in the dataset, it should always be orange. My example doesn't work because I use the keys attribute in combination with data and it should be category. I don't seem to find a way doing this if at all possible?

{
series: [{
keys: ['y', 'color'],
data: [
  ['A', 'red'],
  ['B', 'orange'],
  ['C', '#abcf44'],
  ['D', '#acb222']
]
}]

}

Dataset:

Category          %
A               10%
B               30%
C               10%
D               30%

Dataset
Example pie

Body:
You can define your data as an array of objects with defined name, color and y properties:

  series: [{
    type: 'pie',
    data: [{
      name: 'A',
      color: 'red',
      y: 10
    }, {
      name: 'C',
      color: 'orange',
      y: 30
    }, {
      name: 'D',
      color: '#abcf44',
      y: 10
    }]
  }]

Live demo: http://jsfiddle.net/BlackLabel/jenfgwdk/

API Reference: https://api.highcharts.com/highcharts/series.pie.data


问:
Typescript: type guard for whether an object property is defined, when the key is a wide type?
I have a function that returns whether an object property is undefined. I need this function instead of just doing obj[key] === undefined because otherwise I'd sometimes get Property 'foo' does not exist on type 'Bar'.. It's straightforward to write the type when the property key is a literal. I.e.:

```<code>function hasDefinedProp<
  Obj extends Partial<Record<string, any>>,
  Prop extends string,
>(
  obj: Obj,
  prop: Prop,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
  return obj[prop] !== undefined;
}

const obj: Partial<Record<string, number>> = {};
if (hasDefinedProp(obj, 'foo')) {
    obj.foo + 1; // No error.
    obj.bar + 1; // "Object is possibly 'undefined'."
}
</code>```

However, this doesn't work when the key's type is a wide type, i.e.:

```<code>const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}
</code>```

Is it possible to make the type guard work for wide types?

答:
AFAIK, it is not possible. Once you have added explicit string type to const key: string = ''; - TS is unable to narrow literal type of key. As a result, you are allowed to use any string you want to access a property. TS is unable to distinguish two types with type string in this example:

const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}
```
<p>This remind me an example with explicit type and immutable type assertion:</p>
<pre class="lang-js prettyprint-override"><code>const record: Record<string, number> = {
    a: 1
} as const;

type Keys = keyof typeof record // string instead of "a"
</code>```

It means that in this particular case it might be a good idea to forbid using wide types:

type ForbidWide<Prop> = Prop extends string ? string extends Prop ? never : Prop : never

function hasDefinedProp<
    Obj extends Partial<Record<string, any>>,
    Prop extends string,
    >(
        obj: Obj,
        prop: ForbidWide<Prop>,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
    return obj[prop] !== undefined;
}

const obj: Partial<Record<string, number>> = {};
const key: string = '';
hasDefinedProp(obj, key) // error
```

Playground

Body:
I have a function that returns whether an object property is undefined. I need this function instead of just doing obj[key] === undefined because otherwise I'd sometimes get Property 'foo' does not exist on type 'Bar'.. It's straightforward to write the type when the property key is a literal. I.e.:

function hasDefinedProp<
  Obj extends Partial<Record<string, any>>,
  Prop extends string,
>(
  obj: Obj,
  prop: Prop,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
  return obj[prop] !== undefined;
}

const obj: Partial<Record<string, number>> = {};
if (hasDefinedProp(obj, 'foo')) {
    obj.foo + 1; // No error.
    obj.bar + 1; // "Object is possibly 'undefined'."
}

However, this doesn't work when the key's type is a wide type, i.e.:

const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}

Is it possible to make the type guard work for wide types?

Body:
AFAIK, it is not possible. Once you have added explicit string type to const key: string = ''; - TS is unable to narrow literal type of key. As a result, you are allowed to use any string you want to access a property. TS is unable to distinguish two types with type string in this example:

const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}

This remind me an example with explicit type and immutable type assertion:

const record: Record<string, number> = {
    a: 1
} as const;

type Keys = keyof typeof record // string instead of "a"

It means that in this particular case it might be a good idea to forbid using wide types:

type ForbidWide<Prop> = Prop extends string ? string extends Prop ? never : Prop : never

function hasDefinedProp<
    Obj extends Partial<Record<string, any>>,
    Prop extends string,
    >(
        obj: Obj,
        prop: ForbidWide<Prop>,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
    return obj[prop] !== undefined;
}

const obj: Partial<Record<string, number>> = {};
const key: string = '';
hasDefinedProp(obj, key) // error

Playground


问:
Can't display the values from my data base with Laravel Livewire
I'm using a Livewire component, this is my code:

Search.php :

```<code><?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}
</code>```

search.blade.php :

```<code><div class="searchcomponent">
    <h1>Search</h1>
    <input wire:model="query" type="text" placeholder="Rechercher...">

    @if(!empty($query))
        <ul>
            @if(!empty($vegetables))
                <div class="vegetables">

                    @foreach($vegetables as $vegetable)
                        <li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
                    @endforeach

                </div>
            @else
                <li>No result</li>
            @endif
       </ul>
    @endif
</div>
</code>```

My vegetable Model:

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

    public function getName($id) {
        return $this->name;
    }
}
</code>```

My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?

答:
This is because on the mount you are resetting the vegetable array to an empty array.

Refer to this fiddle for more details:

https://laravelplayground.com/#/snippets/f51e212a-dab3-4325-b6b0-4c6af4c0ab72

Body:
I'm using a Livewire component, this is my code:

Search.php :

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}

search.blade.php :

Search

    <input wire:model="query" type="text" placeholder="Rechercher...">

    @if(!empty($query))

            @if(!empty($vegetables))

                    @foreach($vegetables as $vegetable)

lunch_dining{{ $vegetable['name'] }}

                    @endforeach

            @else

No result

            @endif

    @endif

My vegetable Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

    public function getName($id) {
        return $this->name;
    }
}

My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?


问:
TypeError: Cannot read properties of undefined (reading 'user')
I am trying to create a Facebook clone using Nextjs and created nextjsAuth and configured the login now I tried to get my Facebook profile picture into my clone and this error is shown and I tried to run but this error showing and  I don't know what to do here can anyone solve this, please

```<code>pages\components\Header.js (69:23) @ Header

  67 | onClick={signOut}
  68 | className="rounded-full cursour-pointer"
> 69 | src={session.user.image}
     |             ^
  70 | width="40"
  71 | height="40"
  72 | layout="fixed"
</code>```

full code is shown below you can checkout can you solve this error

import React from "react";

import Image from "next/image";
import {
  BellIcon,
  ChatIcon,
  ChevronDownIcon,
  HomeIcon,
  UserGroupIcon,
  ViewGridIcon,
} from "@heroicons/react/solid";
import {
  FlagIcon,
  PlayIcon,
  SearchIcon,
  ShoppingCartIcon,
} from "@heroicons/react/outline";

import HeaderIcon from "./HeaderIcon";
import { signOut, useSession } from "next-auth/react";

function Header() {
  const {session} = useSession();

  return (

        {/* Left */}

        <Image
          alt="facebook"
          src="https://links.papareact.com/5me"
          width={40}
          height={40}
          layout="fixed"
        />

          <SearchIcon className="h-6 text-gray-600" />
          <input
            className=" hidden md:inline-flex flex ml-2 items-center bg-transparent outline-none
            placeholder-gray-502 flex-shrink"
            type="text"
            placeholder="Search Facebook"
          />

      {/* Center */}

          <HeaderIcon active Icon={HomeIcon} />
          <HeaderIcon Icon={FlagIcon} />
          <HeaderIcon Icon={PlayIcon} />
          <HeaderIcon Icon={ShoppingCartIcon} />
          <HeaderIcon Icon={UserGroupIcon} />

      {/* Right */}

        {/* Profile pic */}
        <Image
          onClick={signOut}
          className="rounded-full cursour-pointer"
          src={session.user.image}
          width="40"
          height="40"
          layout="fixed"
        />

Asram Ahamed

        <ViewGridIcon className="icon" />
        <ChatIcon className="icon" />
        <BellIcon className="icon" />
        <ChevronDownIcon className="icon" />

  );
};

export default Header;```

答:
I fixed it with

```<code>  const { data: session } = useSession();
</code>```

and it worked

Body:
I am trying to create a Facebook clone using Nextjs and created nextjsAuth and configured the login now I tried to get my Facebook profile picture into my clone and this error is shown and I tried to run but this error showing and  I don't know what to do here can anyone solve this, please

pages\components\Header.js (69:23) @ Header

  67 | onClick={signOut}
  68 | className="rounded-full cursour-pointer"
> 69 | src={session.user.image}
     |             ^
  70 | width="40"
  71 | height="40"
  72 | layout="fixed"

full code is shown below you can checkout can you solve this error

import React from "react";

import Image from "next/image";
import {
  BellIcon,
  ChatIcon,
  ChevronDownIcon,
  HomeIcon,
  UserGroupIcon,
  ViewGridIcon,
} from "@heroicons/react/solid";
import {
  FlagIcon,
  PlayIcon,
  SearchIcon,
  ShoppingCartIcon,
} from "@heroicons/react/outline";

import HeaderIcon from "./HeaderIcon";
import { signOut, useSession } from "next-auth/react";

function Header() {
  const {session} = useSession();

  return (

        {/* Left */}

        <Image
          alt="facebook"
          src="https://links.papareact.com/5me"
          width={40}
          height={40}
          layout="fixed"
        />

          <SearchIcon className="h-6 text-gray-600" />
          <input
            className=" hidden md:inline-flex flex ml-2 items-center bg-transparent outline-none
            placeholder-gray-502 flex-shrink"
            type="text"
            placeholder="Search Facebook"
          />

      {/* Center */}

          <HeaderIcon active Icon={HomeIcon} />
          <HeaderIcon Icon={FlagIcon} />
          <HeaderIcon Icon={PlayIcon} />
          <HeaderIcon Icon={ShoppingCartIcon} />
          <HeaderIcon Icon={UserGroupIcon} />

      {/* Right */}

        {/* Profile pic */}
        <Image
          onClick={signOut}
          className="rounded-full cursour-pointer"
          src={session.user.image}
          width="40"
          height="40"
          layout="fixed"
        />

Asram Ahamed

        <ViewGridIcon className="icon" />
        <ChatIcon className="icon" />
        <BellIcon className="icon" />
        <ChevronDownIcon className="icon" />

  );
};

export default Header;

Body:
I fixed it with

  const { data: session } = useSession();

and it worked


问:
System.DirectoryServices AuthenticationTypes
Normally I have been using Secure | Signing | Sealing flags to pull back a directory entry and search.

If I wanted to use SecureSocketsLayer instead, should I also specify any of those flags (Secure | Signing | Sealing) with it, or does the SSL flag encompass full encryption/signing and can be used alone?

I have read http://msdn.microsoft.com/en-us/library/system.directoryservices.authenticationtypes.aspx but the description doesn't make it fully clear.

答: SecureSocketsLayer requires a user cert - it's mutual auth, essentially. It's not the same as Secure | Signing | Sealing. This gets you Kerberos/NTLM authenticated and encrypted traffic. If you don't need mutual auth, I would leave it as-is, but, if you do, you can attach it as a fourth flag. </p>


问:
JavaFX Spinner - How to set min, max and value later in the code?
Say, for example, you are implementing pagination. The Spinner might have initialized and added to an HBox or similar in the initialization part of the screen. After the data is retrieved only you would come to know how many pages are needed and according to that only can set the spinner's min and max. I couldn't find a way to re-initialize or say set these later. Am I looking at the usage wrong?</p>

答:
Finally figured it out: Thanks @kleopatra for the hint:

If you have an Integer Spinner, you can set:

```<code>spinner.setValueFactory(
    new SpinnerValueFactory.IntegerSpinnerValueFactory(
        min,
        max
    )
);
</code>```

Where min and max are decided later in the code.

You can also add an optional third parameter to the constructor to set the value if you wish.

The above code did the job. May be helpful to someone.

Body:
Finally figured it out: Thanks @kleopatra for the hint:

If you have an Integer Spinner, you can set:

spinner.setValueFactory(
    new SpinnerValueFactory.IntegerSpinnerValueFactory(
        min,
        max
    )
);

Where min and max are decided later in the code.

You can also add an optional third parameter to the constructor to set the value if you wish.

The above code did the job. May be helpful to someone.


问:
Firebase getToken - Cannot destructure property 'appConfig'
I have the following trivial messaging app

```<code>// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AI...Y",
  authDomain: "xyz.firebaseapp.com",
  databaseURL: "https://xyz.firebaseio.com",
  projectId: "xyz",
  storageBucket: "xyz.appspot.com",
  messagingSenderId: "441...38",
  appId: "1:....f",
  measurementId: "G-...",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const vapidKey = "BLFWI5-...opE";

console.log("have app");
const messaging = getMessaging(app);

console.log("have messaging", messaging);
getToken({ vapidKey })
  .then((res) => console.log("token", res))
  .catch((err) => console.error(err));
</code>```

haveApp and haveMessaging seem to log correctly, but I am ending up in getToken.catch with

```<code>TypeError: Cannot destructure property 'appConfig' of 'undefined' as it is undefined.
    at getKey2 (idb-manager.ts:104:19)
    at dbGet (idb-manager.ts:50:15)
    at getTokenInternal (token-manager.ts:52:30)
</code>```

I actually have a far more complex app that works with a similar setup, but I wanted to go back to basics to check I understood a few fundamental things. Any idea.

I've tried with VSCode's built in server using CDN imports, and now with vite using local imports. The error is always the same message, albeit with different stacktraces

答:
Using v9? You need to pass the Messaging instance as the first arg...

getToken(messaging, { vapidKey })
```
<p>See https://firebase.google.com/docs/reference/js/messaging_.md#gettoken</p>
<blockquote>
<h3>Signature:</h3>
```export declare function getToken(messaging: Messaging, options?: GetTokenOptions): Promise<string>;
```

This is one of the major changes between versions 8 and 9. All of the functions you import from the various libraries require a FirebaseApp or other instance to be passed in.

Body:
I have the following trivial messaging app

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AI...Y",
  authDomain: "xyz.firebaseapp.com",
  databaseURL: "https://xyz.firebaseio.com",
  projectId: "xyz",
  storageBucket: "xyz.appspot.com",
  messagingSenderId: "441...38",
  appId: "1:....f",
  measurementId: "G-...",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const vapidKey = "BLFWI5-...opE";

console.log("have app");
const messaging = getMessaging(app);

console.log("have messaging", messaging);
getToken({ vapidKey })
  .then((res) => console.log("token", res))
  .catch((err) => console.error(err));

haveApp and haveMessaging seem to log correctly, but I am ending up in getToken.catch with

TypeError: Cannot destructure property 'appConfig' of 'undefined' as it is undefined.
    at getKey2 (idb-manager.ts:104:19)
    at dbGet (idb-manager.ts:50:15)
    at getTokenInternal (token-manager.ts:52:30)

I actually have a far more complex app that works with a similar setup, but I wanted to go back to basics to check I understood a few fundamental things. Any idea.

I've tried with VSCode's built in server using CDN imports, and now with vite using local imports. The error is always the same message, albeit with different stacktraces

Body:
Using v9? You need to pass the Messaging instance as the first arg...

getToken(messaging, { vapidKey })

See https://firebase.google.com/docs/reference/js/messaging_.md#gettoken

Signature:

export declare function getToken(messaging: Messaging, options?: GetTokenOptions): Promise<string>;

This is one of the major changes between versions 8 and 9. All of the functions you import from the various libraries require a FirebaseApp or other instance to be passed in.


问:
React Native - How do I direct to Main Stack screen without logging in and redirect back to Auth Stack from Main Stack screen?
I'm building an app that consists of public and private route.

The private route is as below:
Sign in (starting screen) --> (user signed in) --> Main Stack Screens (Home, Country, Communities, etc.)

The public route is as below:
Sign in (starting screen) --> (user not signed in) --> Main Stack Screens (Home, Country, Communities, etc.) with limited functions and content display to the user

In public route, I'm trying to add a login icon in the header of the Main Stack Screens, so users can be redirected back to the Auth flow and log in or sign up at any point of time when they wish to.

Here is my code for AuthStackNavigator.js:

```<code>import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import SignInScreen from "../screen/authentication/SignInScreen";
import SignUpScreen from "../screen/authentication/SignUpScreen";
import SignUpSuccessScreen from "../screen/authentication/SignUpSuccessScreen";
import PasswordResetScreen from "../screen/authentication/PasswordResetScreen";

const Stack = createStackNavigator();

const AuthStackNavigator = () => {
  return (
    <Stack.Navigator
      initialRouteName="Sign In"
      screenOptions={{ headerShown: false }}
    >
      <Stack.Screen name="Sign In" component={SignInScreen} />
      <Stack.Screen name="Sign Up" component={SignUpScreen} />
      <Stack.Screen name="Sign Up Success" component={SignUpSuccessScreen} />
      <Stack.Screen name="Password Reset" component={PasswordResetScreen} />}
    </Stack.Navigator>
  );
};

export default AuthStackNavigator;
</code>```

Here for MainNavigator.js:

```<code>import React, { useContext } from "react";
import { Platform, StyleSheet } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import CountryScreen from "../screen/CountryScreen";
import CommunitiesScreen from "../screen/CommunitiesScreen";
import CommunityCreateScreen from "../screen/authorized/CommunityCreateScreen";
import CommunityHomeScreen from "../screen/CommunityHomeScreen";
import PostCreateScreen from "../screen/authorized/PostCreateScreen";
import CommentPostScreen from "../screen/authorized/CommentPostScreen";
import SearchBar from "../component/SearchBar";
import { generalconfig } from "../helper/generalconfig";
import { stylesconfig } from "../helper/stylesconfig";
import { AuthContext } from "../src/context/AuthContext";
import CustomProfileImg from "../component/CustomProfileImg";
import DefaultProfileIcon from "../component/DefaultProfileIcon";
import { Entypo } from "react-native-vector-icons";
import LoginIcon from "../component/LoginIcon";

const MainNavigator = () => {
  const Stack = createStackNavigator();
  const platform = Platform.OS;

  const { width } = generalconfig.device;
  const headerImageContainer = stylesconfig.global.headerImageContainer;
  const { common, ios, aos } = stylesconfig.navigatorHeader;

  const { profileImg, token } = useContext(AuthContext);

  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Search Country"
        component={CountryScreen}
        options={{
          title: "Search",
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTitleAlign: "left",
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerRight: () =>
            profileImg ? (
              <CustomProfileImg
                activeOpacity={1.0}
                onPress={() => {}}
                src={{ uri: profileImg }}
                style={headerImageContainer}
              />
            ) : (
              <DefaultProfileIcon
                activeOpacity={1.0}
                onPress={() => {}}
                iconSize={55}
                iconPosition={{ height: 65, marginRight: 11 }}
              />
            ),
        }}
      />
      <Stack.Screen
        name="Communities"
        component={CommunitiesScreen}
        options={{
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerBackTitle: " ",
          headerBackImage: () => (
            <Entypo
              name="controller-fast-backward"
              size={23}
              style={{ marginLeft: width - 376 }}
              color={common.color}
            />
          ),
          headerRight: () => (token ? <LoginIcon /> : null),
        }}
      />
      <Stack.Screen
        name="Create Community"
        component={CommunityCreateScreen}
        options={{
          headerTitle: "Create a Community",
        }}
      />
      <Stack.Screen name="Community Home" component={CommunityHomeScreen} />
      <Stack.Screen name="Create Post" component={PostCreateScreen} />
      <Stack.Screen name="Comment Post" component={CommentPostScreen} />
    </Stack.Navigator>
  );
};

const styles = StyleSheet.create({});

export default MainNavigator;
</code>```

LoginIcon.js (component)

```<code>import React from "react";
import { TouchableOpacity } from "react-native";
import { stylesconfig } from "../helper/stylesconfig";
import { MaterialCommunityIcons } from "react-native-vector-icons";
import AuthStackNavigator from "../navigator/AuthStackNavigator";

const LoginIcon = () => {
  const { common } = stylesconfig.navigatorHeader;

  return (
    <TouchableOpacity
      onPress={() => {
        <NavigationContainer>
          <AuthStackNavigator />
        </NavigationContainer>;
      }}
    >
      <MaterialCommunityIcons
        name="login"
        size={23}
        color={common.color}
        style={{ marginRight: 15 }}
      />
    </TouchableOpacity>
  );
};

export default LoginIcon;
</code>```

SignInScreen.js (partial code of the link navigating to Country Screen when it's pressed)

```<code>      <CustomButtonLink
        custBtnLinkName={browseAroundLabel}
        style={[styles.spacing_Browse, styles.align]}
        onNavigate={() => {
          navigation.navigate(MainNavigator, { screen: "Search Country" });
        }}
        onNavigate={() => <MainNavigator />}
      />
</code>```

CustomButtonLink.js (component)

```<code>const CustomButtonLink = ({ custBtnLinkName, style, onNavigate }) => {
  return (
    <TouchableOpacity style={style} onPress={onNavigate}>
      <Text
        style={[
          stylesconfig.global.gtext,
          generalconfig.platform.os === "ios"
            ? stylesconfig.ios.text
            : stylesconfig.aos.text,
        ]}
      >
        {custBtnLinkName}
      </Text>
    </TouchableOpacity>
  );
};
</code>```

So my questions are:

How do I direct the user to the public route (Country Screen) if user is not authenticated?

Once user is directed to the public route (say Country Screen), how do I redirect him back to the AuthStackNavigator (Sign In screen) when he clicks the login icon?

I'm quite new to React Native so deeply appreciate it if anyone can help.  Thanks!

答:
For Authentication Flows you should be using conditional operations such as "&&", the ternary operator, etc.

The Way recommended by react navigation is to use the above, you can follow their guide here.

E.G.

isSignedIn ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Profile" component={ProfileScreen} />
    <Stack.Screen name="Settings" component={SettingsScreen} />
  </>
) : (
  <>
    <Stack.Screen name="SignIn" component={SignInScreen} />
    <Stack.Screen name="SignUp" component={SignUpScreen} />
  </>
)
```

Body:
I'm building an app that consists of public and private route.

The private route is as below:
Sign in (starting screen) --> (user signed in) --> Main Stack Screens (Home, Country, Communities, etc.)

The public route is as below:
Sign in (starting screen) --> (user not signed in) --> Main Stack Screens (Home, Country, Communities, etc.) with limited functions and content display to the user

In public route, I'm trying to add a login icon in the header of the Main Stack Screens, so users can be redirected back to the Auth flow and log in or sign up at any point of time when they wish to.

Here is my code for AuthStackNavigator.js:

import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import SignInScreen from "../screen/authentication/SignInScreen";
import SignUpScreen from "../screen/authentication/SignUpScreen";
import SignUpSuccessScreen from "../screen/authentication/SignUpSuccessScreen";
import PasswordResetScreen from "../screen/authentication/PasswordResetScreen";

const Stack = createStackNavigator();

const AuthStackNavigator = () => {
  return (
    <Stack.Navigator
      initialRouteName="Sign In"
      screenOptions={{ headerShown: false }}
    >
      <Stack.Screen name="Sign In" component={SignInScreen} />
      <Stack.Screen name="Sign Up" component={SignUpScreen} />
      <Stack.Screen name="Sign Up Success" component={SignUpSuccessScreen} />
      <Stack.Screen name="Password Reset" component={PasswordResetScreen} />}
    </Stack.Navigator>
  );
};

export default AuthStackNavigator;

Here for MainNavigator.js:

import React, { useContext } from "react";
import { Platform, StyleSheet } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import CountryScreen from "../screen/CountryScreen";
import CommunitiesScreen from "../screen/CommunitiesScreen";
import CommunityCreateScreen from "../screen/authorized/CommunityCreateScreen";
import CommunityHomeScreen from "../screen/CommunityHomeScreen";
import PostCreateScreen from "../screen/authorized/PostCreateScreen";
import CommentPostScreen from "../screen/authorized/CommentPostScreen";
import SearchBar from "../component/SearchBar";
import { generalconfig } from "../helper/generalconfig";
import { stylesconfig } from "../helper/stylesconfig";
import { AuthContext } from "../src/context/AuthContext";
import CustomProfileImg from "../component/CustomProfileImg";
import DefaultProfileIcon from "../component/DefaultProfileIcon";
import { Entypo } from "react-native-vector-icons";
import LoginIcon from "../component/LoginIcon";

const MainNavigator = () => {
  const Stack = createStackNavigator();
  const platform = Platform.OS;

  const { width } = generalconfig.device;
  const headerImageContainer = stylesconfig.global.headerImageContainer;
  const { common, ios, aos } = stylesconfig.navigatorHeader;

  const { profileImg, token } = useContext(AuthContext);

  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Search Country"
        component={CountryScreen}
        options={{
          title: "Search",
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTitleAlign: "left",
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerRight: () =>
            profileImg ? (
              <CustomProfileImg
                activeOpacity={1.0}
                onPress={() => {}}
                src={{ uri: profileImg }}
                style={headerImageContainer}
              />
            ) : (
              <DefaultProfileIcon
                activeOpacity={1.0}
                onPress={() => {}}
                iconSize={55}
                iconPosition={{ height: 65, marginRight: 11 }}
              />
            ),
        }}
      />
      <Stack.Screen
        name="Communities"
        component={CommunitiesScreen}
        options={{
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerBackTitle: " ",
          headerBackImage: () => (
            <Entypo
              name="controller-fast-backward"
              size={23}
              style={{ marginLeft: width - 376 }}
              color={common.color}
            />
          ),
          headerRight: () => (token ? <LoginIcon /> : null),
        }}
      />
      <Stack.Screen
        name="Create Community"
        component={CommunityCreateScreen}
        options={{
          headerTitle: "Create a Community",
        }}
      />
      <Stack.Screen name="Community Home" component={CommunityHomeScreen} />
      <Stack.Screen name="Create Post" component={PostCreateScreen} />
      <Stack.Screen name="Comment Post" component={CommentPostScreen} />
    </Stack.Navigator>
  );
};

const styles = StyleSheet.create({});

export default MainNavigator;

LoginIcon.js (component)

import React from "react";
import { TouchableOpacity } from "react-native";
import { stylesconfig } from "../helper/stylesconfig";
import { MaterialCommunityIcons } from "react-native-vector-icons";
import AuthStackNavigator from "../navigator/AuthStackNavigator";

const LoginIcon = () => {
  const { common } = stylesconfig.navigatorHeader;

  return (
    <TouchableOpacity
      onPress={() => {
        <NavigationContainer>
          <AuthStackNavigator />
        </NavigationContainer>;
      }}
    >
      <MaterialCommunityIcons
        name="login"
        size={23}
        color={common.color}
        style={{ marginRight: 15 }}
      />
    </TouchableOpacity>
  );
};

export default LoginIcon;

SignInScreen.js (partial code of the link navigating to Country Screen when it's pressed)

      <CustomButtonLink
        custBtnLinkName={browseAroundLabel}
        style={[styles.spacing_Browse, styles.align]}
        onNavigate={() => {
          navigation.navigate(MainNavigator, { screen: "Search Country" });
        }}
        onNavigate={() => <MainNavigator />}
      />

CustomButtonLink.js (component)

const CustomButtonLink = ({ custBtnLinkName, style, onNavigate }) => {
  return (
    <TouchableOpacity style={style} onPress={onNavigate}>
      <Text
        style={[
          stylesconfig.global.gtext,
          generalconfig.platform.os === "ios"
            ? stylesconfig.ios.text
            : stylesconfig.aos.text,
        ]}
      >
        {custBtnLinkName}
      </Text>
    </TouchableOpacity>
  );
};

So my questions are:

How do I direct the user to the public route (Country Screen) if user is not authenticated?

Once user is directed to the public route (say Country Screen), how do I redirect him back to the AuthStackNavigator (Sign In screen) when he clicks the login icon?

I'm quite new to React Native so deeply appreciate it if anyone can help.  Thanks!


问:
How to show nested items from a API list
I have a data in this format

```<code>{
  "id": 1,
  "brands": [], // "n" number of items inside this brands
  "title": "Phone",
  "image": "/image.png",
  "timestamp": "2022-01-30T23:15:45.355411+05:30",
  "updated": "2022-01-30T23:18:05.053914+05:30"
}
</code>```

Inside the brands data is like this

```<code>brands": [{
  "title": "Phone",
  "id": 1,
  "products": [{
    "id": 1,
    "name": "iPhone 13",
    "image": "/image.png",
    "timestamp": "2022-01-30T23:22:11.259452+05:30",
    "updated": "2022-01-30T23:22:11.259452+05:30",
    "variant": "256 Storage",
  }]
}]
</code>```

I'm able to show up categories fields like title id etc doing this

```<code>{ categories.map((items) => (
  <Col key={items.id} sm={12} md={8} lg={4} xl={3} >
    <div>{items.title}</div>
  </Col>
)) }
</code>```

But onClick I want to show the nested brands to that category , Being new to JS and react, I don't know proper syntax to access to the nested items.

答:
I think something like this could work.

{categories.map(category => (
    <Col key={category.id} sm={12} md={8} lg={4} xl={3} >

{category.title}

Brands

            {category.brands.map(brand => (

{brand.title}

                        brand.products.map(product => (

                                {product.name}
                                {product.timestamp}

                                {product.id}

                        ))

            ))}

    </Col>
))}
```

Body:
I have a data in this format

{
  "id": 1,
  "brands": [], // "n" number of items inside this brands
  "title": "Phone",
  "image": "/image.png",
  "timestamp": "2022-01-30T23:15:45.355411+05:30",
  "updated": "2022-01-30T23:18:05.053914+05:30"
}

Inside the brands data is like this

brands": [{
  "title": "Phone",
  "id": 1,
  "products": [{
    "id": 1,
    "name": "iPhone 13",
    "image": "/image.png",
    "timestamp": "2022-01-30T23:22:11.259452+05:30",
    "updated": "2022-01-30T23:22:11.259452+05:30",
    "variant": "256 Storage",
  }]
}]

I'm able to show up categories fields like title id etc doing this

{ categories.map((items) => (
  <Col key={items.id} sm={12} md={8} lg={4} xl={3} >

{items.title}

  </Col>
)) }

But onClick I want to show the nested brands to that category , Being new to JS and react, I don't know proper syntax to access to the nested items.

Body:
I think something like this could work.

{categories.map(category => (
    <Col key={category.id} sm={12} md={8} lg={4} xl={3} >
        <div>{category.title}</div>
        <h2>Brands</h2>
        <div>
            {category.brands.map(brand => (
                <div>
                    <div>{brand.title}</div>
                    <ul>
                        brand.products.map(product => (
                            <li>
                                <b>{product.name}</b>
                                <b>{product.timestamp}</b>
                                <img src={product.image}/>
                                <span>{product.id}</span>
                            </li>
                        ))
                    </ul>
                </div>
            ))}
        </div>
    </Col>
))}


问:
How to handle a nullable enum type field in a protobuf3 message?
The following are my protobuf definitions:

```<code>enum Foo {
   BAR = 0;
   BAZ = 1;
}

message UpdateRequest {
  string id = 1;
  Foo foo = 2;
  .
  .
  .
}
</code>```

I need the foo field of the UpdateRequest to be nullable. However, if I don't set the value of this field then as per protobuf semantics it always ends up picking BAR as the default value.

Looking around, I found a couple of ways to handle this.

Add an additional UNKNOWN value in the enum and map it to 0 so that this value will be used as the default value instead of BAR and I can treat this value as null.

```<code>enum Foo {
   UNKNOWN = 0;
   BAR = 1;
   BAZ = 2;
}
</code>```

Use oneof construct.

However, somehow I feel that both of the above approaches are a kind of a workaround and I am not able to locate official documentation explaining the best practice to handle this case.

What is the best practice to handle this use case?

答: You should be able to check the field using hasFoo(), while getFoo() will return BAR, hasFoo() should return false.

Body:
The following are my protobuf definitions:

enum Foo {
   BAR = 0;
   BAZ = 1;
}

message UpdateRequest {
  string id = 1;
  Foo foo = 2;
  .
  .
  .
}

I need the foo field of the UpdateRequest to be nullable. However, if I don't set the value of this field then as per protobuf semantics it always ends up picking BAR as the default value.

Looking around, I found a couple of ways to handle this.

Add an additional UNKNOWN value in the enum and map it to 0 so that this value will be used as the default value instead of BAR and I can treat this value as null.

enum Foo {
   UNKNOWN = 0;
   BAR = 1;
   BAZ = 2;
}

Use oneof construct.

However, somehow I feel that both of the above approaches are a kind of a workaround and I am not able to locate official documentation explaining the best practice to handle this case.

What is the best practice to handle this use case?


问:
Detect firebug opening and closing
Does anybody have a way to detect Firebug opening and closing.

I know you can do the following:

```<code>if (window.console && window.console.firebug) {
  //Firebug is enabled
}
</code>```

but this only detects the firebug console on page load. What I want to do is on a page where firebug is not open, detect the opening of the firebug console.

I've tried the following, but with no luck

```<code>setInterval(function(){
  if(window.console && window.console.firebug){
    ...
  else
    ...
}, 1000);
</code>```

Any help greatly appreciated.

Matt

答:
you can make it as</p>

```<code>var t = setTimeout("CheckFireBug()",10000);
function CheckFireBug() {
    var t = setTimeout("CheckFireBug()",10000);
    if (window.console && window.console.firebug) {
        //Firebug is enabled
        console.debug('Firebug is enabled.');
    } else {
        //Firebug is not enabled
        console.debug('Firebug is not enabled.');
    }
}
</code>```

Title: Detect firebug opening and closing

Body:
Does anybody have a way to detect Firebug opening and closing.

I know you can do the following:

if (window.console && window.console.firebug) {
  //Firebug is enabled
}

but this only detects the firebug console on page load. What I want to do is on a page where firebug is not open, detect the opening of the firebug console.

I've tried the following, but with no luck

setInterval(function(){
  if(window.console && window.console.firebug){
    ...
  else
    ...
}, 1000);

Any help greatly appreciated.

Matt

Body:
you can make it as

var t = setTimeout("CheckFireBug()",10000);
function CheckFireBug() {
    var t = setTimeout("CheckFireBug()",10000);
    if (window.console && window.console.firebug) {
        //Firebug is enabled
        console.debug('Firebug is enabled.');
    } else {
        //Firebug is not enabled
        console.debug('Firebug is not enabled.');
    }
}


问:
Apply and apply with COQ
Sorry for the ambiguous question but I'm having hard time understanding the difference between apply and apply with.

Suppose I have a goal, when should I use apply and when should I use apply with?
my goal is of the form:
P a b.
And the lemma I'm trying to apply to has forall a b.
If I'm using apply, it just makes the a b constants.
If I'm using apply with it generalizes the a and b.

答:
When you look at a theorem statement, you can check whether the universally quantified variables appear in the final conclusion of the statement.  I all of them do appear, you can use apply.  If one of them does not, then it is often more practical to use apply ... with ....

Here are two examples.

```<code>Require Import Arith.
Check le_trans.
(* This says :
  Nat.le_trans
   : forall n m p : nat, n <= m -> m <= p -> n <= p. *)
Check le_S.
(* This says :
 le_S
  : forall n m : nat, n <= m -> n <= S m *)
Check le_n.
(* This says :
 le_n
  : forall n: nat, n <= n *)m -> n <= S m
</code>```

I am taking examples from the already existing Arith library.  The two Check commands make it possible to verify that we are on the same page.  The first one, about le_trans shows that in this theorem there is one variable, named y in my example, which does not appear in the final statement.  So, when performing an apply command, this y will not be guessable by comparison with the goal  at hand.  For this reason, this theorem is a good candidate for apply ... with ....

Here is an example proof:

```<code>Lemma test_drive : forall x, x <= S (S x).
Proof.
intros x.
apply le_trans with (S x).
apply le_S.
apply le_n.
apply le_S.
apply le_n.
end.
</code>```

When applying the theorem le_trans, the Coq system can guess which value will be used for instanciating variables named n and p, by simply comparing with the goal at the time: n should should be x and p should be S (S x).  For m, a value should be given, and apply expects the user to give it, this is where we use the with clause.  In this case, we can simply give the value (the order in which variables appear is being used).  We choose to give S x.  As a result, we obtain two goals, one with statement x <= S x  and one with statement S x <= S (S x).  Both goals are instances of the final statement of le_S.  In turn, this lemma has the property that both universally quantified variables appear in the final statement, so apply without the with clause can be used.

The same happens later when we want to use the lemma le_n.

Title: Apply and apply with COQ

Body:
When you look at a theorem statement, you can check whether the universally quantified variables appear in the final conclusion of the statement.  I all of them do appear, you can use apply.  If one of them does not, then it is often more practical to use apply ... with ....

Here are two examples.

Require Import Arith.
Check le_trans.
(* This says :
  Nat.le_trans
   : forall n m p : nat, n <= m -> m <= p -> n <= p. *)
Check le_S.
(* This says :
 le_S
  : forall n m : nat, n <= m -> n <= S m *)
Check le_n.
(* This says :
 le_n
  : forall n: nat, n <= n *)m -> n <= S m

I am taking examples from the already existing Arith library.  The two Check commands make it possible to verify that we are on the same page.  The first one, about le_trans shows that in this theorem there is one variable, named y in my example, which does not appear in the final statement.  So, when performing an apply command, this y will not be guessable by comparison with the goal  at hand.  For this reason, this theorem is a good candidate for apply ... with ....

Here is an example proof:

Lemma test_drive : forall x, x <= S (S x).
Proof.
intros x.
apply le_trans with (S x).
apply le_S.
apply le_n.
apply le_S.
apply le_n.
end.

When applying the theorem le_trans, the Coq system can guess which value will be used for instanciating variables named n and p, by simply comparing with the goal at the time: n should should be x and p should be S (S x).  For m, a value should be given, and apply expects the user to give it, this is where we use the with clause.  In this case, we can simply give the value (the order in which variables appear is being used).  We choose to give S x.  As a result, we obtain two goals, one with statement x <= S x  and one with statement S x <= S (S x).  Both goals are instances of the final statement of le_S.  In turn, this lemma has the property that both universally quantified variables appear in the final statement, so apply without the with clause can be used.

The same happens later when we want to use the lemma le_n.


问:
Error http 422 and XMLHttpRequest in flutter
I want to connect to a web service. When I use postman, request send and response receive successfully. But in the flutter app, I get error 422 in the android emulator. And with the same code in flutter web, I get XMLHttpRequest error.

My postman:

This is my data that send to the server:

```<code>var data = {
  "username": usernameController.text,
  "password": passwordController.text,
  "email": emailController.text
};
</code>```

And send a request with dio:

```<code>Response response = await client
        .post(theUrl,
            options: Options(headers: {
              HttpHeaders.contentTypeHeader: "application/json",
              HttpHeaders.acceptHeader:"*/*"
            }),
            data: jsonEncode(data))
        .timeout(const Duration(seconds: 10));
</code>```

I get errors on this method:

```<code>on DioError catch (error) {
    var statusCode = error.response?.statusCode;
    print("+++++++++++++++" + statusCode.toString());
    print("+++++++++++++++" + error.message);
}
</code>```

How can I fix these errors?

答:
I Added this code to options in dio and Error 422 in mobile is fixed:

```<code>Options(
  validateStatus: (status) {
    return status! < 500;
   },
   followRedirects: false,
   ...)
</code>```

But I still get error XMLHttpRequest in flutter web.

Body:
I want to connect to a web service. When I use postman, request send and response receive successfully. But in the flutter app, I get error 422 in the android emulator. And with the same code in flutter web, I get XMLHttpRequest error.

My postman:

This is my data that send to the server:

var data = {
  "username": usernameController.text,
  "password": passwordController.text,
  "email": emailController.text
};

And send a request with dio:

Response response = await client
        .post(theUrl,
            options: Options(headers: {
              HttpHeaders.contentTypeHeader: "application/json",
              HttpHeaders.acceptHeader:"*/*"
            }),
            data: jsonEncode(data))
        .timeout(const Duration(seconds: 10));

I get errors on this method:

on DioError catch (error) {
    var statusCode = error.response?.statusCode;
    print("+++++++++++++++" + statusCode.toString());
    print("+++++++++++++++" + error.message);
}

How can I fix these errors?

Body:
I Added this code to options in dio and Error 422 in mobile is fixed:

Options(
  validateStatus: (status) {
    return status! < 500;
   },
   followRedirects: false,
   ...)

But I still get error XMLHttpRequest in flutter web.


问:
get the last record id using bookshelf.js/knex.js[mysql] + express.js
for example, if I have 2 tables(invoices  , bills items which include the quantity ) connected to each other through a one to many relationships . and a post api gives me the data . the new  bill id will be the last id+1 so if I can make a loop that will make the objects be inserted then run

```<code>  knex.insert(arrayPurchaseItems, 'id').into('purchaseRequests').then()
</code>```

so I don't need to wait for the bill insertion to be resolved
however, the risk of the purchase request insertion starting before bill inserting completion  exist . any ideas ??

答:
```<code>knex.select().from('table_name').orderBy([{column:"id",order:"desc"}]).limit(1)
</code>```

Here we are taking id and sorting it in reverse order.

Then take the last result by limiting the result

Body:
for example, if I have 2 tables(invoices  , bills items which include the quantity ) connected to each other through a one to many relationships . and a post api gives me the data . the new  bill id will be the last id+1 so if I can make a loop that will make the objects be inserted then run

  knex.insert(arrayPurchaseItems, 'id').into('purchaseRequests').then()

so I don't need to wait for the bill insertion to be resolved
however, the risk of the purchase request insertion starting before bill inserting completion  exist . any ideas ??

Body:
knex.select().from('table_name').orderBy([{column:"id",order:"desc"}]).limit(1)

Here we are taking id and sorting it in reverse order.

Then take the last result by limiting the result