问:
MSBuild ZipDirectory Output Different when Building Solution and Building Individual Project
I'm having an issue with MSBuild ZipDirectory command, where the zipped output file differs between when built by individual project and when built for entire solution.

For example,
The expected zip file looks like below:

```<code>A.txt

B.txt

C.txt
</code>```

The zipped file looks as expected when built as individual project.

However,
When solution is build as a whole,
The zipped file looks like below, missing some files:

```<code>A.txt

B.txt
</code>```

What is causing such issue??

答:
MSBuild ZipDirectory Output Different when Building Solution and
  Building Individual Project

I wonder if you use ZipDirectory task to compress some certain files in your project. I have tested the command in different projects in the same solution and did not face the same issue as you said. So please check this:

1) If you just compress some content files in the project, try to create a new folder in Solution Explorer called resource and then put any files you want to compress into this. And remember to set this target executes after build process.

```<code><Target Name="ZipOutputPath" AfterTargets="Build">
    <ZipDirectory
        SourceDirectory="$(MSBuildProjectDirectory)\resource"
        DestinationFile="$(MSBuildProjectDirectory)\output.zip" />
  </Target>
</code>```

2) If you want to compress the files of the output folder, please make sure that you have set Copy to Output Directory of the specific files to Copy if newer.

Note :please check if there are some extra targets which will delete some files like C.txt or there is some extra condidtions to limit this.

Build Solution means that it can build all the projects at the same time so I wonder if some extra projects have some configuration which will cause this behavior in the first project.

3) Besides, you can also try zip task to realize this:

```<code><Target Name="zipfiles" AfterTargets = "Build">
 <ItemGroup>
    <ZipFiles Include="xxxxx\A.txt" />
    <ZipFiles Include="xxxxx\B.txt" />
    <ZipFiles Include="xxxxx\C.txt" />
  </ItemGroup>
  <Zip OutputFilename="$(OutputPath)Project.zip" Files="@(ZipFiles)" />
 </Target>
</code>```

In addition, if all of these did not help, there might be a situation where you might have a problem with your VS environment. Due to it, you can follow these steps:

A) close VS instance, delete .vs hidden folder under the solution path,bin and obj folder. Then restart your solution and then build again to see whether the issue persists.

B) use devenv /safemode to start VS and then test whether the issue is caused by third party extensions, packages.

C) do a repair in VS Installer.

If I misunderstand your issue, please share more detailed info and feel free to let us know.

Body:
I'm having an issue with MSBuild ZipDirectory command, where the zipped output file differs between when built by individual project and when built for entire solution.

For example,
The expected zip file looks like below:

A.txt

B.txt

C.txt

The zipped file looks as expected when built as individual project.

However,
When solution is build as a whole,
The zipped file looks like below, missing some files:

A.txt

B.txt

What is causing such issue??

Body:
MSBuild ZipDirectory Output Different when Building Solution and
  Building Individual Project

I wonder if you use ZipDirectory task to compress some certain files in your project. I have tested the command in different projects in the same solution and did not face the same issue as you said. So please check this:

1) If you just compress some content files in the project, try to create a new folder in Solution Explorer called resource and then put any files you want to compress into this. And remember to set this target executes after build process.

<Target Name="ZipOutputPath" AfterTargets="Build">
    <ZipDirectory
        SourceDirectory="$(MSBuildProjectDirectory)\resource"
        DestinationFile="$(MSBuildProjectDirectory)\output.zip" />
  </Target>

2) If you want to compress the files of the output folder, please make sure that you have set Copy to Output Directory of the specific files to Copy if newer.

Note :please check if there are some extra targets which will delete some files like C.txt or there is some extra condidtions to limit this.

Build Solution means that it can build all the projects at the same time so I wonder if some extra projects have some configuration which will cause this behavior in the first project.

3) Besides, you can also try zip task to realize this:

<Target Name="zipfiles" AfterTargets = "Build">
 <ItemGroup>
    <ZipFiles Include="xxxxx\A.txt" />
    <ZipFiles Include="xxxxx\B.txt" />
    <ZipFiles Include="xxxxx\C.txt" />
  </ItemGroup>
  <Zip OutputFilename="$(OutputPath)Project.zip" Files="@(ZipFiles)" />
 </Target>

In addition, if all of these did not help, there might be a situation where you might have a problem with your VS environment. Due to it, you can follow these steps:

A) close VS instance, delete .vs hidden folder under the solution path,bin and obj folder. Then restart your solution and then build again to see whether the issue persists.

B) use devenv /safemode to start VS and then test whether the issue is caused by third party extensions, packages.

C) do a repair in VS Installer.

If I misunderstand your issue, please share more detailed info and feel free to let us know.


来源: stackexchange

问:
Continuous animation problem even if hovered out
I have a button that will fade a div upon hover.
If I hover in a button then hover out and repeat that procedure multiple times in quick succession then hover out, the div will go on animating when it should have stopped.
Please refer to the following snippet.

http://jsfiddle.net/arvinboggs/uenEQ/9/

Is there a way to correct this behavior?

Is there a way stop the animation on the final hover out?

答:
Cut and paste from a previous answer of mine to a similar question:

I actually create a 'state' variable to ensure only 1 action can fire at any time.

What I do is

```<code>set state = 0; when I initialise the page
check if state == 0 when something is clicked
if it's 0, then I set it to 1 (meaning something's happening)
run the animation
once the animation is complete, I reset the state to 0
</code>```

Effectively, you can only fire the animation event is state == 0 and then there's no overlapping.

So to answer your question, when you bind() the hover, it needs to check whether it's allowed to fire the animation or not based on the state setting.

```<code>var hoverState = 0;
$('.myLink').bind('mouseenter'), function(){
    myHoverCode();
});

function hoverCode(){
  if(hoverState == 0){
    hoverState = 1; // bind this hover state so we can't trigger it again
   // do my animation
  $('#someElement').animate({
},100, function(){
// animation complete
hoverState = 0; // reset the hover state
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Cut and paste from a previous answer of mine to a similar question:

I actually create a 'state' variable to ensure only 1 action can fire at any time.

What I do is

set state = 0; when I initialise the page
check if state == 0 when something is clicked
if it's 0, then I set it to 1 (meaning something's happening)
run the animation
once the animation is complete, I reset the state to 0

Effectively, you can only fire the animation event is state == 0 and then there's no overlapping.

So to answer your question, when you bind() the hover, it needs to check whether it's allowed to fire the animation or not based on the state setting.

var hoverState = 0;
$('.myLink').bind('mouseenter'), function(){
    myHoverCode();
});

function hoverCode(){
  if(hoverState == 0){
    hoverState = 1; // bind this hover state so we can't trigger it again
   // do my animation
  $('#someElement').animate({
},100, function(){
// animation complete
hoverState = 0; // reset the hover state
});


问:
website shows the original source code- but google not
So this is my website https://aba-elearning.com/
when I look on the source code it shows that everything is fine.

when I ask from "google console" to test live URL I see Japanese letters.

when I ran site:aba-elearning.com in google I can see I got hacked.
So I used this free tool https://aw-snap.info/

to check my website and the result shows that there is a script somewhere inside my site that cuz that.

I checked everywhere, found some spammy php codex inside my server (Built on Joomla).
but the Japanese still there.

this is the code results from the test
https://aw-snap.info/file-viewer/?protocol=secure&ref_sel=GSP2&ua_sel=ff&chk-cache=&fs=1&tgt=fGJ8LXtse3x9bltuZy5eXW0%3D~enc

this is how google see my website:
https://aw-snap.info/file-viewer/?protocol=secure&ref_sel=none&ua_sel=gbot2&chk-cache=&fs=0&tgt=aHR0cHM6YGB8Ynwte2x7fH1uW25nLl5dbWA%3D~enc

when I ask google to index my home page it says

Image from google console

on top of that, I can't update the Joomla for over a year from some reason!
I have PHP knowledge and codding I looked inside the .htaccess files robots.txt
and index.php for some fishy code, I found this:

IMage of the code I took down

I really don't know what to do and would love for some directions!

答:
Your site was hacked. Someone modified your files to deliver specific content.

Here are two articles which might help you to fix the issue:

https://www.bluebridgedev.com/joomla-hacked
https://www.joomshaper.com/blog/my-joomla-site-was-hacked-what-to-do

I recommend installing Akeeba Admin Tools to prevent basic attacks.

https://www.akeebabackup.com/products/admin-tools.html

A good source for ideas to secure a site is this: https://www.bluebridgedev.com/blog/entry/how-to-secure-a-joomla-site

In general, that blog is worth a read: https://www.bluebridgedev.com/blog

For possible new security issues, I recommend subscribing to the RSS feed of:

https://developer.joomla.org/security-centre

https://vel.joomla.org/live-vel

https://www.exploit-db.com/

ContentLicense: CC BY-SA 4.0


问:
Cython cannot refer to a declared type in a cdef class if there is a property with that same name?
I have some complex generated cython code that wraps a C++ library.

For one of the C++ libraries I wrap, I get a really hard to understand
error. The following is a minimum reproducible example

bad.pxd:

```<code>cdef class Foo:
    pass

cdef class Bar:
    pass
</code>```

bad.pyx:

```<code>cdef class Bar:
    x = {}

    Bar.x['Foo'] = Foo

    @property
    def Foo(self):
        pass

    @Foo.setter
    def Foo(self, val):
        pass
</code>```

The error from the cython compiler:

```<code>Error compiling Cython file:
------------------------------------------------------------
...
cdef class Bar:
    x = {}

    Bar.x['Foo'] = Foo
                ^
------------------------------------------------------------

bad.pyx:4:19: 'Foo' is not a constant, variable or function identifier
</code>```

This compiles fine if I comment out Bar.x['Foo'] = Foo or if I comment
out the property.

It seems like you cannot refer to a typename if you also use that name
as a property. It seems ok to do this if it is a method, but not a
property.

Does this violate some rule in Cython, or is this more likely a bug?

I realize that the right answer is "don't do that", but unfortunately,
I do not control the names that result in this admittedly odd class
definition.

答:
The best workaround would be

```<code>Bar.x['Foo'] = globals()['Foo'].
</code>```

Even in some of the cases you mention work they don't do what you'd expect: if Foo is a method then the dict ends up as:

```<code>{'Foo': <method 'Foo' of 'modulename.Bar' objects>}
</code>```

(i.e. not the Python behaviour).

It probably is a bug, but I doubt if it's easy or high priority to fix since it's a combination of lookup being resolved at compile-time and properties not being assignable. The former is almost certainly known and probably unfixable. Bugs can be reported on the issue tracker.

Body:
I have some complex generated cython code that wraps a C++ library.

For one of the C++ libraries I wrap, I get a really hard to understand
error. The following is a minimum reproducible example

bad.pxd:

cdef class Foo:
    pass

cdef class Bar:
    pass

bad.pyx:

cdef class Bar:
    x = {}

    Bar.x['Foo'] = Foo

    @property
    def Foo(self):
        pass

    @Foo.setter
    def Foo(self, val):
        pass

The error from the cython compiler:

Error compiling Cython file:
------------------------------------------------------------
...
cdef class Bar:
    x = {}

    Bar.x['Foo'] = Foo
                ^
------------------------------------------------------------

bad.pyx:4:19: 'Foo' is not a constant, variable or function identifier

This compiles fine if I comment out Bar.x['Foo'] = Foo or if I comment
out the property.

It seems like you cannot refer to a typename if you also use that name
as a property. It seems ok to do this if it is a method, but not a
property.

Does this violate some rule in Cython, or is this more likely a bug?

I realize that the right answer is "don't do that", but unfortunately,
I do not control the names that result in this admittedly odd class
definition.

Body:
The best workaround would be

Bar.x['Foo'] = globals()['Foo'].

Even in some of the cases you mention work they don't do what you'd expect: if Foo is a method then the dict ends up as:

{'Foo': <method 'Foo' of 'modulename.Bar' objects>}

(i.e. not the Python behaviour).

It probably is a bug, but I doubt if it's easy or high priority to fix since it's a combination of lookup being resolved at compile-time and properties not being assignable. The former is almost certainly known and probably unfixable. Bugs can be reported on the issue tracker.


问:
SwiftUI: Support multiple modals
I'm trying to setup a view that can display multiple modals depending on which button is tapped.

When I add just one sheet, everything works:

```<code>.sheet(isPresented: $showingModal1) { ... }
</code>```

But when I add another sheet, only the last one works.

```<code>.sheet(isPresented: $showingModal1) { ... }
.sheet(isPresented: $showingModal2) { ... }
</code>```

UPDATE

I tried to get this working, but I'm not sure how to declare the type for modal. I'm getting an error of Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements.

```<code>struct ContentView: View {
    @State var modal: View?
    var body: some View {
        VStack {
            Button(action: {
                self.modal = ModalContentView1()
            }) {
                Text("Show Modal 1")
            }
            Button(action: {
                self.modal = ModalContentView2()
            }) {
                Text("Show Modal 2")
            }
        }.sheet(item: self.$modal, content: { modal in
            return modal
        })
    }
}

struct ModalContentView1: View {
    var body: some View {
        Text("Modal 1")
    }
}

struct ModalContentView2: View {
    var body: some View {
        Text("Modal 2")
    }
}
</code>```

答:
I'm not sure whether this was always possible, but in Xcode 11.3.1 there is an overload of .sheet() for exactly this use case (https://developer.apple.com/documentation/swiftui/view/3352792-sheet). You can call it with an Identifiable item instead of a bool:

```<code>struct ModalA: View {

    var body: some View {
        Text("Hello, World! (A)")
    }

}

struct ModalB: View {

    var body: some View {
        Text("Hello, World! (B)")
    }

}

struct MyContentView: View {

    enum Sheet: Hashable, Identifiable {

        case a
        case b

        var id: Int {
            return self.hashValue
        }

    }

    @State var activeSheet: Sheet? = nil

    var body: some View {
        VStack(spacing: 42) {
            Button(action: {
                self.activeSheet = .a
            }) {
                Text("Hello, World! (A)")
            }
            Button(action: {
                self.activeSheet = .b
            }) {
                Text("Hello, World! (B)")
            }
        }
            .sheet(item: $activeSheet) { item in
                if item == .a {
                    ModalA()
                } else if item == .b {
                    ModalB()
                }
            }
    }

}
</code>```

Title: SwiftUI: Support multiple modals

Body:
I'm trying to setup a view that can display multiple modals depending on which button is tapped.

When I add just one sheet, everything works:

.sheet(isPresented: $showingModal1) { ... }

But when I add another sheet, only the last one works.

.sheet(isPresented: $showingModal1) { ... }
.sheet(isPresented: $showingModal2) { ... }

UPDATE

I tried to get this working, but I'm not sure how to declare the type for modal. I'm getting an error of Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements.

struct ContentView: View {
    @State var modal: View?
    var body: some View {
        VStack {
            Button(action: {
                self.modal = ModalContentView1()
            }) {
                Text("Show Modal 1")
            }
            Button(action: {
                self.modal = ModalContentView2()
            }) {
                Text("Show Modal 2")
            }
        }.sheet(item: self.$modal, content: { modal in
            return modal
        })
    }
}

struct ModalContentView1: View {
    var body: some View {
        Text("Modal 1")
    }
}

struct ModalContentView2: View {
    var body: some View {
        Text("Modal 2")
    }
}

Body:
I'm not sure whether this was always possible, but in Xcode 11.3.1 there is an overload of .sheet() for exactly this use case (https://developer.apple.com/documentation/swiftui/view/3352792-sheet). You can call it with an Identifiable item instead of a bool:

struct ModalA: View {

    var body: some View {
        Text("Hello, World! (A)")
    }

}

struct ModalB: View {

    var body: some View {
        Text("Hello, World! (B)")
    }

}

struct MyContentView: View {

    enum Sheet: Hashable, Identifiable {

        case a
        case b

        var id: Int {
            return self.hashValue
        }

    }

    @State var activeSheet: Sheet? = nil

    var body: some View {
        VStack(spacing: 42) {
            Button(action: {
                self.activeSheet = .a
            }) {
                Text("Hello, World! (A)")
            }
            Button(action: {
                self.activeSheet = .b
            }) {
                Text("Hello, World! (B)")
            }
        }
            .sheet(item: $activeSheet) { item in
                if item == .a {
                    ModalA()
                } else if item == .b {
                    ModalB()
                }
            }
    }

}


问:
Create element, and add parent attributes to innerHTML
I'm creating a button that opens a modal for editing a document. I add attributes to the button and grab them when the button is clicked. I've added an icon to the innerHTML of my button, but that doesn't inherit the attributes (ie if the icon within the button is clicked, the modal doesn't have the data, while clicking outside the icon but still inside the button works fine).

```<code>const edit = document.createElement('button')
edit.innerHTML = '<svg class="review__icon"><use xlink:href="/img/icons.svg#icon-edit"></use></svg>'

edit.setAttribute('data-key', el._id)
edit.setAttribute('data-title', el.title)
...
</code>```

Now obviously I could just add the same attributes to the icon, but that seems daft. Is there some way to have the icon in my innerHTML inherit the data-attributes of its parent, the button?

答:
if the icon within the button is clicked, the modal doesn't have
  the data, while clicking outside the icon but still inside the button
  works fine.

The solution is to apply to the icon the CSS style:

```<code>pointer-events: none;
</code>```

While maintaining the icon's visibility, this effectively makes the icon insubstantial.

When you try to click the icon, you will click right through it and click on the button underneath instead.

Further Reading:

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Body:
I'm creating a button that opens a modal for editing a document. I add attributes to the button and grab them when the button is clicked. I've added an icon to the innerHTML of my button, but that doesn't inherit the attributes (ie if the icon within the button is clicked, the modal doesn't have the data, while clicking outside the icon but still inside the button works fine).

const edit = document.createElement('button')
edit.innerHTML = '<svg class="review__icon"><use xlink:href="/img/icons.svg#icon-edit"></use></svg>'

edit.setAttribute('data-key', el._id)
edit.setAttribute('data-title', el.title)
...

Now obviously I could just add the same attributes to the icon, but that seems daft. Is there some way to have the icon in my innerHTML inherit the data-attributes of its parent, the button?

Body:
if the icon within the button is clicked, the modal doesn't have
  the data, while clicking outside the icon but still inside the button
  works fine.

The solution is to apply to the icon the CSS style:

pointer-events: none;

While maintaining the icon's visibility, this effectively makes the icon insubstantial.

When you try to click the icon, you will click right through it and click on the button underneath instead.

Further Reading:

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events


问:
How do I remove the gap inbetween my navbar buttons

I would like to know how to fix this issue I have tried everything that I can think of. Any help would be great. all my paddings and margins are set to zero or auto.
nothing that is obvious to me is causing the issue, I have tried first and last child float left and right but this did not work.

#nav {
  text-align: center;
  margin: 0;
  overflow: hidden;
  display: block;
}

#nav ul {
  margin: auto;
  padding: 0;
  font-size: 100%;
  list-style: none;
  list-style-type: none;
}

#nav ul li {
  display: inline-block;
}

#nav a {
  transition: 0.3s;
  background-color: #fff;
}

#nav ul li a {
  text-decoration: none;
  padding: 10px 30px;
  display: block;
  color: #000000;
  background-color: red;
}

#nav a:hover {
  color: #fff;
  background-color: red;
}

#nav .active {
  background-color: red;
  color: #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="nav">
  <ul>
    <li><a>Home</a></li>
    <li><a>About</a></li>
    <li><a>Contact</a></li>
  </ul>
</div></code>```

答:
I just added 'display: flex' to #nav ul.

Please check this fiddle https://jsfiddle.net/smilingpigs/ar1h8ynq/5/

nav {
  text-align: center;
  margin: 0;
  overflow: hidden;
  display: block;
}

nav ul {
  margin: auto;
  padding: 0;
  display: flex;
  font-size: 100%;
  list-style: none;
  list-style-type: none;
}

nav ul li {
  display: inline-block;
}

nav a {
  transition: 0.3s;
  background-color: #fff;
}

nav ul li a {
  text-decoration: none;
  padding: 10px 30px;
  display: flex;
  color: #000000;
  background-color: red;
}

nav a:hover {
  color: #fff;
  background-color: red;
}

nav .active {
  background-color: red;
  color: #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li><a>Home</a></li>
    <li><a>About</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav></code>```

Body:
I would like to know how to fix this issue I have tried everything that I can think of. Any help would be great. all my paddings and margins are set to zero or auto.
nothing that is obvious to me is causing the issue, I have tried first and last child float left and right but this did not work.

#nav {
  text-align: center;
  margin: 0;
  overflow: hidden;
  display: block;
}

#nav ul {
  margin: auto;
  padding: 0;
  font-size: 100%;
  list-style: none;
  list-style-type: none;
}

#nav ul li {
  display: inline-block;
}

#nav a {
  transition: 0.3s;
  background-color: #fff;
}

#nav ul li a {
  text-decoration: none;
  padding: 10px 30px;
  display: block;
  color: #000000;
  background-color: red;
}

#nav a:hover {
  color: #fff;
  background-color: red;
}

#nav .active {
  background-color: red;
  color: #000000;
}

Home

About

Contact

Body:
I just added 'display: flex' to #nav ul.

Please check this fiddle https://jsfiddle.net/smilingpigs/ar1h8ynq/5/

nav {
  text-align: center;
  margin: 0;
  overflow: hidden;
  display: block;
}

nav ul {
  margin: auto;
  padding: 0;
  display: flex;
  font-size: 100%;
  list-style: none;
  list-style-type: none;
}

nav ul li {
  display: inline-block;
}

nav a {
  transition: 0.3s;
  background-color: #fff;
}

nav ul li a {
  text-decoration: none;
  padding: 10px 30px;
  display: flex;
  color: #000000;
  background-color: red;
}

nav a:hover {
  color: #fff;
  background-color: red;
}

nav .active {
  background-color: red;
  color: #000000;
}

<nav>
  <ul>
    <li><a>Home</a></li>
    <li><a>About</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav>


问:
Custom AlertDialog.Builder positive and negative buttons not showing
Hello I followed every tutorial in Stack Overflow and YouTube anyways once I got to display my RecyclerView then I needed to accomplish other things with no problem at all. Anyways my only problem is that the positive button and the negative buttons disappeared. I assume that the problem might be that the things I have done in my XML is overlapping with the buttons in the view but I only have 3 items in the RecyclerView, so this is my big doubt. I made the dialog in an onLongClick then I added a RecyclerView method to get the position and the data present in the row that's why I cant call the alertDialog.setPositiveButton() in another place. This is quite a challenge would be appreciated to get some help in this.

This is my XML

```<code><androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <TextView
        android:id="@+id/text_adm_asigna_asesor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/poppins_bold"
        android:text="Asigna un asesor"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:visibility="visible"
        android:layout_marginRight="30dp" />

        <LinearLayout
            android:id="@+id/linear_dialog_testDrive"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:visibility="gone"
           >

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/circle_imagen_seleccion_alert"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:visibility="gone"
                android:src="@drawable/lifeon_logo"
                android:layout_marginLeft="40dp">

            </de.hdodenhof.circleimageview.CircleImageView>

            <TextView
                android:id="@+id/alert_cambia_test_drive_nombre"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/poppins_bold"
                android:textColor="@android:color/black"
                android:text="@string/nombre"
                android:visibility="gone"
                android:layout_marginLeft="30dp">

            </TextView>

        </LinearLayout>

        <Button
            android:id="@+id/cambiar_seleccion_alert_test_drive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:background="@drawable/button_shape"
            android:text="@string/cambiar_seleccion"
            android:layout_gravity="center_horizontal"
            android:visibility="gone"
            >

        </Button>

    </LinearLayout>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>
</code>```

This is the java code

```<code>      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {

        }

        @Override
        public void onLongClick(View view, int position) {
            asesores.clear();

            ParseObject itemTestDrive = listadoTestDrive.get(position);

            testDriveObjectId = itemTestDrive.getObjectId();

            LayoutInflater inflater = getLayoutInflater();
            View convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_agreements, null);
            alertDialog.setView(convertView);

            RecyclerView list = convertView.findViewById(R.id.list);
            TextView txt = convertView.findViewById(R.id.text_adm_asigna_asesor);
            CircleImageView ima=convertView.findViewById(R.id.circle_imagen_seleccion_alert);
            TextView txtNombreSeleccion=convertView.findViewById(R.id.alert_cambia_test_drive_nombre);
            Button botonCambiarSeleccion=convertView.findViewById(R.id.cambiar_seleccion_alert_test_drive);
            LinearLayout linearLayout=convertView.findViewById(R.id.linear_dialog_testDrive);

            botonCambiarSeleccion.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.setVisibility(View.VISIBLE);
                    ima.setVisibility(View.GONE);
                    txtNombreSeleccion.setVisibility(View.GONE);
                    botonCambiarSeleccion.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                }
            });

            ParseQuery<ParseObject> query1 = ParseQuery.getQuery("CitaTestDrive");
            query1.include("ComercialAsignado");
            query1.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                @Override
                public void done(ParseObject object, ParseException e) {
                    if (object.getParseObject("ComercialAsignado") != null) {
                        txt.setText(getActivity().getResources().getString(R.string.Advertencia_asignacion_a_alguien));

                    }

                }
            });

            ParseUser user = ParseUser.getCurrentUser();

            ParseObject sucursal = user.getParseObject("PerteneceSucursal");
            String sucurObjectId = sucursal.getObjectId();

            ParseQuery<ParseUser> query = ParseUser.getQuery();
            ParseObject suc = ParseObject.createWithoutData("Sucursal", sucurObjectId);
            query.whereEqualTo("PerteneceSucursal", suc);
            query.include("PerteneceSucursal");
            query.whereEqualTo("Rol","Asesor");
            query.findInBackground(new FindCallback<ParseUser>() {
                @Override
                public void done(List<ParseUser> objects, ParseException e) {
                    if (e == null) {
                        for (ParseUser obj : objects) {
                            asesores.add(obj);
                        }
                        list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                        list.setHasFixedSize(true);
                        ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
                        list.setAdapter(adapter);
                    }
                }
            });
            list.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), list, new RecyclerTouchListener.ClickListener() {
                @Override
                public void onClick(View view, int position) {
                    ParseUser item = asesores.get(position);

                    list.setVisibility(view.GONE);
                    ima.setVisibility(view.VISIBLE);
                    txtNombreSeleccion.setVisibility(view.VISIBLE);
                    botonCambiarSeleccion.setVisibility(View.VISIBLE);
                    linearLayout.setVisibility(View.VISIBLE);

                    ParseFile parseFile = item.getParseFile("Avatar");
                    if (parseFile != null) {
                        parseFile.getDataInBackground(new GetDataCallback() {
                            @Override
                            public void done(byte[] data, ParseException e) {
                                if (e == null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                                    if (bmp != null) {
                                        ima.setImageBitmap(bmp);
                                    }
                                }
                            }
                        });
                    }

                    String asesorObjectId = item.getObjectId();
                    String asesorNombre = item.getString("Nombre");
                    txtNombreSeleccion.setText(asesorNombre);

                    alertDialog.setPositiveButton(getApplicationContext().getResources().getString(R.string.guardar), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ParseQuery<ParseObject> query = ParseQuery.getQuery("CitaTestDrive");

                            query.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                                @Override
                                public void done(ParseObject object, ParseException e) {

                                    object.put("ComercialAsignado", ParseObject.createWithoutData("_User", asesorObjectId));
                                    object.put("PendienteAsignacionAdmin", "Asignado");
                                    object.saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(ParseException e) {
                                            if (e == null) {
                                                Toast.makeText(getApplicationContext(), "Test drive asignado a:" + asesorNombre, Toast.LENGTH_LONG).show();
                                            } else {
                                                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });

                                }

                            });

                            adapter.notifyDataSetChanged();

                        }
                    });

                    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                }

                @Override
                public void onLongClick(View view, int position) {

                }
            }));

            list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            list.setHasFixedSize(true);

            ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
            list.setAdapter(adapter);

            alertDialog.show();

        }
    }));
</code>```

Appreciate if you don't answer if you don't know the correct answer or way to solve this.

Update: Android is gone crazy!!!.When I make the first onLongClick the alert dialog still doesn't work since I don't have a way to go back I click in the outside of the alert dialog and it disappears. Then I make another long Click and it works!!! this is very weird why does this happen????? nothing have changed.

答:
use code like this,</p>

```<code>AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setMessage(message);
    builder.setCancelable(false);
    builder.setPositiveButton(
            "Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

                }
            });

    builder.setNegativeButton(
            "No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

              }
            });

    AlertDialog alert = builder.create();
    alert.setOnShowListener(arg0 -> {
        alert.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.RED));
        alert.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.RED));
    });
    alert.show();
</code>```

Body:
Hello I followed every tutorial in Stack Overflow and YouTube anyways once I got to display my RecyclerView then I needed to accomplish other things with no problem at all. Anyways my only problem is that the positive button and the negative buttons disappeared. I assume that the problem might be that the things I have done in my XML is overlapping with the buttons in the view but I only have 3 items in the RecyclerView, so this is my big doubt. I made the dialog in an onLongClick then I added a RecyclerView method to get the position and the data present in the row that's why I cant call the alertDialog.setPositiveButton() in another place. This is quite a challenge would be appreciated to get some help in this.

This is my XML

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <TextView
        android:id="@+id/text_adm_asigna_asesor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/poppins_bold"
        android:text="Asigna un asesor"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:visibility="visible"
        android:layout_marginRight="30dp" />

        <LinearLayout
            android:id="@+id/linear_dialog_testDrive"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:visibility="gone"
           >

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/circle_imagen_seleccion_alert"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:visibility="gone"
                android:src="@drawable/lifeon_logo"
                android:layout_marginLeft="40dp">

            </de.hdodenhof.circleimageview.CircleImageView>

            <TextView
                android:id="@+id/alert_cambia_test_drive_nombre"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/poppins_bold"
                android:textColor="@android:color/black"
                android:text="@string/nombre"
                android:visibility="gone"
                android:layout_marginLeft="30dp">

            </TextView>

        </LinearLayout>

        <Button
            android:id="@+id/cambiar_seleccion_alert_test_drive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:background="@drawable/button_shape"
            android:text="@string/cambiar_seleccion"
            android:layout_gravity="center_horizontal"
            android:visibility="gone"
            >

        </Button>

    </LinearLayout>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>

This is the java code

      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {

        }

        @Override
        public void onLongClick(View view, int position) {
            asesores.clear();

            ParseObject itemTestDrive = listadoTestDrive.get(position);

            testDriveObjectId = itemTestDrive.getObjectId();

            LayoutInflater inflater = getLayoutInflater();
            View convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_agreements, null);
            alertDialog.setView(convertView);

            RecyclerView list = convertView.findViewById(R.id.list);
            TextView txt = convertView.findViewById(R.id.text_adm_asigna_asesor);
            CircleImageView ima=convertView.findViewById(R.id.circle_imagen_seleccion_alert);
            TextView txtNombreSeleccion=convertView.findViewById(R.id.alert_cambia_test_drive_nombre);
            Button botonCambiarSeleccion=convertView.findViewById(R.id.cambiar_seleccion_alert_test_drive);
            LinearLayout linearLayout=convertView.findViewById(R.id.linear_dialog_testDrive);

            botonCambiarSeleccion.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.setVisibility(View.VISIBLE);
                    ima.setVisibility(View.GONE);
                    txtNombreSeleccion.setVisibility(View.GONE);
                    botonCambiarSeleccion.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                }
            });

            ParseQuery<ParseObject> query1 = ParseQuery.getQuery("CitaTestDrive");
            query1.include("ComercialAsignado");
            query1.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                @Override
                public void done(ParseObject object, ParseException e) {
                    if (object.getParseObject("ComercialAsignado") != null) {
                        txt.setText(getActivity().getResources().getString(R.string.Advertencia_asignacion_a_alguien));

                    }

                }
            });

            ParseUser user = ParseUser.getCurrentUser();

            ParseObject sucursal = user.getParseObject("PerteneceSucursal");
            String sucurObjectId = sucursal.getObjectId();

            ParseQuery<ParseUser> query = ParseUser.getQuery();
            ParseObject suc = ParseObject.createWithoutData("Sucursal", sucurObjectId);
            query.whereEqualTo("PerteneceSucursal", suc);
            query.include("PerteneceSucursal");
            query.whereEqualTo("Rol","Asesor");
            query.findInBackground(new FindCallback<ParseUser>() {
                @Override
                public void done(List<ParseUser> objects, ParseException e) {
                    if (e == null) {
                        for (ParseUser obj : objects) {
                            asesores.add(obj);
                        }
                        list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                        list.setHasFixedSize(true);
                        ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
                        list.setAdapter(adapter);
                    }
                }
            });
            list.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), list, new RecyclerTouchListener.ClickListener() {
                @Override
                public void onClick(View view, int position) {
                    ParseUser item = asesores.get(position);

                    list.setVisibility(view.GONE);
                    ima.setVisibility(view.VISIBLE);
                    txtNombreSeleccion.setVisibility(view.VISIBLE);
                    botonCambiarSeleccion.setVisibility(View.VISIBLE);
                    linearLayout.setVisibility(View.VISIBLE);

                    ParseFile parseFile = item.getParseFile("Avatar");
                    if (parseFile != null) {
                        parseFile.getDataInBackground(new GetDataCallback() {
                            @Override
                            public void done(byte[] data, ParseException e) {
                                if (e == null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                                    if (bmp != null) {
                                        ima.setImageBitmap(bmp);
                                    }
                                }
                            }
                        });
                    }

                    String asesorObjectId = item.getObjectId();
                    String asesorNombre = item.getString("Nombre");
                    txtNombreSeleccion.setText(asesorNombre);

                    alertDialog.setPositiveButton(getApplicationContext().getResources().getString(R.string.guardar), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ParseQuery<ParseObject> query = ParseQuery.getQuery("CitaTestDrive");

                            query.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                                @Override
                                public void done(ParseObject object, ParseException e) {

                                    object.put("ComercialAsignado", ParseObject.createWithoutData("_User", asesorObjectId));
                                    object.put("PendienteAsignacionAdmin", "Asignado");
                                    object.saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(ParseException e) {
                                            if (e == null) {
                                                Toast.makeText(getApplicationContext(), "Test drive asignado a:" + asesorNombre, Toast.LENGTH_LONG).show();
                                            } else {
                                                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });

                                }

                            });

                            adapter.notifyDataSetChanged();

                        }
                    });

                    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                }

                @Override
                public void onLongClick(View view, int position) {

                }
            }));

            list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            list.setHasFixedSize(true);

            ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
            list.setAdapter(adapter);

            alertDialog.show();

        }
    }));

Appreciate if you don't answer if you don't know the correct answer or way to solve this.

Update: Android is gone crazy!!!.When I make the first onLongClick the alert dialog still doesn't work since I don't have a way to go back I click in the outside of the alert dialog and it disappears. Then I make another long Click and it works!!! this is very weird why does this happen????? nothing have changed.

Body:
use code like this,

AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setMessage(message);
    builder.setCancelable(false);
    builder.setPositiveButton(
            "Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

                }
            });

    builder.setNegativeButton(
            "No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

              }
            });

    AlertDialog alert = builder.create();
    alert.setOnShowListener(arg0 -> {
        alert.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.RED));
        alert.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.RED));
    });
    alert.show();


问:
How to avoid data from other tab to be visible in current tab
I am using createMaterialTopTabNavigator to display Top Tabs in react native but the data from other tab is visible on the current tab

I have tried to set the container style to flex 1 and the flexWrap : 'wrap' but still the problem persists

```<code>const NotificationTabs = createMaterialTopTabNavigator(
  {
    MobileNotification: {
      screen: MobileNotificationScreen,
      navigationOptions: {
        title: Languages.Notifications.Mobile,
      },
    },
    EmailNotification: {
      screen: EmailNotificationScreen,
      navigationOptions: {
        title: Languages.Notifications.Email,
      },
    },
  },
  {
    initialRouteName: 'MobileNotification',
    tabBarComponent: TopTabBarComponent,
    tabBarOptions: {
      style: {
        backgroundColor: Colors.SAWhite,
      },
      labelStyle: {
        color: Colors.SAPrimary,
        ...Fonts.Style.normal,
      },
      activeTintColor: Colors.SAPrimary,
      inactiveTintColor: Colors.SASecondary,
      upperCaseLabel: false,
    },
  }
);
</code>```

```<code> <View style={styles.flat}>
    <NotificationTabs navigation={navigation} />
 </View>
</code>```

styles

```<code>  flat: {
    flex:1
    borderRadius:10
    marginTop: '10%',
    padding: 4,
    backgroundColor: Colors.SAWhite,
  },
</code>```

答:
I fixed it by adding overflow: 'hidden' to the styles

```<code>  flat: {
    flex:1
    borderRadius:10
    marginTop: '10%',
    padding: 4,
    backgroundColor: Colors.SAWhite,
    overflow: 'hidden'
  }
</code>```

Body:
I am using createMaterialTopTabNavigator to display Top Tabs in react native but the data from other tab is visible on the current tab

I have tried to set the container style to flex 1 and the flexWrap : 'wrap' but still the problem persists

const NotificationTabs = createMaterialTopTabNavigator(
  {
    MobileNotification: {
      screen: MobileNotificationScreen,
      navigationOptions: {
        title: Languages.Notifications.Mobile,
      },
    },
    EmailNotification: {
      screen: EmailNotificationScreen,
      navigationOptions: {
        title: Languages.Notifications.Email,
      },
    },
  },
  {
    initialRouteName: 'MobileNotification',
    tabBarComponent: TopTabBarComponent,
    tabBarOptions: {
      style: {
        backgroundColor: Colors.SAWhite,
      },
      labelStyle: {
        color: Colors.SAPrimary,
        ...Fonts.Style.normal,
      },
      activeTintColor: Colors.SAPrimary,
      inactiveTintColor: Colors.SASecondary,
      upperCaseLabel: false,
    },
  }
);

 <View style={styles.flat}>
    <NotificationTabs navigation={navigation} />
 </View>

styles

  flat: {
    flex:1
    borderRadius:10
    marginTop: '10%',
    padding: 4,
    backgroundColor: Colors.SAWhite,
  },

Body:
I fixed it by adding overflow: 'hidden' to the styles

  flat: {
    flex:1
    borderRadius:10
    marginTop: '10%',
    padding: 4,
    backgroundColor: Colors.SAWhite,
    overflow: 'hidden'
  }


问:
React Axios how to correctly pass in config as parameter?
Does anyone know how to pass in config in Axios?
It works when the option that is passed in is "method:'GET'", but it won't work when options are "method:'POST,data:jsondata". it returns error 500 with 'GET' method. Why is it still a 'GET' method, is there a workaround or I'm doing it wrong?
I want to call only this function when using Axios.

```<code> fetchWithToken(url, options) {
        const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }
        if (this.loggedIn) {
            headers['Authorization'] = 'Bearer ' + this.getToken()
            return axios(url, { headers, options })
                .then(response => { return response })
        }
}
</code>```

答:
```<code>let postData = {
    // DATA FOR POST METHOD
}

axios({
    method: 'POST',
    url: `YOUR_API_ENDPOINT`,
    headers: {
        Authorization: `YOUR_AUTH_TOKEN`,
        "Content-Type": "application/json"
    },
    data: {
        ...postData
    }
})
.then((res) => {
    // YOUR CODE HERE
})
.catch((err) => {
    console.log(err);
});
</code>```

Body:
Does anyone know how to pass in config in Axios?
It works when the option that is passed in is "method:'GET'", but it won't work when options are "method:'POST,data:jsondata". it returns error 500 with 'GET' method. Why is it still a 'GET' method, is there a workaround or I'm doing it wrong?
I want to call only this function when using Axios.

 fetchWithToken(url, options) {
        const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }
        if (this.loggedIn) {
            headers['Authorization'] = 'Bearer ' + this.getToken()
            return axios(url, { headers, options })
                .then(response => { return response })
        }
}


问:
how to set initialRouteName dynamically in the react-native
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

```<code>import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);
</code>```

答:
You can check the condition on the main page or App.js

```<code>render() {
  const status = get AsyncStorage.getItem('unit');
  if(status != null)
  { return <Home/> }
  else
  { return <AnotherScreen/> }
}
</code>```

But we can switch between pages if we use stacknavigator or switchnavigator..
We cant goto the particular tabs directly according to my knowledge. (Correct me if I am wrong).

Body:
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);

Body:
You can check the condition on the main page or App.js

render() {
  const status = get AsyncStorage.getItem('unit');
  if(status != null)
  { return <Home/> }
  else
  { return <AnotherScreen/> }
}

But we can switch between pages if we use stacknavigator or switchnavigator..
We cant goto the particular tabs directly according to my knowledge. (Correct me if I am wrong).


问:
allauth unverified email remains unverified once email expires
I have a custom user model. and I use Django rest auth to handle authentication of users. the problem is that after sign up when the email is sent. if the user doesn't verify the email before it expires, it seems that it remains stuck like that indefinitely. I was expecting the verification email to be sent again since ACCOUNT_EMAIL_VERIFICATION = "mandatory" in my settings, from the documentation, it is supposed to resend the verification message by default, but this isnt happening. I am lost as to what else to do and I can't seem to find any resource that helps.

below is my model

models.py

```<code>class User(AbstractBaseUser, PermissionsMixin):
    username = None
    email = models.EmailField(max_length=254, unique=True)
    name = models.CharField(max_length=250)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=255, unique=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

</code>```

in my settings.py the user has an expiry date of 2 days

```<code>ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None #or "api/authenticated/"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1
ACCOUNT_EMAIL_CONFIRMATION_HMAC = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_VERIFICATION = "mandatory"
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 3600
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 180
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_LOGIN_ON_PASSWORD_RESET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "api/login/"
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
</code>```

答:
First of all, you have mentioned you are using django-rest-auth which is not the case, and you are probably using django-allauth.

According to django-allauth's documentation:

ACCOUNT_EMAIL_VERIFICATION:

When set to “mandatory” the user is blocked from logging in until the email address is verified. Choose “optional” or “none” to allow logins with an unverified e-mail address. In case of “optional”, the e-mail verification mail is still sent, whereas in case of “none” no e-mail verification mails are sent.

So there is nothing mentioned about re-sending the verification email if the first one expires. To accomplish what you want, you should have a job script running and checking for expired verification tokens and re-send the verification emails manually.

You should create a script that looks something like this:

```<code>from time import sleep
from django.utils import timezone
from django_allauth.account.models import EmailConfirmation

while True:
    def_expired = timezone.now() - datetime.timedelta(days=app_settings.EMAIL_CONFIRMATION_EXPIRE_DAYS)
    expired_tokens = EmailConfirmation.objects.filter(sent__lte=def_expired)
    for token in expired_tokens:
        token.send()
    sleep(2)
</code>```

And keep this script running using any scheduler you like (supervisor, pm2, cronjob, etc).

Bottom line, django-allauth does not/can not have the functionality you want. This job needs to be done manually.

Body:
I have a custom user model. and I use Django rest auth to handle authentication of users. the problem is that after sign up when the email is sent. if the user doesn't verify the email before it expires, it seems that it remains stuck like that indefinitely. I was expecting the verification email to be sent again since ACCOUNT_EMAIL_VERIFICATION = "mandatory" in my settings, from the documentation, it is supposed to resend the verification message by default, but this isnt happening. I am lost as to what else to do and I can't seem to find any resource that helps.

below is my model

models.py

class User(AbstractBaseUser, PermissionsMixin):
    username = None
    email = models.EmailField(max_length=254, unique=True)
    name = models.CharField(max_length=250)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=255, unique=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

in my settings.py the user has an expiry date of 2 days

ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None #or "api/authenticated/"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1
ACCOUNT_EMAIL_CONFIRMATION_HMAC = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_VERIFICATION = "mandatory"
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 3600
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 180
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_LOGIN_ON_PASSWORD_RESET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "api/login/"
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"

Body:
First of all, you have mentioned you are using django-rest-auth which is not the case, and you are probably using django-allauth.

According to django-allauth's documentation:

ACCOUNT_EMAIL_VERIFICATION:

When set to “mandatory” the user is blocked from logging in until the email address is verified. Choose “optional” or “none” to allow logins with an unverified e-mail address. In case of “optional”, the e-mail verification mail is still sent, whereas in case of “none” no e-mail verification mails are sent.

So there is nothing mentioned about re-sending the verification email if the first one expires. To accomplish what you want, you should have a job script running and checking for expired verification tokens and re-send the verification emails manually.

You should create a script that looks something like this:

from time import sleep
from django.utils import timezone
from django_allauth.account.models import EmailConfirmation

while True:
    def_expired = timezone.now() - datetime.timedelta(days=app_settings.EMAIL_CONFIRMATION_EXPIRE_DAYS)
    expired_tokens = EmailConfirmation.objects.filter(sent__lte=def_expired)
    for token in expired_tokens:
        token.send()
    sleep(2)

And keep this script running using any scheduler you like (supervisor, pm2, cronjob, etc).

Bottom line, django-allauth does not/can not have the functionality you want. This job needs to be done manually.


问:
REGEX from PHP to JS
Could you suggest how to correct this expression

```<code>(^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$)
</code>```

for use with javascript, so that it gives the true when the date formats are yyyy-mm-yy and when the dates are listed separated by commas if there are several of them?

```<code>Expected result:
2017-03-25, 2017-03-27, 2017-03-28 true
2017-03-25 true
</code>```

答:
Your PHP regex contains a bug, namely, the Group 1 parentheses are wrapping the whole pattern while the recursed part should only be ([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]).

So, in order to fix the PHP pattern, you need to remove the outer parentheses:

```<code>^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$
</code>```

Since the (?1) regex subroutine recurses the Group 1 pattern, all you need is to repeat the pattrn in a JS regex:

```<code>^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])(?:,\s*[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))*$
</code>```

See this regex demo.

In JS code, do not write it as a regex literal, create it dynamically for easier maintenance:

const date_reg = `[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])`;
const reg = new RegExp(String.raw`^${date_reg}(?:,\s*${date_reg})*$`);
console.log(reg.test("2017-03-25, 2017-03-27, 2017-03-28"));```

Title: REGEX from PHP to JS

Body:
Could you suggest how to correct this expression

(^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$)

for use with javascript, so that it gives the true when the date formats are yyyy-mm-yy and when the dates are listed separated by commas if there are several of them?

Expected result:
2017-03-25, 2017-03-27, 2017-03-28 true
2017-03-25 true

Body:
Your PHP regex contains a bug, namely, the Group 1 parentheses are wrapping the whole pattern while the recursed part should only be ([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]).

So, in order to fix the PHP pattern, you need to remove the outer parentheses:

^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$

Since the (?1) regex subroutine recurses the Group 1 pattern, all you need is to repeat the pattrn in a JS regex:

^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])(?:,\s*[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))*$

See this regex demo.

In JS code, do not write it as a regex literal, create it dynamically for easier maintenance:

const date_reg = `[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])`;
const reg = new RegExp(String.raw`^${date_reg}(?:,\s*${date_reg})*$`);
console.log(reg.test("2017-03-25, 2017-03-27, 2017-03-28"));


问:
Swagger C# Enum generation - underlying int values do not match the original enum
I created an enum on my server with integer values set manually rather than the default increment up from 0

```<code>public enum UserType
{
    Anonymous = 0,
    Customer = 10,
    Technician = 21,
    Manager = 25,
    Primary = 30
}
</code>```

My server is running using AspNetCore.App 2.2.0. It's configured in Startup.cs with swashbuckle aspnetcore 4.0.1 to generate a swagger json file to describe the api every time the server is started.

I then use NSwag Studio for windows v 13.2.3.0 to generate a C sharp api client with that swagger JSON file, for use in a Xamarin app. The generated enum in the resulting c sharp api client looks like this - the underlying integer values do not match the original enum.

```<code>[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.1.5.0 (Newtonsoft.Json v11.0.0.0)")]
public enum UserType
{
    [System.Runtime.Serialization.EnumMember(Value = @"Anonymous")]
    Anonymous = 0,

    [System.Runtime.Serialization.EnumMember(Value = @"Customer")]
    Customer = 1,

    [System.Runtime.Serialization.EnumMember(Value = @"Technician")]
    Technician = 2,

    [System.Runtime.Serialization.EnumMember(Value = @"Manager")]
    Manager = 3,

    [System.Runtime.Serialization.EnumMember(Value = @"Primary")]
    Primary = 4,

}
</code>```

This creates a problem for me client side as there are situations where I need to know the integer value. I am looking for a solution where I can avoid writing converters every time I want to know the integer value on the client side.

Option 1:
Is there an option I am missing in either NSwag Studio or in .net configuration (my Startup.Cs config is below for reference) where I can force the generated enums to get the same integer values as the original enum?

Option 2:
Alternatively if not, both my client and my server have access to the same original enum via a shared class library. Is there a way to get the generated api client to use the actual original enums in the apiclient.cs rather than generate its own?

Reference:

The enums part of my swagger generation code in Startup.Cs looks like this

```<code>services.AddJsonOptions(options =>
{
   options.SerializerSettings.Converters.Add(new StringEnumConverter());
....

services.AddSwaggerGen(setup =>
{
   setup.SwaggerDoc("v1", new Info { Title = AppConst.SwaggerTitle, Version = "v1" });

   setup.UseReferencedDefinitionsForEnums();
   ... other stuff...
 }
</code>```

答:
So these are the two Enum Helpers I'm using. One is used by NSwag (x-enumNames) and the other is used by Azure AutoRest (x-ms-enums)

Finally found the reference for EnumDocumentFilter (https://stackoverflow.com/a/49941775/1910735)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace SwaggerDocsHelpers
{
    /// <summary>
    /// Add enum value descriptions to Swagger
    /// https://stackoverflow.com/a/49941775/1910735
    /// </summary>
    public class EnumDocumentFilter : IDocumentFilter
    {
        /// <inheritdoc />
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            // add enum descriptions to result models
            foreach (var schemaDictionaryItem in swaggerDoc.Definitions)
            {
                var schema = schemaDictionaryItem.Value;
                foreach (var propertyDictionaryItem in schema.Properties)
                {
                    var property = propertyDictionaryItem.Value;
                    var propertyEnums = property.Enum;
                    if (propertyEnums != null && propertyEnums.Count > 0)
                    {
                        property.Description += DescribeEnum(propertyEnums);
                    }
                }
            }

            if (swaggerDoc.Paths.Count <= 0) return;

            // add enum descriptions to input parameters
            foreach (var pathItem in swaggerDoc.Paths.Values)
            {
                DescribeEnumParameters(pathItem.Parameters);

                // head, patch, options, delete left out
                var possibleParameterisedOperations = new List<Operation> { pathItem.Get, pathItem.Post, pathItem.Put };
                possibleParameterisedOperations.FindAll(x => x != null)
                    .ForEach(x => DescribeEnumParameters(x.Parameters));
            }
        }

        private static void DescribeEnumParameters(IList<IParameter> parameters)
        {
            if (parameters == null) return;

            foreach (var param in parameters)
            {
                if (param is NonBodyParameter nbParam && nbParam.Enum?.Any() == true)
                {
                    param.Description += DescribeEnum(nbParam.Enum);
                }
                else if (param.Extensions.ContainsKey("enum") && param.Extensions["enum"] is IList<object> paramEnums &&
                  paramEnums.Count > 0)
                {
                    param.Description += DescribeEnum(paramEnums);
                }
            }
        }

        private static string DescribeEnum(IEnumerable<object> enums)
        {
            var enumDescriptions = new List<string>();
            Type type = null;
            foreach (var enumOption in enums)
            {
                if (type == null) type = enumOption.GetType();
                enumDescriptions.Add($"{Convert.ChangeType(enumOption, type.GetEnumUnderlyingType())} = {Enum.GetName(type, enumOption)}");
            }

            return $"{Environment.NewLine}{string.Join(Environment.NewLine, enumDescriptions)}";
        }
    }

    public class EnumFilter : ISchemaFilter
    {
        public void Apply(Schema model, SchemaFilterContext context)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (context == null)
                throw new ArgumentNullException("context");

            if (context.SystemType.IsEnum)
            {

                var enumUnderlyingType = context.SystemType.GetEnumUnderlyingType();
                model.Extensions.Add("x-ms-enum", new
                {
                    name = context.SystemType.Name,
                    modelAsString = false,
                    values = context.SystemType
                    .GetEnumValues()
                    .Cast<object>()
                    .Distinct()
                    .Select(value =>
                    {
                        //var t = context.SystemType;
                        //var convereted = Convert.ChangeType(value, enumUnderlyingType);
                        //return new { value = convereted, name = value.ToString() };
                        return new { value = value, name = value.ToString() };
                    })
                    .ToArray()
                });
            }
        }
    }

    /// <summary>
    /// Adds extra schema details for an enum in the swagger.json i.e. x-enumNames (used by NSwag to generate Enums for C# client)
    /// https://github.com/RicoSuter/NSwag/issues/1234
    /// </summary>
    public class NSwagEnumExtensionSchemaFilter : ISchemaFilter
    {
        public void Apply(Schema model, SchemaFilterContext context)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (context == null)
                throw new ArgumentNullException("context");

            if (context.SystemType.IsEnum)
            {
                var names = Enum.GetNames(context.SystemType);
                model.Extensions.Add("x-enumNames", names);
            }
        }
    }
}
</code>```

Then in your startup.cs you configure them

```<code>        services.AddSwaggerGen(c =>
        {
            ... the rest of your configuration

            // REMOVE THIS to use Integers for Enums
            // c.DescribeAllEnumsAsStrings();

            // add enum generators based on whichever code generators you decide
            c.SchemaFilter<NSwagEnumExtensionSchemaFilter>();
            c.SchemaFilter<EnumFilter>();
        });
</code>```

This should generate your enums as this in the Swagger.json file

```<code>        sensorType: {
          format: "int32",
          enum: [
            0,
            1,
            2,
            3
          ],
          type: "integer",
          x-enumNames: [
            "NotSpecified",
            "Temperature",
            "Fuel",
            "Axle"
          ],
          x-ms-enum: {
            name: "SensorTypesEnum",
            modelAsString: false,
            values: [{
                value: 0,
                name: "NotSpecified"
              },
              {
                value: 1,
                name: "Temperature"
              },
              {
                value: 2,
                name: "Fuel"
              },
              {
                value: 3,
                name: "Axle"
              }
            ]
          }
        },
</code>```

There is one issue with this solution though, (which I haven't had time to look into)
Is that the Enum names are generated with my DTO names in NSwag - If you do find a solution to this do let me know :-)

Example, the following Enum was generated using NSwag:

Body:
I created an enum on my server with integer values set manually rather than the default increment up from 0

public enum UserType
{
    Anonymous = 0,
    Customer = 10,
    Technician = 21,
    Manager = 25,
    Primary = 30
}

My server is running using AspNetCore.App 2.2.0. It's configured in Startup.cs with swashbuckle aspnetcore 4.0.1 to generate a swagger json file to describe the api every time the server is started.

I then use NSwag Studio for windows v 13.2.3.0 to generate a C sharp api client with that swagger JSON file, for use in a Xamarin app. The generated enum in the resulting c sharp api client looks like this - the underlying integer values do not match the original enum.

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.1.5.0 (Newtonsoft.Json v11.0.0.0)")]
public enum UserType
{
    [System.Runtime.Serialization.EnumMember(Value = @"Anonymous")]
    Anonymous = 0,

    [System.Runtime.Serialization.EnumMember(Value = @"Customer")]
    Customer = 1,

    [System.Runtime.Serialization.EnumMember(Value = @"Technician")]
    Technician = 2,

    [System.Runtime.Serialization.EnumMember(Value = @"Manager")]
    Manager = 3,

    [System.Runtime.Serialization.EnumMember(Value = @"Primary")]
    Primary = 4,

}

This creates a problem for me client side as there are situations where I need to know the integer value. I am looking for a solution where I can avoid writing converters every time I want to know the integer value on the client side.

Option 1:
Is there an option I am missing in either NSwag Studio or in .net configuration (my Startup.Cs config is below for reference) where I can force the generated enums to get the same integer values as the original enum?

Option 2:
Alternatively if not, both my client and my server have access to the same original enum via a shared class library. Is there a way to get the generated api client to use the actual original enums in the apiclient.cs rather than generate its own?

Reference:

The enums part of my swagger generation code in Startup.Cs looks like this

services.AddJsonOptions(options =>
{
   options.SerializerSettings.Converters.Add(new StringEnumConverter());
....

services.AddSwaggerGen(setup =>
{
   setup.SwaggerDoc("v1", new Info { Title = AppConst.SwaggerTitle, Version = "v1" });

   setup.UseReferencedDefinitionsForEnums();
   ... other stuff...
 }

Body:
So these are the two Enum Helpers I'm using. One is used by NSwag (x-enumNames) and the other is used by Azure AutoRest (x-ms-enums)

Finally found the reference for EnumDocumentFilter (https://stackoverflow.com/a/49941775/1910735)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace SwaggerDocsHelpers
{
    /// <summary>
    /// Add enum value descriptions to Swagger
    /// https://stackoverflow.com/a/49941775/1910735
    /// </summary>
    public class EnumDocumentFilter : IDocumentFilter
    {
        /// <inheritdoc />
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            // add enum descriptions to result models
            foreach (var schemaDictionaryItem in swaggerDoc.Definitions)
            {
                var schema = schemaDictionaryItem.Value;
                foreach (var propertyDictionaryItem in schema.Properties)
                {
                    var property = propertyDictionaryItem.Value;
                    var propertyEnums = property.Enum;
                    if (propertyEnums != null && propertyEnums.Count > 0)
                    {
                        property.Description += DescribeEnum(propertyEnums);
                    }
                }
            }

            if (swaggerDoc.Paths.Count <= 0) return;

            // add enum descriptions to input parameters
            foreach (var pathItem in swaggerDoc.Paths.Values)
            {
                DescribeEnumParameters(pathItem.Parameters);

                // head, patch, options, delete left out
                var possibleParameterisedOperations = new List<Operation> { pathItem.Get, pathItem.Post, pathItem.Put };
                possibleParameterisedOperations.FindAll(x => x != null)
                    .ForEach(x => DescribeEnumParameters(x.Parameters));
            }
        }

        private static void DescribeEnumParameters(IList<IParameter> parameters)
        {
            if (parameters == null) return;

            foreach (var param in parameters)
            {
                if (param is NonBodyParameter nbParam && nbParam.Enum?.Any() == true)
                {
                    param.Description += DescribeEnum(nbParam.Enum);
                }
                else if (param.Extensions.ContainsKey("enum") && param.Extensions["enum"] is IList<object> paramEnums &&
                  paramEnums.Count > 0)
                {
                    param.Description += DescribeEnum(paramEnums);
                }
            }
        }

        private static string DescribeEnum(IEnumerable<object> enums)
        {
            var enumDescriptions = new List<string>();
            Type type = null;
            foreach (var enumOption in enums)
            {
                if (type == null) type = enumOption.GetType();
                enumDescriptions.Add($"{Convert.ChangeType(enumOption, type.GetEnumUnderlyingType())} = {Enum.GetName(type, enumOption)}");
            }

            return $"{Environment.NewLine}{string.Join(Environment.NewLine, enumDescriptions)}";
        }
    }

    public class EnumFilter : ISchemaFilter
    {
        public void Apply(Schema model, SchemaFilterContext context)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (context == null)
                throw new ArgumentNullException("context");

            if (context.SystemType.IsEnum)
            {

                var enumUnderlyingType = context.SystemType.GetEnumUnderlyingType();
                model.Extensions.Add("x-ms-enum", new
                {
                    name = context.SystemType.Name,
                    modelAsString = false,
                    values = context.SystemType
                    .GetEnumValues()
                    .Cast<object>()
                    .Distinct()
                    .Select(value =>
                    {
                        //var t = context.SystemType;
                        //var convereted = Convert.ChangeType(value, enumUnderlyingType);
                        //return new { value = convereted, name = value.ToString() };
                        return new { value = value, name = value.ToString() };
                    })
                    .ToArray()
                });
            }
        }
    }

    /// <summary>
    /// Adds extra schema details for an enum in the swagger.json i.e. x-enumNames (used by NSwag to generate Enums for C# client)
    /// https://github.com/RicoSuter/NSwag/issues/1234
    /// </summary>
    public class NSwagEnumExtensionSchemaFilter : ISchemaFilter
    {
        public void Apply(Schema model, SchemaFilterContext context)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (context == null)
                throw new ArgumentNullException("context");

            if (context.SystemType.IsEnum)
            {
                var names = Enum.GetNames(context.SystemType);
                model.Extensions.Add("x-enumNames", names);
            }
        }
    }
}

Then in your startup.cs you configure them

        services.AddSwaggerGen(c =>
        {
            ... the rest of your configuration

            // REMOVE THIS to use Integers for Enums
            // c.DescribeAllEnumsAsStrings();

            // add enum generators based on whichever code generators you decide
            c.SchemaFilter<NSwagEnumExtensionSchemaFilter>();
            c.SchemaFilter<EnumFilter>();
        });

This should generate your enums as this in the Swagger.json file

        sensorType: {
          format: "int32",
          enum: [
            0,
            1,
            2,
            3
          ],
          type: "integer",
          x-enumNames: [
            "NotSpecified",
            "Temperature",
            "Fuel",
            "Axle"
          ],
          x-ms-enum: {
            name: "SensorTypesEnum",
            modelAsString: false,
            values: [{
                value: 0,
                name: "NotSpecified"
              },
              {
                value: 1,
                name: "Temperature"
              },
              {
                value: 2,
                name: "Fuel"
              },
              {
                value: 3,
                name: "Axle"
              }
            ]
          }
        },

There is one issue with this solution though, (which I haven't had time to look into)
Is that the Enum names are generated with my DTO names in NSwag - If you do find a solution to this do let me know :-)

Example, the following Enum was generated using NSwag:


问:
Accessing C++ std::vector object members before object initialization
I just realized that I can access object members of my empty object vector list.
I thought vector.reserve(nmb) just reserves the required memory (kind of nmb*sizeof(object)).

```<code>#include <iostream>
#include <vector>

class Car {

    public: int tires = 4;

    Car(void) {
        std::cout << "Constructor of Car" << std::endl;
    }
};

int main()
{
    std::vector<Car> carList;
    carList.reserve(20);
    std::cout << "Car tires: " << carList[0].tires << std::endl;
    std::cout << "Now comes the emplace_back:" << std::endl;
    carList.emplace_back();
    std::cout << "Car tires: " << carList[0].tires << std::endl;

    //Car carArray[20];
    //std::cout << "Car tires: " << carArray[0].tires << std::endl;

    return 0;
}
</code>```

gives me:

```<code>Car tires: 0
Now comes the emplace_back:
Constructor of Car
Car tires: 4

...Program finished with exit code 0
</code>```

Why can I access members of not yet initialized objects?
Thank you.

答:
Because the operator[] does not do any boundary checks (and just translates to some pointer arithmetic when you compile an optimized binary). This is so std::vector can be as efficiently used as a plain C array.

The 0 that you read is just what happens to be in memory where the vector has reserved space on the heap. Note that the operating system initializes the program's memory with 0 as a security measure (so you cannot peek on old data). If your applications runs a bit longer and pages are recycled, you can also observe other garbage values.

You could try at() instead which will check for boundaries.

Body:
I just realized that I can access object members of my empty object vector list.
I thought vector.reserve(nmb) just reserves the required memory (kind of nmb*sizeof(object)).

#include <iostream>
#include <vector>

class Car {

    public: int tires = 4;

    Car(void) {
        std::cout << "Constructor of Car" << std::endl;
    }
};

int main()
{
    std::vector<Car> carList;
    carList.reserve(20);
    std::cout << "Car tires: " << carList[0].tires << std::endl;
    std::cout << "Now comes the emplace_back:" << std::endl;
    carList.emplace_back();
    std::cout << "Car tires: " << carList[0].tires << std::endl;

    //Car carArray[20];
    //std::cout << "Car tires: " << carArray[0].tires << std::endl;

    return 0;
}

gives me:

Car tires: 0
Now comes the emplace_back:
Constructor of Car
Car tires: 4

...Program finished with exit code 0

Why can I access members of not yet initialized objects?
Thank you.


问:
Group by with Inner join doesn't return any result
```<code>SELECT TOP 6 *
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber
</code>```

I have a table vws_entryline associated to the table vws_customer according to the account number of the customers, as you can see. I would want to group the results by another field, VoucherNumber (which is present in vws_entryline only).

For example, I would want to have these results (it's not JSON format, only an example from my mind that doesn't correspond exactly to a group by... but what I want is actually a SQL group by result):

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "N45PO",
  field_1_vws_entryline: 150.25},

{AccountNumber: "PO200",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "PO200",
  "VoucherNumber": "N45PO", field_1_vws_entryline: 25.75},

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "AZERTY",
  field_1_vws_entryline: 50,50},

{AccountNumber: "SW7",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "SW7",
  "VoucherNumber": "42HaveAGoodDay24", field_1_vws_entryline: 50,50}

As you can see, the results are correctly grouped by the VoucherNumber field.

However, my SQL request doesn't return any result. Why?

Edit

I've tried:

```<code>SELECT el.EntryLineDate, el.VoucherNumber, el.label, el.GeneralAccountNumber,
       el.Debit, el.Credit, el.type, el.amount, el.PaymentTypeid, el.EntryNumber,
       c.ThirdId, c.civility, c.name, c.NaturalPerson, c.ThirdLanguage, c.siren,
       c.nic, c.naf, c.AccountNumber
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber
</code>```

but it doesn't work

答:
Try below :</p>

```<code>SELECT TOP 6 c.AccountNumber,field_1_vws_customer,el.GeneralAccountNumber,el.VoucherNumber,
field_1_vws_entryline from vws_entryline el inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber group by c.AccountNumber,field_1_vws_customer,el.GeneralAccountNumber,el.VoucherNumber,
field_1_vws_entryline
</code>```

Body:
SELECT TOP 6 *
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber

I have a table vws_entryline associated to the table vws_customer according to the account number of the customers, as you can see. I would want to group the results by another field, VoucherNumber (which is present in vws_entryline only).

For example, I would want to have these results (it's not JSON format, only an example from my mind that doesn't correspond exactly to a group by... but what I want is actually a SQL group by result):

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "N45PO",
  field_1_vws_entryline: 150.25},

{AccountNumber: "PO200",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "PO200",
  "VoucherNumber": "N45PO", field_1_vws_entryline: 25.75},

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "AZERTY",
  field_1_vws_entryline: 50,50},

{AccountNumber: "SW7",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "SW7",
  "VoucherNumber": "42HaveAGoodDay24", field_1_vws_entryline: 50,50}

As you can see, the results are correctly grouped by the VoucherNumber field.

However, my SQL request doesn't return any result. Why?

Edit

I've tried:

SELECT el.EntryLineDate, el.VoucherNumber, el.label, el.GeneralAccountNumber,
       el.Debit, el.Credit, el.type, el.amount, el.PaymentTypeid, el.EntryNumber,
       c.ThirdId, c.civility, c.name, c.NaturalPerson, c.ThirdLanguage, c.siren,
       c.nic, c.naf, c.AccountNumber
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber

but it doesn't work

Body:
Try below :

SELECT TOP 6 c.AccountNumber,field_1_vws_customer,el.GeneralAccountNumber,el.VoucherNumber,
field_1_vws_entryline from vws_entryline el inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber group by c.AccountNumber,field_1_vws_customer,el.GeneralAccountNumber,el.VoucherNumber,
field_1_vws_entryline