问:
Calling an Async method in a C# library from a VB main method
My application is written in VB.net and for reasons beyond my control, I cannot change the technology. I am trying to use AWS S3 buckets to store files. My application in VB will need to show a window which lists files in a bucket and enable the users to download them.

The listing of files in S3 is done using an Async Task using C#

```<code> public async Task<List<string>> listAllContentsAsync()
        {
            List<string> contents = new List<string>();
            client = new AmazonS3Client(bucketRegion);
            ListObjectsV2Request request = new ListObjectsV2Request
            {
                BucketName = bucketName,
                MaxKeys = 20
            };

            ListObjectsV2Response response;
            do
            {
                response = await client.ListObjectsV2Async(request);

                foreach (S3Object entry in response.S3Objects)
                {
                    String contentName = entry.Key.Split('.')[0];
                    contents.Add(contentName);
                }

                request.ContinuationToken = response.NextContinuationToken;
            } while (response.IsTruncated);

            return contents;
        }
</code>```

I then create a dll for the project in C# and reference it in the VB project. Just for a POC I created a sample VB project which would instantiate an object and call the listAllContentsAsync method to list contents.

I had to change the signature of the Main method because the function I am calling is Async. Here is the updated Main method in VB :

```<code>Async Function Main() As Task(Of Task)
    Dim objcsClass = New CallMeFromVB.ClassInCSharpProject()
    Dim inputChar As ConsoleKeyInfo = Console.ReadKey()
    Dim contents As New List(Of String)

    contents = Await objcsClass.listAllContentsAsync()
    For Each content As String In contents
        Console.Write(content & " ")
    Next

End Function
</code>```

Now, when I try to run my VB project, I get an error saying that there is no Main method in the project. Is there a way I can call an Async method (listAllContentsAsync) from the VB Main method?

答:
Just turn it syncronous:</p>

```<code>Sub Main()
    Dim objcsClass = New CallMeFromVB.ClassInCSharpProject()
    Dim inputChar As ConsoleKeyInfo = Console.ReadKey()
    Dim contents As New List(Of String)
    contents = objcsClass.listAllContentsAsync().GetAwaiter().GetResult()
    For Each content As String In contents
        Console.Write(content & " ")
    Next

End Sub
</code>```

Body:
My application is written in VB.net and for reasons beyond my control, I cannot change the technology. I am trying to use AWS S3 buckets to store files. My application in VB will need to show a window which lists files in a bucket and enable the users to download them.

The listing of files in S3 is done using an Async Task using C#

 public async Task<List<string>> listAllContentsAsync()
        {
            List<string> contents = new List<string>();
            client = new AmazonS3Client(bucketRegion);
            ListObjectsV2Request request = new ListObjectsV2Request
            {
                BucketName = bucketName,
                MaxKeys = 20
            };

            ListObjectsV2Response response;
            do
            {
                response = await client.ListObjectsV2Async(request);

                foreach (S3Object entry in response.S3Objects)
                {
                    String contentName = entry.Key.Split('.')[0];
                    contents.Add(contentName);
                }

                request.ContinuationToken = response.NextContinuationToken;
            } while (response.IsTruncated);

            return contents;
        }

I then create a dll for the project in C# and reference it in the VB project. Just for a POC I created a sample VB project which would instantiate an object and call the listAllContentsAsync method to list contents.

I had to change the signature of the Main method because the function I am calling is Async. Here is the updated Main method in VB :

Async Function Main() As Task(Of Task)
    Dim objcsClass = New CallMeFromVB.ClassInCSharpProject()
    Dim inputChar As ConsoleKeyInfo = Console.ReadKey()
    Dim contents As New List(Of String)

    contents = Await objcsClass.listAllContentsAsync()
    For Each content As String In contents
        Console.Write(content & " ")
    Next

End Function

Now, when I try to run my VB project, I get an error saying that there is no Main method in the project. Is there a way I can call an Async method (listAllContentsAsync) from the VB Main method?

Body:
Just turn it syncronous:

Sub Main()
    Dim objcsClass = New CallMeFromVB.ClassInCSharpProject()
    Dim inputChar As ConsoleKeyInfo = Console.ReadKey()
    Dim contents As New List(Of String)
    contents = objcsClass.listAllContentsAsync().GetAwaiter().GetResult()
    For Each content As String In contents
        Console.Write(content & " ")
    Next

End Sub


来源: stackexchange

问:
Elasticsearch query for distinct values with multiple conditions
I want to perform following in the elasticsearch.

select distinct name, city from students where class = 10 and age = 15;

and it should return all distinct values for name and city. How to perform this?

答:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-collapse. Field collapsing Should be helpful here.

```<code>{
    "query": {
    "bool": {
     "must": [
       {"match":
         {
         "class": 10
         }
       },
       {"match":
         {
         "age": 15
         }
       }
     ]
    }
  },
    "collapse" : {
        "field" : "name.keyword" ,
        "inner_hits" : {
          "name": "by_type",
            "collapse" : {"field" : "city.keyword"}
        }
    },
    "size": 100
}
</code>```

The above query will return one document par name and city after matching with class and age.

ContentLicense: CC BY-SA 4.0

Body:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-collapse. Field collapsing Should be helpful here.

{
    "query": {
    "bool": {
     "must": [
       {"match":
         {
         "class": 10
         }
       },
       {"match":
         {
         "age": 15
         }
       }
     ]
    }
  },
    "collapse" : {
        "field" : "name.keyword" ,
        "inner_hits" : {
          "name": "by_type",
            "collapse" : {"field" : "city.keyword"}
        }
    },
    "size": 100
}

The above query will return one document par name and city after matching with class and age.


问:
Check whether an employee is present on three consecutive days
I have a table called tbl_A with the following schema:

After insert, I have the following data in tbl_A:

Now the question is how to write a query for the following scenario:

Put (1) in front of any employee who was present three days consecutively

Put (0) in front of employee who was not present three days consecutively

The output screen shoot:

I think we should use case statement, but I am not able to check three consecutive days from date. I hope I am helped in this

Thank you

答:
```<code>--Below is My Approch

select Name,
       Case WHen Max_Count>=3 Then 1 else 0 end as Presence
from
(
    Select Name,MAx(Coun) as Max_Count
    from
  (
      select Name, (count(*) over (partition by Name,Ref_Date)) as Coun from
      (
        select  Name,adate + row_number()  over (partition by Name order by Adate  desc) as Ref_Date
        from temp
        where available='Y'
       )
  ) group by Name
);

</code>```

ContentLicense: CC BY-SA 3.0


问:
Taking selenium screenshots and displaying on tkinter gui
I'm trying to take a screenshot of a selenium page and display it on a canvas on my tkinter gui, but for some reason I get the error:

```<code>TypeError: __str__ returned non-string (type bytes)
</code>```

This is the code, thanks for any help in advance

```<code>from tkinter import *
import tkinter as tk
import time
from selenium import webdriver

root = tk.Tk()
root.geometry('700x700')

def picture():
    browser = webdriver.Chrome('C:\\Users\\Downloads\\chromedriver_win324\\chromedriver.exe')
    browser.get('https://google.co.uk')
    fil = browser.get_screenshot_as_png()
    img = PhotoImage(fil)
    canvas = Canvas(root, width=300,height=300)
    canvas.place(x=12.5,y=450)
    canvas.create_image(20,20, image=img)

Button(root, text='Start', command=lambda: picture()).pack()
root.mainloop()
</code>```

答:
The problem is that you're trying to use the data as the first positional parameter to PhotoImage, but the first positional parameter is for the name rather than the image itself.

You need to provide the data as the value for the data attribute:

```<code>img = PhotoImage(data=fil)
</code>```

Body:
I'm trying to take a screenshot of a selenium page and display it on a canvas on my tkinter gui, but for some reason I get the error:

TypeError: __str__ returned non-string (type bytes)

This is the code, thanks for any help in advance

from tkinter import *
import tkinter as tk
import time
from selenium import webdriver

root = tk.Tk()
root.geometry('700x700')

def picture():
    browser = webdriver.Chrome('C:\\Users\\Downloads\\chromedriver_win324\\chromedriver.exe')
    browser.get('https://google.co.uk')
    fil = browser.get_screenshot_as_png()
    img = PhotoImage(fil)
    canvas = Canvas(root, width=300,height=300)
    canvas.place(x=12.5,y=450)
    canvas.create_image(20,20, image=img)

Button(root, text='Start', command=lambda: picture()).pack()
root.mainloop()

Body:
The problem is that you're trying to use the data as the first positional parameter to PhotoImage, but the first positional parameter is for the name rather than the image itself.

You need to provide the data as the value for the data attribute:

img = PhotoImage(data=fil)


问:
All combinations for specific arrangement- python
Id like to compute all the combination for different, specific arrangements and put them in separate list.

The general form of an element is like [[a#, b#], [a#, b#]], where the # can take on numbers from 1-4.

The goal is to make a list of all the possible elements that can result for a certain form/arrangement. like if the form is [[ai, bi], [ai, bi]], where i can be a value from 1-4.
The output for this form would look like this,

```<code>A=[[[a1, b1], [a1, b1]], [[a2, b2], [a2, b2]], [[a3, b3], [a3, b3]], [[a4, b4], [a4, b4]]]
</code>```

Other i form is [[ai, bj], [ai, bj]], where i and j can be value from 1-4 but i≠j, and the outcome would be a list of all the possibilities. Similarly, the form could be [[ai, bj], [ak, bj]], where i, j, k can ba values from 1-4 but i≠j≠k

Im not even sure how to approach this so there isn't any code Ive started on so Im just looking for input or advice on how to work this out.

答:
As your example shows, I don't think you want to use any combination. A formatting may work for you.</p>

```<code>z = []
for i in range(1, 5):
    x = []
    y = []
    x.append('a{}'.format(i))
    x.append('b{}'.format(i))
    y.append(x)
    y.append(x)
    z.append(y)
</code>```

Body:
Id like to compute all the combination for different, specific arrangements and put them in separate list.

The general form of an element is like [[a#, b#], [a#, b#]], where the # can take on numbers from 1-4.

The goal is to make a list of all the possible elements that can result for a certain form/arrangement. like if the form is [[ai, bi], [ai, bi]], where i can be a value from 1-4.
The output for this form would look like this,

A=[[[a1, b1], [a1, b1]], [[a2, b2], [a2, b2]], [[a3, b3], [a3, b3]], [[a4, b4], [a4, b4]]]

Other i form is [[ai, bj], [ai, bj]], where i and j can be value from 1-4 but i≠j, and the outcome would be a list of all the possibilities. Similarly, the form could be [[ai, bj], [ak, bj]], where i, j, k can ba values from 1-4 but i≠j≠k

Im not even sure how to approach this so there isn't any code Ive started on so Im just looking for input or advice on how to work this out.

Body:
As your example shows, I don't think you want to use any combination. A formatting may work for you.

z = []
for i in range(1, 5):
    x = []
    y = []
    x.append('a{}'.format(i))
    x.append('b{}'.format(i))
    y.append(x)
    y.append(x)
    z.append(y)


问:
R - Why I couldn't use text() function for my plot in R?
I created a data.frame from the IMF data about population dynamics by countries (World Economic Outlook):

```<code>   Country Afghanistan Albania Algeria Angola Antigua.and.Barbuda    Argentina Armenia Aruba Australia
1    1980        <NA>   2.672  18.666  8.910               0.068   27.950    <NA>  <NA>    14.802
2    1981        <NA>   2.726  19.246  9.151               0.068   28.450    <NA>  <NA>    15.039
</code>```

Then I created a plot for Argentina:

```<code>plot(mydata$Country, mydata$Argentina)
</code>```

And tried to text the data labels:

```<code>text(x = mydata$Country,y = mydata$Argentina,labels = mydata$Argentina,cex=0.2)
</code>```

But I don't see anything:(

Contrary, I could do it very easy in mtcars:

```<code>plot(a$mpg, a$hp)
text(a$mpg, a$hp, a$hp)
</code>```

What's the problem with my example?

答:
Aziz, in his comment, seems to be right. If you run: </p>

```<code>## This is the data
mydata <- data.frame(Country = 1980:1981, Argentina= c(27.95, 28.54))
## This is the plot
plot(mydata$Country, mydata$Argentina)
## This writes text in the plot
text(x = mydata$Country,y = mydata$Argentina,labels = mydata$Argentina,cex=1)
</code>```

<p>you will indeed see the figures corresponding to Argentina written as text in your plot. </p>

Body:
I created a data.frame from the IMF data about population dynamics by countries (World Economic Outlook):

   Country Afghanistan Albania Algeria Angola Antigua.and.Barbuda    Argentina Armenia Aruba Australia
1    1980        <NA>   2.672  18.666  8.910               0.068   27.950    <NA>  <NA>    14.802
2    1981        <NA>   2.726  19.246  9.151               0.068   28.450    <NA>  <NA>    15.039

Then I created a plot for Argentina:

plot(mydata$Country, mydata$Argentina)

And tried to text the data labels:

text(x = mydata$Country,y = mydata$Argentina,labels = mydata$Argentina,cex=0.2)

But I don't see anything:(

Contrary, I could do it very easy in mtcars:

plot(a$mpg, a$hp)
text(a$mpg, a$hp, a$hp)

What's the problem with my example?

Body:
Aziz, in his comment, seems to be right. If you run:

## This is the data
mydata <- data.frame(Country = 1980:1981, Argentina= c(27.95, 28.54))
## This is the plot
plot(mydata$Country, mydata$Argentina)
## This writes text in the plot
text(x = mydata$Country,y = mydata$Argentina,labels = mydata$Argentina,cex=1)

you will indeed see the figures corresponding to Argentina written as text in your plot.


问:
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>

答:
When it comes to Microsoft, it's the linker that takes care of this during the link phase and the compiler might warn you about unused static functions (file scope).

If you want the linker to remove unused functions, you use the /OPT:REF option.

Title: Do unused functions get optimized out?


问:
python ssl ssl.SSLError: [SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:590)
I get this error when using python 2.7.10 or 2.7.9 but works with python 2.7.6 (haven't tested other versions)

OpenSLL version:

```<code>openssl version -a
OpenSSL 1.0.1f 6 Jan 2014
built on: Thu Jun 11 15:30:15 UTC 2015
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"
</code>```

Python:

```<code>import ssl
print ssl.OPENSSL_VERSION_NUMBER
268439663L
print get_server_certificate(('someInternalIp', 443), ssl_version=ssl.PROTOCOL_SSLv23)
</code>```

StackTrace:

```<code>File "C:\Python27\lib\ssl.py", line 985, in get_server_certificate
  with closing(context.wrap_socket(sock)) as sslsock:
File "C:\Python27\lib\ssl.py", line 352, in wrap_socket
  _context=self)
File "C:\Python27\lib\ssl.py", line 579, in __init__
  self.do_handshake()
File "C:\Python27\lib\ssl.py", line 808, in do_handshake
  self._sslobj.do_handshake()
ssl.SSLError: [SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:590)
</code>```

答:
If you run your requests in debian-based OS or docker image you need to change your SSL config. Debian by default works with SSL v1.2 + at the moment.

You can edit openssl.cnf manually if you want but there's a quicker solution:

```<code>sed -i 's/MinProtocol = TLSv1.2/MinProtocol = TLSv1.0/' /etc/ssl/openssl.cnf
</code>```

It helped in my case, requests to URLs with old SSL now return nice 200 response.

Body:
I get this error when using python 2.7.10 or 2.7.9 but works with python 2.7.6 (haven't tested other versions)

OpenSLL version:

openssl version -a
OpenSSL 1.0.1f 6 Jan 2014
built on: Thu Jun 11 15:30:15 UTC 2015
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

Python:

import ssl
print ssl.OPENSSL_VERSION_NUMBER
268439663L
print get_server_certificate(('someInternalIp', 443), ssl_version=ssl.PROTOCOL_SSLv23)

StackTrace:

File "C:\Python27\lib\ssl.py", line 985, in get_server_certificate
  with closing(context.wrap_socket(sock)) as sslsock:
File "C:\Python27\lib\ssl.py", line 352, in wrap_socket
  _context=self)
File "C:\Python27\lib\ssl.py", line 579, in __init__
  self.do_handshake()
File "C:\Python27\lib\ssl.py", line 808, in do_handshake
  self._sslobj.do_handshake()
ssl.SSLError: [SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:590)

Body:
If you run your requests in debian-based OS or docker image you need to change your SSL config. Debian by default works with SSL v1.2 + at the moment.

You can edit openssl.cnf manually if you want but there's a quicker solution:

sed -i 's/MinProtocol = TLSv1.2/MinProtocol = TLSv1.0/' /etc/ssl/openssl.cnf

It helped in my case, requests to URLs with old SSL now return nice 200 response.


问:
Failed to build when using fragment testing library on AndroidGradlePlugin 3.5.0 and above for Dynamic Feature module
So, I was trying to use fragment testing library androidx.fragment:fragment-testing:1.2.4 in a dynamic feature module. When I used Android Gradle Plugin (AGP) version 3.6.3, it failed to build with an error

```<code>AAPT: error: resource style/FragmentScenarioEmptyFragmentActivityTheme (aka com.example.reminder.test:style/FragmentScenarioEmptyFragmentActivityTheme) not found.
</code>```

And so I was curious and checkout the codelab github and try to upgrade the AGP on that project to 3.6.3 and it can build successfully. But the codelab does not use Dynamic Features.

So I tried to actually run a fragment test in my app module only (excluding the dynamic features module) and yes it can build successfully too.
But I still need to test my fragment in the dynamic features module, so I tried playing with the version one by one and then when I downgrade the AGP version to 3.4.1 it can build successfully.

And I found out that since AGP version 3.5.0 and above, it just failed to build with the same error above.

So,

```<code>AGP 3.5.0 and above:
- Building test on app module only -> works
- Building test on dynamic features -> failed to build

AGP 3.4.2 and below:
- Building test on app module only -> works
- Building test with dynamic features -> works
</code>```

But I still want to use AGP 3.6.0 because I want to utilise viewBinding.

So does anyone know how to resolve the error above for fragment testing with dynamic features module?

答: Upgrading AGP to 4.0.0 and above should resolve the issue.

Body:
So, I was trying to use fragment testing library androidx.fragment:fragment-testing:1.2.4 in a dynamic feature module. When I used Android Gradle Plugin (AGP) version 3.6.3, it failed to build with an error

AAPT: error: resource style/FragmentScenarioEmptyFragmentActivityTheme (aka com.example.reminder.test:style/FragmentScenarioEmptyFragmentActivityTheme) not found.

And so I was curious and checkout the codelab github and try to upgrade the AGP on that project to 3.6.3 and it can build successfully. But the codelab does not use Dynamic Features.

So I tried to actually run a fragment test in my app module only (excluding the dynamic features module) and yes it can build successfully too.
But I still need to test my fragment in the dynamic features module, so I tried playing with the version one by one and then when I downgrade the AGP version to 3.4.1 it can build successfully.

And I found out that since AGP version 3.5.0 and above, it just failed to build with the same error above.

So,

AGP 3.5.0 and above:
- Building test on app module only -> works
- Building test on dynamic features -> failed to build

AGP 3.4.2 and below:
- Building test on app module only -> works
- Building test with dynamic features -> works

But I still want to use AGP 3.6.0 because I want to utilise viewBinding.

So does anyone know how to resolve the error above for fragment testing with dynamic features module?


问:
Can't set width of a List to 0 in landscape
I'm trying to do sliding sidepanel with list. And the problem is that on devices with safearea guide, I can't set width of a list to 0 in landscape orientation.

```<code>struct ContentView: View {
  var body: some View {
    HStack {
        Spacer()
        List {
            Text("1")
            Text("2")
        }
        .frame(width:0)
    }
    .background(Color.green)
  }
}
</code>```

In portrait mode it looks like:

In landscape:

Any idea how to hide the list completely?

On the devices without safe area everything works well without issues.

The workaround, I found, is to add e.g.

```<code>Rectangle().frame(width: 0)
</code>```

to the same HStack, then the list is not shown at all in all conditions, but this looks weird.

Update from Jun 10th:
I've been discussing this issue with Apple DTS team, and they confirmed, that I'm observing a system bug (now reported to the engineering team via FB7729714).
From other side, they pointed me that setting width of a view would cause relayout of child views, and thus setting to 0 is even more complicated thing. Therefore recommended is to work with position and offset for such cases as sliding views.

答:
I'm not sure how exactly your code looks as you didn't provide more information, but here is how you can implement a sliding menu in SwiftUI without additional hacks.

You show/hide the side panel using GeometryReader, offset and animating transition:

```<code>struct ContentView: View {
    @State var showMenu = false

    var body: some View {
        NavigationView {
            GeometryReader { geometry in
                ZStack(alignment: .leading) {
                    MainView(showMenu: self.$showMenu)
                        .frame(width: geometry.size.width, height: geometry.size.height)
                        .offset(x: self.showMenu ? geometry.size.width : 0)
                        .disabled(self.showMenu ? true : false)
                    if self.showMenu {
                        MenuView()
                            .frame(width: geometry.size.width)
                            .transition(.move(edge: .leading))
                    }
                }
            }
            .background(Color.red)
            .navigationBarTitle("Side Menu", displayMode: .inline)
            .navigationBarItems(leading: (
                Button(action: {
                    withAnimation {
                        self.showMenu.toggle()
                    }
                    }) {
                    Image(systemName: "line.horizontal.3")
                        .imageScale(.large)
                }
                ))
        }
    }
}
</code>```

```<code>struct MainView: View {
    @Binding var showMenu: Bool

    var body: some View {
        Button(action: {
            withAnimation {
                self.showMenu = true
            }
        }) {
            Text("Show Menu")
        }
    }
}
</code>```

```<code>struct MenuView: View {
    var body: some View {
        List {
            Text("Item 1")
            Text("Item 2")
            Spacer()
        }
        .background(Color.green)
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}
</code>```

The full explanation of this code is in this tutorial: How To Create A Side Menu In SwiftUI.

Also you can try adding this to your Views to fill the whole screen:

```<code>.edgesIgnoringSafeArea()
</code>```

Tested in Xcode 11.5. A slider disappears completely from the screen - I hope it's what you wanted to achieve.

Body:
I'm trying to do sliding sidepanel with list. And the problem is that on devices with safearea guide, I can't set width of a list to 0 in landscape orientation.

struct ContentView: View {
  var body: some View {
    HStack {
        Spacer()
        List {
            Text("1")
            Text("2")
        }
        .frame(width:0)
    }
    .background(Color.green)
  }
}

In portrait mode it looks like:

In landscape:

Any idea how to hide the list completely?

On the devices without safe area everything works well without issues.

The workaround, I found, is to add e.g.

Rectangle().frame(width: 0)

to the same HStack, then the list is not shown at all in all conditions, but this looks weird.

Update from Jun 10th:
I've been discussing this issue with Apple DTS team, and they confirmed, that I'm observing a system bug (now reported to the engineering team via FB7729714).
From other side, they pointed me that setting width of a view would cause relayout of child views, and thus setting to 0 is even more complicated thing. Therefore recommended is to work with position and offset for such cases as sliding views.

Body:
I'm not sure how exactly your code looks as you didn't provide more information, but here is how you can implement a sliding menu in SwiftUI without additional hacks.

You show/hide the side panel using GeometryReader, offset and animating transition:

struct ContentView: View {
    @State var showMenu = false

    var body: some View {
        NavigationView {
            GeometryReader { geometry in
                ZStack(alignment: .leading) {
                    MainView(showMenu: self.$showMenu)
                        .frame(width: geometry.size.width, height: geometry.size.height)
                        .offset(x: self.showMenu ? geometry.size.width : 0)
                        .disabled(self.showMenu ? true : false)
                    if self.showMenu {
                        MenuView()
                            .frame(width: geometry.size.width)
                            .transition(.move(edge: .leading))
                    }
                }
            }
            .background(Color.red)
            .navigationBarTitle("Side Menu", displayMode: .inline)
            .navigationBarItems(leading: (
                Button(action: {
                    withAnimation {
                        self.showMenu.toggle()
                    }
                    }) {
                    Image(systemName: "line.horizontal.3")
                        .imageScale(.large)
                }
                ))
        }
    }
}

struct MainView: View {
    @Binding var showMenu: Bool

    var body: some View {
        Button(action: {
            withAnimation {
                self.showMenu = true
            }
        }) {
            Text("Show Menu")
        }
    }
}

struct MenuView: View {
    var body: some View {
        List {
            Text("Item 1")
            Text("Item 2")
            Spacer()
        }
        .background(Color.green)
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}

The full explanation of this code is in this tutorial: How To Create A Side Menu In SwiftUI.

Also you can try adding this to your Views to fill the whole screen:

.edgesIgnoringSafeArea()

Tested in Xcode 11.5. A slider disappears completely from the screen - I hope it's what you wanted to achieve.


问:
How to convert 'binary string' to normal string in Python3?
For example, I have a string like this(return value of subprocess.check_output):

```<code>>>> b'a string'
b'a string'
</code>```

Whatever I did to it, it is always printed with the annoying b' before the string:

```<code>>>> print(b'a string')
b'a string'
>>> print(str(b'a string'))
b'a string'
</code>```

Does anyone have any ideas about how to use it as a normal string or convert it into a normal string?

答: Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

Body:
For example, I have a string like this(return value of subprocess.check_output):

>>> b'a string'
b'a string'

Whatever I did to it, it is always printed with the annoying b' before the string:

>>> print(b'a string')
b'a string'
>>> print(str(b'a string'))
b'a string'

Does anyone have any ideas about how to use it as a normal string or convert it into a normal string?


问:
Count based on merge column
I have a table with the below structure.

up_cnt_1 corresponds to dt_1 and up_cnt_2 corresponds to dt_2 column . I want to aggregate up_cnt_1 grouped by dt_1 and up_cnt_2 grouped by dt_2 but the final table should have a single column for these dates , although counts will be separately mentioned. The merged date column basically has the unique values of dt_1 and dt_2 and for any date if the value of corresponding count is missing it is shown as 0.

The expected output is as below:

I am using Teradata 16 as RDBMS

答:
One option uses union all and aggregation:

```<code>select dt_merge, sum(up_cnt_1) up_cnt_1, sum(up_cnt_2) up_cnt_2
from (
    select dt_1 dt_merge, up_cnt_1, 0 up_cnt_2 from mytable
    union all
    select dt_2, 0, up_cnt_2 from mytable
) t
group by dt_merge
</code>```

Title: Count based on merge column

Body:
One option uses union all and aggregation:

select dt_merge, sum(up_cnt_1) up_cnt_1, sum(up_cnt_2) up_cnt_2
from (
    select dt_1 dt_merge, up_cnt_1, 0 up_cnt_2 from mytable
    union all
    select dt_2, 0, up_cnt_2 from mytable
) t
group by dt_merge


问:
How to check that the to which table the view is currently pointing to in oracle?
I have a situation like, I have two tables having same structure. I have a view which points to one of the table. In my store procedure I have to check first which table the view points to and accordingly update the other table and then finally update the view to point to the updated table.
How to check that which table the view is currently pointing at??</p>

答:
```<code>select referenced_name
from all_dependencies
where name = 'MYVIEW'
and owner = 'MYSCHEMA'
and referenced_type = 'TABLE';
</code>```


问:
Call Child Method from Parent with react-native
I know that this is a pretty common question but some answers I found on the internet are deprecated.
How do you call a method of a Child Component from the Parent Component in 2020?

My actual code is something like this but it's not working

Child:

```<code>export default class CustomComp extends React.Component{
  exampleMethod = () => {
    console.log('pressed');
  };

  render(){
    return (
      ...
    );
  }
}
</code>```

Parent:

```<code>export default class App extends React.Component{
  child = CustomComp;
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={this.child.exampleMethod} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}
</code>```

答:
You have to call the function as a callback function.

```<code>onPress={() => this.child.exampleMethod()}
</code>```

Plus, I think child = CustomComp has no effect since ref={child => {this.child = child}} is NOT affected by child = CustomComp.

So, your Parent js file should be as follows.

```<code>export default class App extends React.Component{
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={() => this.child.exampleMethod()} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}
</code>```

Body:
I know that this is a pretty common question but some answers I found on the internet are deprecated.
How do you call a method of a Child Component from the Parent Component in 2020?

My actual code is something like this but it's not working

Child:

export default class CustomComp extends React.Component{
  exampleMethod = () => {
    console.log('pressed');
  };

  render(){
    return (
      ...
    );
  }
}

Parent:

export default class App extends React.Component{
  child = CustomComp;
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={this.child.exampleMethod} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}

Body:
You have to call the function as a callback function.

onPress={() => this.child.exampleMethod()}

Plus, I think child = CustomComp has no effect since ref={child => {this.child = child}} is NOT affected by child = CustomComp.

So, your Parent js file should be as follows.

export default class App extends React.Component{
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={() => this.child.exampleMethod()} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}


问:
Why does typing variable length Tuple require ellipses but List does not?
According to the docs:

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

So therefore, the annotation Tuple[int] specifies a tuple containing a single integer; yet List[int] implies variable length.

Why must ... be used with Tuple[int, ...] and not with List[int] if both can be homeo/hetero-geneous?

答:
A tuple is typically used for a small heterogenous set of values of fixed size. Therefore the type hint takes individual arguments denoting the type of each value, e.g. Tuple[str, int, list]. A homogeneous tuple is really a special case, and the ... notation is a shorthand for it.

A list is typically a homogenous sequence of undefined length. Hence its type hint only takes one argument.


问:
Angular Toggle only the element click on
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

```<code>show = false;

toggle() {
    this.show = !this.show;
}
</code>```

app.component.html

```<code><div>
    <div *ngIf="show">
      <div>One</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Two</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Three</div>
    </div>
    <button type="button" toggle()"></button>
</div>
</code>```

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

答:
You could also use [ngSwitch] to solve this problem. (See stackblitz below)

app.component.html

Tab1

Tab2

Tab3

<ng-container [ngSwitch]="tab">

Tab 1

Tab 2

Tab 3

</ng-container>
```
<h3>app.component.ts</h3>
<pre class="lang-js prettyprint-override"><code>export class AppComponent  {
  public tab: string = "tab1";

  public showTab(tab: string) {
    this.tab = tab;
  }
}
</code>```

https://stackblitz.com/edit/angular-ivy-snj6zw

https://angular.io/api/common/NgSwitch

Body:
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

show = false;

toggle() {
    this.show = !this.show;
}

app.component.html

One

    <button type="button" toggle()"></button>

Two

    <button type="button" toggle()"></button>

Three

    <button type="button" toggle()"></button>

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

Body:
You could also use [ngSwitch] to solve this problem. (See stackblitz below)

app.component.html

<nav>
  <ul style="cursor: pointer;">
    <li (click)="showTab('tab1')"><a href="#">Tab1</a></li>
    <li (click)="showTab('tab2')"><a href="#">Tab2</a></li>
    <li (click)="showTab('tab3')"><a href="#">Tab3</a></li>
  </ul>
</nav>
<ng-container [ngSwitch]="tab">
  <div *ngSwitchCase="'tab1'">
    <h1>Tab 1</h1>
  </div>
  <div *ngSwitchCase="'tab2'">
    <h1>Tab 2</h1>
  </div>
  <div *ngSwitchCase="'tab3'">
    <h1>Tab 3</h1>
  </div>
</ng-container>

app.component.ts

export class AppComponent  {
  public tab: string = "tab1";

  public showTab(tab: string) {
    this.tab = tab;
  }
}

https://stackblitz.com/edit/angular-ivy-snj6zw

https://angular.io/api/common/NgSwitch


问:
Initialization of a struct instance data member in constructor?
I have a c++ class which as a private data member has a struct defined:

```<code>Class example {

...

private:
   struct Impl;
   Impl& structure_;
};
</code>```

Assuming that the struct Impl is defined as follows:

```<code>struct example::Impl{
    int m1;
    int m2;
    int m3;
};
</code>```

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

```<code>example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}
</code>```

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks

答:
If you're going for the pImpl idiom, use a pointer, and allocate + deallocate it in the class, then assign to it inside the ctor.

```<code>Class example {

...

private:
   struct Impl;
   Impl* pimpl_
};

example::example() :
     pimpl_(new Impl())
{
  pimpl_->m1 = 00;
  pimpl_->m2 = 00;
  pimpl_->m3 = 00;
...
}

example::~example(){
  delete pimpl_;
}
</code>```

If you really want a reference, dereference the returned pointer from new and take its address again when deleting it:

```<code>example::example() : impl_(*new Impl(), ...

example::~example(){ delete &impl_; }
</code>```

Body:
I have a c++ class which as a private data member has a struct defined:

Class example {

...

private:
   struct Impl;
   Impl& structure_;
};

Assuming that the struct Impl is defined as follows:

struct example::Impl{
    int m1;
    int m2;
    int m3;
};

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks

Body:
If you're going for the pImpl idiom, use a pointer, and allocate + deallocate it in the class, then assign to it inside the ctor.

Class example {

...

private:
   struct Impl;
   Impl* pimpl_
};

example::example() :
     pimpl_(new Impl())
{
  pimpl_->m1 = 00;
  pimpl_->m2 = 00;
  pimpl_->m3 = 00;
...
}

example::~example(){
  delete pimpl_;
}

If you really want a reference, dereference the returned pointer from new and take its address again when deleting it:

example::example() : impl_(*new Impl(), ...

example::~example(){ delete &impl_; }


问:
TypeError: __init__() got multiple values for argument 'executable_path' using Selenium through Python
Error is:

```<code>TypeError: __init__() got multiple values for argument 'executable_path'
</code>```

I can't see what is causing this!

chrome_options = Options() #line 8
chrome_options.add_argument('--headless') #line 9
chrome_options.add_argument('--no-sandbox') #line 10
chrome_options.add_argument('--disable-gpu') #line 11
browser=webdriver.Chrome(chrome_options,executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe') #This is line 12
```

<p>This is the error</p>

```Traceback (most recent call last):
File "main.py", line 12, in <module>
browser = webdriver.Chrome(chrome_options, executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe')
TypeError: __init__() got multiple values for argument 'executable_path'
```

答:
executable_path is the first positional parameter defined by Chrome, so that's what the first positional argument chrome_options is bound to. Then you try to set the same parameter again, this time with a keyword argument. Specify both using keyword arguments:

```<code>browser = webdriver.Chrome(options=chrome_options, executable_path='...')
</code>```

or specify the path first:

```<code>browser = webdriver.Chrome(r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe', options=chrome_options)
</code>```

I still used a keyword argument for the options because options is the third positional parameter; port is the second.

Here's the definition in question:

```<code>class WebDriver(ChromiumDriver):
    """
    Controls the ChromeDriver and allows you to drive the browser.
    You will need to download the ChromeDriver executable from
    http://chromedriver.storage.googleapis.com/index.html
    """

    def __init__(self, executable_path="chromedriver", port=DEFAULT_PORT,
                 options=None, service_args=None,
                 desired_capabilities=None, service_log_path=DEFAULT_SERVICE_LOG_PATH,
                 chrome_options=None, service=None, keep_alive=True):
        ...
</code>```

Body:
Error is:

TypeError: __init__() got multiple values for argument 'executable_path'

I can't see what is causing this!

chrome_options = Options() #line 8
chrome_options.add_argument('--headless') #line 9
chrome_options.add_argument('--no-sandbox') #line 10
chrome_options.add_argument('--disable-gpu') #line 11
browser=webdriver.Chrome(chrome_options,executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe') #This is line 12

This is the error

Traceback (most recent call last):
File "main.py", line 12, in <module>
browser = webdriver.Chrome(chrome_options, executable_path=r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe')
TypeError: __init__() got multiple values for argument 'executable_path'

Body:
executable_path is the first positional parameter defined by Chrome, so that's what the first positional argument chrome_options is bound to. Then you try to set the same parameter again, this time with a keyword argument. Specify both using keyword arguments:

browser = webdriver.Chrome(options=chrome_options, executable_path='...')

or specify the path first:

browser = webdriver.Chrome(r'C:/Users/Lenovo/AppData/Roaming/Python/Python37/chromedriver.exe', options=chrome_options)

I still used a keyword argument for the options because options is the third positional parameter; port is the second.

Here's the definition in question:

class WebDriver(ChromiumDriver):
    """
    Controls the ChromeDriver and allows you to drive the browser.
    You will need to download the ChromeDriver executable from
    http://chromedriver.storage.googleapis.com/index.html
    """

    def __init__(self, executable_path="chromedriver", port=DEFAULT_PORT,
                 options=None, service_args=None,
                 desired_capabilities=None, service_log_path=DEFAULT_SERVICE_LOG_PATH,
                 chrome_options=None, service=None, keep_alive=True):
        ...


问:
Apply the same random shuffle on multiple containers
I am writing a program where a Manager-class handles different containers.
Every container is the same size with the same contents and needs to be (randomly) shuffled the same way.
(FYI, The program will later apply different operations on each container)

What I want to achieve:
Randomly sort each container, but all containers has to be sorted the same way, without copying a container. I do not want to copy because the contents of each container is not just integers and would thus be very expensive.

Therefore, I do not seek a solution like the one that follows:

```<code>void ContainerMgr::Shuffle()
{
    std::random_shuffle(m_tmp.begin(), m_tmp.end());

    for (auto &subContainer : m_allContainers)
        subContainer = m_tmp;
}
</code>```

My question:
Does C++ (perhaps STL) provide a way to randomly shuffle, let's say 5, different (equally sized) containers in the same way?

Thanks in advance!

答:
Both std::random_shuffle before it ws removed and it's replacement, std::shuffle, support passing to them a pseudo-random number generator.  You should be able to leverage that to pass "the same" generator to each invocation to of the shuffler so that it shuffles in the same manner.

I say should here because the implementation of the shuffling algorithms is pretty vauge and all we really have is [alg.random.shuffle]/5 which has

Remarks: To the extent that the implementation of this function makes use of random numbers, the object referenced by g shall serve as the implementation's source of randomness.

I believe that remark means that two identical PRNG's pass to two different invocations should produce the same result since they would have the same randomness

That would give you code like

```<code>void ContainerMgr::Shuffle()
{
    std::random_device rd;
    std::mt19937 g(rd()); // set a random seed

    for (auto &subContainer : m_allContainers)
    {
        auto g_copy = g;
        std::shuffle(subContainer.begin(), subContainer.end(), g_copy);
}
</code>```

Body:
I am writing a program where a Manager-class handles different containers.
Every container is the same size with the same contents and needs to be (randomly) shuffled the same way.
(FYI, The program will later apply different operations on each container)

What I want to achieve:
Randomly sort each container, but all containers has to be sorted the same way, without copying a container. I do not want to copy because the contents of each container is not just integers and would thus be very expensive.

Therefore, I do not seek a solution like the one that follows:

void ContainerMgr::Shuffle()
{
    std::random_shuffle(m_tmp.begin(), m_tmp.end());

    for (auto &subContainer : m_allContainers)
        subContainer = m_tmp;
}

My question:
Does C++ (perhaps STL) provide a way to randomly shuffle, let's say 5, different (equally sized) containers in the same way?

Thanks in advance!

Body:
Both std::random_shuffle before it ws removed and it's replacement, std::shuffle, support passing to them a pseudo-random number generator.  You should be able to leverage that to pass "the same" generator to each invocation to of the shuffler so that it shuffles in the same manner.

I say should here because the implementation of the shuffling algorithms is pretty vauge and all we really have is [alg.random.shuffle]/5 which has

Remarks: To the extent that the implementation of this function makes use of random numbers, the object referenced by g shall serve as the implementation's source of randomness.

I believe that remark means that two identical PRNG's pass to two different invocations should produce the same result since they would have the same randomness

That would give you code like

void ContainerMgr::Shuffle()
{
    std::random_device rd;
    std::mt19937 g(rd()); // set a random seed

    for (auto &subContainer : m_allContainers)
    {
        auto g_copy = g;
        std::shuffle(subContainer.begin(), subContainer.end(), g_copy);
}


问:
How to set tkinter Entry Border Radius
This is my first question to here. I don't know how to set Border Radius for Tkinter Entry, Thanks for your Help!</p>

答: There is no option to set a border radius on the tkinter or ttk Entry widgets, or any of the other widgets in those modules. Tkinter doesn't support the concept of a border radius.

Title: How to set tkinter Entry Border Radius


问:
Is It Okay to use helpers in views?
Simple question about best-practice. I'm using Kohana... is it okay to use helpers in views? For example, to use URL::site(). I could pass it from controller, you know. I assume it's okay, because there are helpers like HTML that is meant to be used in views, right?

答:
The way you're currently doing it is ok, altough the whole practice of having any logics in views is questionable, but it's how Kohana is currently recommending.

When you get to use ViewModel pattern (with Kostache?), you'll separate all logics from templates. Until then, it's ok to use methods that don't do anything that should be done in the controller / model (echo, conditions and loops are "considered allowed").

Title: Is It Okay to use helpers in views?


问:
How to update data in a joined table from a default view? - Ruby on Rails
I am a beginner Ruby on Rails student, trying to fix up this mess I found myself in :D I'm trying to build a web app that allows registered users to buy bus tickets, while unregistered users can only browse through the ticket list. There are 3 tables User (created with devise), Ticket(a table that contains tickets...I seeded sample data inside) and Bought (joined table from User and Ticket since the link is many-to-many. Database schema is the following :

```<code>  create_table "boughts", force: :cascade do |t|
    t.integer "user_id", null: false
    t.integer "ticket_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["ticket_id"], name: "index_boughts_on_ticket_id"
    t.index ["user_id"], name: "index_boughts_on_user_id"
  end

  create_table "tickets", force: :cascade do |t|
    t.string "bus"
    t.datetime "time"
    t.integer "quantity"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "price"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

  add_foreign_key "boughts", "tickets"
  add_foreign_key "boughts", "users"
end
</code>```

Now, when a registered/logged-in user clicks "Buy" button (its a fake buy), I want to insert a row into table "Boughts" with this particular user's ID, and with the ID of the ticket he clicked "Buy" next to. The purpose of this is that this user can later view the tickets he has bought on his "bought tickets view", or something of the sort.

Index/Home view (pages.html.erb)

```<code>    <%= link_to 'Sign out',destroy_user_session_path, method: :delete %>

    <table>
    <thead>
        <tr>
            <td>Bus</td>
            <td>Time</td>
            <td>Quantity</td>
            <td>Price</td>
        </tr>
    </thead>

    <tbody>
        <% @tickets.each do |ticket| %>
        <tr>
            <td><%= ticket.bus %></td>
            <td><%= ticket.time %></td>
            <td><%= ticket.quantity %></td>
            <td><%= ticket.price %></td>
            <td>
                <%= button_to 'Buy', create_path, method: :post %>
            </td>
        </tr>
        <% end %>
    </tbody>
</table>
</code>```

Pages controller

```<code>class PagesController < ApplicationController
  def home
    @tickets = Ticket.all

  end
  def create
    @boughts = Bought.new(bought_params)

        if bought.save
            redirect_to :root
        else
            flash[:errors] = bought.errors.full_messages
            redirect_back fallback_location: root_path
        end
  end
  private
    def bought_params
        params.require(:bought).permit(:user_id, :ticket_id)
    end
end
</code>```

Routes

```<code>Rails.application.routes.draw do
  resources :tickets
  resources :boughts
  devise_for :users
  root to: "pages#home"
  post '/create', to: 'pages#create', as: 'create'
end
</code>```

Should I update the boughts table from a "boughts" controller, or can I do it from the pages_controller (the controller for the main view/index homepage). This specific code doesn't work, the error is ("param is missing or the value is empty: bought"). The goal is to fill the boughts table with user-bought tickets and then display them on that users's specific profile page.

答:
You're correct in thinking this isn't entirely best practice.

You should be submitting directly to the boughts_controller because that's the only thing you're trying to create/update from this single button click.

The other problem is you're not sending any parameters to the create method.

Assuming you generated the boughts_controller with a scaffold command

```<code><%= button_to 'Buy', boughts_path(bought: {user_id: current_user.id, ticket_id: ticket }) %>
</code>```

method: :post is not needed, this is the default for button_to, you can see the documentation on this here: https://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

Then from the boughts_controller, after the "tracking" record is created, you should redirect to the path where the user can actually buy something.

Body:
I am a beginner Ruby on Rails student, trying to fix up this mess I found myself in :D I'm trying to build a web app that allows registered users to buy bus tickets, while unregistered users can only browse through the ticket list. There are 3 tables User (created with devise), Ticket(a table that contains tickets...I seeded sample data inside) and Bought (joined table from User and Ticket since the link is many-to-many. Database schema is the following :

  create_table "boughts", force: :cascade do |t|
    t.integer "user_id", null: false
    t.integer "ticket_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["ticket_id"], name: "index_boughts_on_ticket_id"
    t.index ["user_id"], name: "index_boughts_on_user_id"
  end

  create_table "tickets", force: :cascade do |t|
    t.string "bus"
    t.datetime "time"
    t.integer "quantity"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "price"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

  add_foreign_key "boughts", "tickets"
  add_foreign_key "boughts", "users"
end

Now, when a registered/logged-in user clicks "Buy" button (its a fake buy), I want to insert a row into table "Boughts" with this particular user's ID, and with the ID of the ticket he clicked "Buy" next to. The purpose of this is that this user can later view the tickets he has bought on his "bought tickets view", or something of the sort.

Index/Home view (pages.html.erb)

    <%= link_to 'Sign out',destroy_user_session_path, method: :delete %>

            Bus
            Time
            Quantity
            Price

        <% @tickets.each do |ticket| %>

            <%= ticket.bus %>
            <%= ticket.time %>
            <%= ticket.quantity %>
            <%= ticket.price %>

                <%= button_to 'Buy', create_path, method: :post %>

        <% end %>

Pages controller

class PagesController < ApplicationController
  def home
    @tickets = Ticket.all

  end
  def create
    @boughts = Bought.new(bought_params)

        if bought.save
            redirect_to :root
        else
            flash[:errors] = bought.errors.full_messages
            redirect_back fallback_location: root_path
        end
  end
  private
    def bought_params
        params.require(:bought).permit(:user_id, :ticket_id)
    end
end

Routes

Rails.application.routes.draw do
  resources :tickets
  resources :boughts
  devise_for :users
  root to: "pages#home"
  post '/create', to: 'pages#create', as: 'create'
end

Should I update the boughts table from a "boughts" controller, or can I do it from the pages_controller (the controller for the main view/index homepage). This specific code doesn't work, the error is ("param is missing or the value is empty: bought"). The goal is to fill the boughts table with user-bought tickets and then display them on that users's specific profile page.

Body:
You're correct in thinking this isn't entirely best practice.

You should be submitting directly to the boughts_controller because that's the only thing you're trying to create/update from this single button click.

The other problem is you're not sending any parameters to the create method.

Assuming you generated the boughts_controller with a scaffold command

<%= button_to 'Buy', boughts_path(bought: {user_id: current_user.id, ticket_id: ticket }) %>

method: :post is not needed, this is the default for button_to, you can see the documentation on this here: https://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

Then from the boughts_controller, after the "tracking" record is created, you should redirect to the path where the user can actually buy something.


问:
jQuery Validation: rules do not apply to elements created dynamically from json
In my Laravel App I have a form that may contain dynamic fields. On "Add Contact" button click group of fields is added from template. Some of the fields have to be validated so I added rules dynamically for each of this fields with .rules() method. When I create a new entity that these dynamic fields should be part of it`s working fine for me:

When I edit an entity, I create these field groups from the json string that I get from the controller. Fields with values are created, but for some reason, the rules do not apply to these dynamically created fields. When I try to apply a rule to such a field, I get an error:

```<code>Uncaught TypeError: Cannot read property 'settings' of undefined
</code>```

I found out that this happens when I add rules to dynamic fields:

```<code>let firstName = $('#first-name-' + elementNumber);
let jobTitle = $('#job-title-' + elementNumber);
let contactEmail = $('#contact-email-' + elementNumber);

firstName.rules("add", {
    required: true
});

jobTitle.rules("add", {
    required: true
});

contactEmail.rules("add", {
    required: true,
    email: true
});
</code>```

My code:

```<code>let buildingForm = $('#building_form');
let addContactButton = $('#add_contact');
let contactsContainer = $('#contacts_container');
var elementNumber = 1;

let model = "{{ $model->building_id ?? '' }}"

if (model) {
    let buildingContacts = '{!! $buildingContacts ?? "" !!}'

    if (buildingContacts) {
        buildingContacts = JSON.parse(buildingContacts)

        $.each(buildingContacts, function (index, value) {
            addContact(value)
            elementNumber++
        });
    }
}

addContactButton.on('click', function () {
    addContact()
    elementNumber++
});

buildingForm.validate({
    ignore: ""
});

function addContact(value = null) {
    let contactLayout = getContactLayout(elementNumber, value);
    contactsContainer.prepend(contactLayout);

    let firstName = $('#first-name-' + elementNumber);
    let jobTitle = $('#job-title-' + elementNumber);
    let contactEmail = $('#contact-email-' + elementNumber);

    firstName.rules("add", {
        required: true
    });

    jobTitle.rules("add", {
        required: true
    });

    contactEmail.rules("add", {
        required: true,
        email: true
    });

    $('#delete-contact-button-' + elementNumber).on('click', function (e) {
        $.confirm({
            title: 'Confirm action',
            content: 'Are you sure you want to delete Contact?',
            buttons: {
                confirm: function () {
                    deleteContact(e.target.id);
                },
                cancel: function () {
                    $.alert('Canceled');
                },
            }
        });
    });
}

function deleteContact(buttonId) {
    let buttonOneContactContainer = $('#' + buttonId).closest('div.one-contact-container');
    buttonOneContactContainer.remove();

}

function getContactLayout(elementNumber, value = null) {
    return `
        <div class="p-t-10 p-b-10 p-l-10 p-r-10 m-t-10 border one-contact-container" id="one-contact-container-${elementNumber}">
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group row">
                        <label for="first-name-${elementNumber}" class="col-md-4 label-right">First Name <span class="required">*</span></label>
                        <div class="col-md-8">
                            <input name="contacts[first_name][${elementNumber}]" id="first-name-${elementNumber}" type="text" value="${value ? value.first_name : ''}" class="form-control first-name-input">
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group row">
                        <label for="last-name-${elementNumber}" class="col-md-4 label-right">Last Name</label>
                        <div class="col-md-8">
                            <input name="contacts[last_name][${elementNumber}]" id="last-name-${elementNumber}" type="text" value="${value ? value.last_name : ''}" class="form-control">
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group row">
                        <label for="job-title-${elementNumber}" class="col-md-4 label-right">Job Title <span class="required">*</span></label>
                        <div class="col-md-8">
                            <input name="contacts[job_title][${elementNumber}]" id="job-title-${elementNumber}" type="text" value="${value ? value.job_title : ''}" class="form-control job-title-input">
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group row">
                        <label for="contact-email-${elementNumber}" class="col-md-4 label-right">Email <span class="required">*</span></label>
                        <div class="col-md-8">
                            <input name="contacts[contact_email][${elementNumber}]" id="contact-email-${elementNumber}" type="text" value="${value ? value.email : ''}" class="form-control email-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group row">
                        <label for="office-phone-${elementNumber}" class="col-md-4 label-right">Office Phone</label>
                        <div class="col-md-8">
                            <input name="contacts[office_phone][${elementNumber}]" id="office-phone-${elementNumber}" type="text" value="${value ? value.office_phone : ''}" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group row">
                        <label for="mobile-phone-${elementNumber}" class="col-md-4 label-right">Mobile Phone</label>
                        <div class="col-md-8">
                            <input name="contacts[mobile_phone][${elementNumber}]" id="mobile-phone-${elementNumber}" type="text" value="${value ? value.mobile_phone : ''}" class="form-control">
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="form-group row">
                        <label for="contact-notes-${elementNumber}" class="col-md-2 label-right">Notes</label>
                        <div class="col-md-10">
                            <textarea name="contacts[contact_notes][${elementNumber}]" id="contact-notes-${elementNumber}" class="form-control">${value ? value.notes : ''}</textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12 test-right">
                    <span class="btn-danger btn pull-right delete-contact" id="delete-contact-button-${elementNumber}">Delete contact</span>
                </div>
            </div>
        </div>
    `;
}
</code>```

So, creating new fields and generating existing ones from json strings fulfills the same function.

JSON example:

```<code>[{
    "building_contact_id": 781,
    "building_id": 76516,
    "job_title": "Officer",
    "first_name": "John",
    "last_name": "",
    "mobile_phone": "",
    "office_phone": "",
    "email": "john.doe@mail.com",
    "notes": "",
    "created_at": "2020-06-02T13:42:32.000000Z",
    "updated_at": "2020-06-02T13:42:32.000000Z"
}]
</code>```

答:
Needed to be wrapped in a timeout:</p>

```<code>setTimeout(function () {
    if (firstName.length) {
        firstName.rules("add", {
            required: true
        });
    }

    if (jobTitle.length) {
        jobTitle.rules("add", {
            required: true
        });
    }

    if (contactEmail.length) {
        contactEmail.rules("add", {
            required: true
        });
    }
}, 100)
</code>```

Body:
In my Laravel App I have a form that may contain dynamic fields. On "Add Contact" button click group of fields is added from template. Some of the fields have to be validated so I added rules dynamically for each of this fields with .rules() method. When I create a new entity that these dynamic fields should be part of it`s working fine for me:

When I edit an entity, I create these field groups from the json string that I get from the controller. Fields with values are created, but for some reason, the rules do not apply to these dynamically created fields. When I try to apply a rule to such a field, I get an error:

Uncaught TypeError: Cannot read property 'settings' of undefined

I found out that this happens when I add rules to dynamic fields:

let firstName = $('#first-name-' + elementNumber);
let jobTitle = $('#job-title-' + elementNumber);
let contactEmail = $('#contact-email-' + elementNumber);

firstName.rules("add", {
    required: true
});

jobTitle.rules("add", {
    required: true
});

contactEmail.rules("add", {
    required: true,
    email: true
});

My code:

let buildingForm = $('#building_form');
let addContactButton = $('#add_contact');
let contactsContainer = $('#contacts_container');
var elementNumber = 1;

let model = "{{ $model->building_id ?? '' }}"

if (model) {
    let buildingContacts = '{!! $buildingContacts ?? "" !!}'

    if (buildingContacts) {
        buildingContacts = JSON.parse(buildingContacts)

        $.each(buildingContacts, function (index, value) {
            addContact(value)
            elementNumber++
        });
    }
}

addContactButton.on('click', function () {
    addContact()
    elementNumber++
});

buildingForm.validate({
    ignore: ""
});

function addContact(value = null) {
    let contactLayout = getContactLayout(elementNumber, value);
    contactsContainer.prepend(contactLayout);

    let firstName = $('#first-name-' + elementNumber);
    let jobTitle = $('#job-title-' + elementNumber);
    let contactEmail = $('#contact-email-' + elementNumber);

    firstName.rules("add", {
        required: true
    });

    jobTitle.rules("add", {
        required: true
    });

    contactEmail.rules("add", {
        required: true,
        email: true
    });

    $('#delete-contact-button-' + elementNumber).on('click', function (e) {
        $.confirm({
            title: 'Confirm action',
            content: 'Are you sure you want to delete Contact?',
            buttons: {
                confirm: function () {
                    deleteContact(e.target.id);
                },
                cancel: function () {
                    $.alert('Canceled');
                },
            }
        });
    });
}

function deleteContact(buttonId) {
    let buttonOneContactContainer = $('#' + buttonId).closest('div.one-contact-container');
    buttonOneContactContainer.remove();

}

function getContactLayout(elementNumber, value = null) {
    return `

                        First Name *

                            <input name="contacts[first_name][${elementNumber}]" id="first-name-${elementNumber}" type="text" value="${value ? value.first_name : ''}" class="form-control first-name-input">

                        Last Name

                            <input name="contacts[last_name][${elementNumber}]" id="last-name-${elementNumber}" type="text" value="${value ? value.last_name : ''}" class="form-control">

                        Job Title *

                            <input name="contacts[job_title][${elementNumber}]" id="job-title-${elementNumber}" type="text" value="${value ? value.job_title : ''}" class="form-control job-title-input">

                        Email *

                            <input name="contacts[contact_email][${elementNumber}]" id="contact-email-${elementNumber}" type="text" value="${value ? value.email : ''}" class="form-control email-input">

                        Office Phone

                            <input name="contacts[office_phone][${elementNumber}]" id="office-phone-${elementNumber}" type="text" value="${value ? value.office_phone : ''}" class="form-control">

                        Mobile Phone

                            <input name="contacts[mobile_phone][${elementNumber}]" id="mobile-phone-${elementNumber}" type="text" value="${value ? value.mobile_phone : ''}" class="form-control">

                        Notes

                            <textarea name="contacts[contact_notes][${elementNumber}]" id="contact-notes-${elementNumber}" class="form-control">${value ? value.notes : ''}</textarea>

                    Delete contact

    `;
}

So, creating new fields and generating existing ones from json strings fulfills the same function.

JSON example:

[{
    "building_contact_id": 781,
    "building_id": 76516,
    "job_title": "Officer",
    "first_name": "John",
    "last_name": "",
    "mobile_phone": "",
    "office_phone": "",
    "email": "john.doe@mail.com",
    "notes": "",
    "created_at": "2020-06-02T13:42:32.000000Z",
    "updated_at": "2020-06-02T13:42:32.000000Z"
}]

Body:
Needed to be wrapped in a timeout:

setTimeout(function () {
    if (firstName.length) {
        firstName.rules("add", {
            required: true
        });
    }

    if (jobTitle.length) {
        jobTitle.rules("add", {
            required: true
        });
    }

    if (contactEmail.length) {
        contactEmail.rules("add", {
            required: true
        });
    }
}, 100)


问:
What is the benefit of writing C function in Objective C?
I am curious when and why we should write C function in Objective C code. I see some of the code where the C function could be replaced by a Objective C class level method.

I tried to google this but did not get much useful information. Please give me some simple examples where we should use a C function.

答:
It's worth to consider how they exactly differ.

Performance

Extra steps of a Objective-C method call vs a C function call include:

passing "hidden" arguments: instance/class as the 1st argument and the selector name as the 2nd argument.

optionally traversing the class hierarchy to find the one actually having the implementation

a lookup in
the selector cache to find the relevant IMP.

All of it takes time, so a C function call will always happen marginally faster. Example of an area where it may matter is audio processing.

Nontrivial reverse engineering

Selector names are a giveaway of what a Objective-c method does, so it's a bit harder to analyze what a C function does. You have greater flexibility too to further conceal the invocation (before resorting to asm).

Inability to swizzle

It's very hard to hook a C function, but it's so easy to replace/hook implementation of an objective method. Nowadays nondynamic direct objective-c methods do exist to counter that (__attribute__((objc_direct))) but that's very recent objc language evolution.

Special use cases for C functions

Apart from obvious main entry point other examples include:

- signal handlers

- code executed before + (void)initialize; and main for C functions marked with __attribute__((constructor))

- threading operations requiring ultra precise timing


问:
Customised ordering in Hive's row_number() over partition by order by window function
I have a table with an identifier column id and another column with string values column_b for which I would like to do customer ordering on column_b. Let's say that column_b consists of values A, B, C, D.

The syntax that can be used in Hive for row_number() over() is:

```<code>SELECT id, column_b, row_number() over(partition by id order by column_b) as row_id
FROM   some_table
</code>```

Example see here for an example

However, I would like to do custom ordering on column_b instead of alphabetic ordering. The above syntax would yield something like:

Instead, I would like to explicitly order by column_b using the order A, C, D, B, that is:

How can I achieve this?

答:
Explicitly specify the order using case statement. You can use other scalar functions in the order by:

```<code>SELECT id, column_b,
       row_number() over(partition by id order by case column_b
                                                       when 'A' then '1'
                                                       when 'C' then '2'
                                                       when 'D' then '3'
                                                       when 'B' then '4'
                                                       --add more cases
                                                       --for example other values sort
                                                       --in natural order
                                                       else column_b
                                                       --or use constant
                                                       --to make sure
                                                       --everything else is greater than 4
                                                       --like this  else concat('5',column_b)
                                                  end
                         ) as row_id
  FROM some_table
</code>```

Also you can calculate order column in the subquery and use it in the window, it will work the same:

```<code>SELECT id, column_b,
       row_number() over(partition by id order by orderby) as row_id
  FROM (select t.*,
               case column_b
                    when 'A' then '1'
                    when 'C' then '2'
                    when 'D' then '3'
                    when 'B' then '4'
                    else concat('5',column_b)
               end orderby
           from some_table t
        ) s
</code>```

Body:
I have a table with an identifier column id and another column with string values column_b for which I would like to do customer ordering on column_b. Let's say that column_b consists of values A, B, C, D.

The syntax that can be used in Hive for row_number() over() is:

SELECT id, column_b, row_number() over(partition by id order by column_b) as row_id
FROM   some_table

Example see here for an example

However, I would like to do custom ordering on column_b instead of alphabetic ordering. The above syntax would yield something like:

Instead, I would like to explicitly order by column_b using the order A, C, D, B, that is:

How can I achieve this?

Body:
Explicitly specify the order using case statement. You can use other scalar functions in the order by:

SELECT id, column_b,
       row_number() over(partition by id order by case column_b
                                                       when 'A' then '1'
                                                       when 'C' then '2'
                                                       when 'D' then '3'
                                                       when 'B' then '4'
                                                       --add more cases
                                                       --for example other values sort
                                                       --in natural order
                                                       else column_b
                                                       --or use constant
                                                       --to make sure
                                                       --everything else is greater than 4
                                                       --like this  else concat('5',column_b)
                                                  end
                         ) as row_id
  FROM some_table

Also you can calculate order column in the subquery and use it in the window, it will work the same:

SELECT id, column_b,
       row_number() over(partition by id order by orderby) as row_id
  FROM (select t.*,
               case column_b
                    when 'A' then '1'
                    when 'C' then '2'
                    when 'D' then '3'
                    when 'B' then '4'
                    else concat('5',column_b)
               end orderby
           from some_table t
        ) s


问:
HTML5 dragleave fired when hovering a child element
The problem I'm having is that the dragleave event of an element is fired when hovering a child element of that element. Also, dragenter is not fired when hovering back the parent element again.

I made a simplified fiddle: http://jsfiddle.net/pimvdb/HU6Mk/1/.

HTML:

```<code><div id="drag" draggable="true">drag me</div>

<hr>

<div id="drop">
    drop here
    <p>child</p>
    parent
</div>
</code>```

with the following JavaScript:

```<code>$('#drop').bind({
                 dragenter: function() {
                     $(this).addClass('red');
                 },

                 dragleave: function() {
                     $(this).removeClass('red');
                 }
                });

$('#drag').bind({
                 dragstart: function(e) {
                     e.allowedEffect = "copy";
                     e.setData("text/plain", "test");
                 }
                });
</code>```

What it is supposed to do is notifying the user by making the drop div red when dragging something there. This works, but if you drag into the p child, the dragleave is fired and the div isn't red anymore. Moving back to the drop div also doesn't make it red again. It's necessary to move completely out of the drop div and drag back into it again to make it red.

Is it possible to prevent dragleave from firing when dragging into a child element?

2017 Update:  TL;DR, Look up CSS pointer-events: none; as described in @H.D.'s answer below that works in modern browsers and IE11.

答:
I struggeled a LOT with this, even after reading through all of these answers, and thought I may share my solution with you, because I figured it may be one of the simpler approaches, somewhat different though. My thought was of simply omitting the dragleave event listener completely, and coding the dragleave behaviour with each new dragenter event fired, while making sure that dragenter events won't be fired unnecessarily.

In my example below, I have a table, where I want to be able to exchange table row contents with each other via drag & drop API. On dragenter, a CSS class shall be added to the row element into which you're currently dragging your element, to highlight it, and on dragleave, this class shall be removed.

Example:

Very basic HTML table:

```<code><table>
  <tr>
    <td draggable="true" class="table-cell">Hello</td>
  </tr>
  <tr>
    <td draggable="true" clas="table-cell">There</td>
  </tr>
</table>
</code>```

And the dragenter event handler function, added onto each table cell (aside dragstart, dragover, drop, and dragend handlers, which are not specific to this question, so not copied here):

```<code>/*##############################################################################
##                              Dragenter Handler                             ##
##############################################################################*/

// When dragging over the text node of a table cell (the text in a table cell),
// while previously being over the table cell element, the dragleave event gets
// fired, which stops the highlighting of the currently dragged cell. To avoid
// this problem and any coding around to fight it, everything has been
// programmed with the dragenter event handler only; no more dragleave needed

// For the dragenter event, e.target corresponds to the element into which the
// drag enters. This fact has been used to program the code as follows:

var previousRow = null;

function handleDragEnter(e) {
  // Assure that dragenter code is only executed when entering an element (and
  // for example not when entering a text node)
  if (e.target.nodeType === 1) {
    // Get the currently entered row
    let currentRow = this.closest('tr');
    // Check if the currently entered row is different from the row entered via
    // the last drag
    if (previousRow !== null) {
      if (currentRow !== previousRow) {
        // If so, remove the class responsible for highlighting it via CSS from
        // it
        previousRow.className = "";
      }
    }
    // Each time an HTML element is entered, add the class responsible for
    // highlighting it via CSS onto its containing row (or onto itself, if row)
    currentRow.className = "ready-for-drop";
    // To know which row has been the last one entered when this function will
    // be called again, assign the previousRow variable of the global scope onto
    // the currentRow from this function run
    previousRow = currentRow;
  }
}
</code>```

Very basic comments left in code, such that this code suits for beginners too. Hope this will help you out! Note that you will of course need to add all the event listeners I mentioned above onto each table cell for this to work.

Body:
The problem I'm having is that the dragleave event of an element is fired when hovering a child element of that element. Also, dragenter is not fired when hovering back the parent element again.

I made a simplified fiddle: http://jsfiddle.net/pimvdb/HU6Mk/1/.

HTML:

drag me

    drop here

child

    parent

with the following JavaScript:

$('#drop').bind({
                 dragenter: function() {
                     $(this).addClass('red');
                 },

                 dragleave: function() {
                     $(this).removeClass('red');
                 }
                });

$('#drag').bind({
                 dragstart: function(e) {
                     e.allowedEffect = "copy";
                     e.setData("text/plain", "test");
                 }
                });

What it is supposed to do is notifying the user by making the drop div red when dragging something there. This works, but if you drag into the p child, the dragleave is fired and the div isn't red anymore. Moving back to the drop div also doesn't make it red again. It's necessary to move completely out of the drop div and drag back into it again to make it red.

Is it possible to prevent dragleave from firing when dragging into a child element?

2017 Update:  TL;DR, Look up CSS pointer-events: none; as described in @H.D.'s answer below that works in modern browsers and IE11.

Body:
I struggeled a LOT with this, even after reading through all of these answers, and thought I may share my solution with you, because I figured it may be one of the simpler approaches, somewhat different though. My thought was of simply omitting the dragleave event listener completely, and coding the dragleave behaviour with each new dragenter event fired, while making sure that dragenter events won't be fired unnecessarily.

In my example below, I have a table, where I want to be able to exchange table row contents with each other via drag & drop API. On dragenter, a CSS class shall be added to the row element into which you're currently dragging your element, to highlight it, and on dragleave, this class shall be removed.

Example:

Very basic HTML table:

<table>
  <tr>
    <td draggable="true" class="table-cell">Hello</td>
  </tr>
  <tr>
    <td draggable="true" clas="table-cell">There</td>
  </tr>
</table>

And the dragenter event handler function, added onto each table cell (aside dragstart, dragover, drop, and dragend handlers, which are not specific to this question, so not copied here):

/*##############################################################################
##                              Dragenter Handler                             ##
##############################################################################*/

// When dragging over the text node of a table cell (the text in a table cell),
// while previously being over the table cell element, the dragleave event gets
// fired, which stops the highlighting of the currently dragged cell. To avoid
// this problem and any coding around to fight it, everything has been
// programmed with the dragenter event handler only; no more dragleave needed

// For the dragenter event, e.target corresponds to the element into which the
// drag enters. This fact has been used to program the code as follows:

var previousRow = null;

function handleDragEnter(e) {
  // Assure that dragenter code is only executed when entering an element (and
  // for example not when entering a text node)
  if (e.target.nodeType === 1) {
    // Get the currently entered row
    let currentRow = this.closest('tr');
    // Check if the currently entered row is different from the row entered via
    // the last drag
    if (previousRow !== null) {
      if (currentRow !== previousRow) {
        // If so, remove the class responsible for highlighting it via CSS from
        // it
        previousRow.className = "";
      }
    }
    // Each time an HTML element is entered, add the class responsible for
    // highlighting it via CSS onto its containing row (or onto itself, if row)
    currentRow.className = "ready-for-drop";
    // To know which row has been the last one entered when this function will
    // be called again, assign the previousRow variable of the global scope onto
    // the currentRow from this function run
    previousRow = currentRow;
  }
}

Very basic comments left in code, such that this code suits for beginners too. Hope this will help you out! Note that you will of course need to add all the event listeners I mentioned above onto each table cell for this to work.


问:
How to change from last VC to middle VC on Swifft
So i need to write some code to help me dismiss the segue modally once the question VC (4th) sends a segue to the results VC (5th). I want the 5th VC to dismiss the segue modally to the Difficulty VC (3th) using the code

self.dismiss(animated: true, completion: nil)

allows me to dismiss to the previous VC, which is the Question VC. But how can I dismiss to the dificulty VC (3rd VC).

Thanks!

Oscar Ramos

Storyboad 5 VC's

code for the last VC

答:
You can make use of the completion handler of the dismiss(animated:completion:) method, like this:

```<code>vc5.dismiss(animated: true) { [vc4] in
    vc4.dismiss(animated: true)
}
</code>```

For information about how this method works you can read the documentation.

Body:
You can make use of the completion handler of the dismiss(animated:completion:) method, like this:

vc5.dismiss(animated: true) { [vc4] in
    vc4.dismiss(animated: true)
}

For information about how this method works you can read the documentation.


问:
how to attach the pdf file that is present in program file throught mail
am generating a pdf file in my c# code... i want to attach that pdf file and same to my mail id using attachment... can anyone help me in sending pdf through attachment internally using c# code

thank you

答:
You can attach your pdf file as : </p>

```<code>MailMessage message = new MailMessage();
message.To = "mailgoesto@domain.com";
message.From = "mailcomesfrom@domain.com";
message.Subject = "mail with pdf";
message.Body = "your pdf attached";
message.Attachments.Add(new Attachment(@"c:\pdftoattach.pdf"));

SmtpMail.SmtpServer = "mail.domain.com";
SmtpMail.Send(message);
</code>```

OwnerDisplayName: apekshabs

ContentLicense: CC BY-SA 2.5

Body:
You can attach your pdf file as :

MailMessage message = new MailMessage();
message.To = "mailgoesto@domain.com";
message.From = "mailcomesfrom@domain.com";
message.Subject = "mail with pdf";
message.Body = "your pdf attached";
message.Attachments.Add(new Attachment(@"c:\pdftoattach.pdf"));

SmtpMail.SmtpServer = "mail.domain.com";
SmtpMail.Send(message);

OwnerDisplayName: ScarletGarden


问:
How do i avoid logging the output of skipped role in Ansible
I am skipping a role in Ansible using when condition but it is still printing the task when i run the playbook. Is there a way to not log these task or may be if they are logging then add something like Task Skipped?

/roles/copyrepo/tasks/main.yml

```<code>---
- include: real_tasks.yml
  when: temp.stat.isdir is undefined
</code>```

/roles/copyrepo/tasks/real_tasks.yml

```<code>    - name: Ensuring that the web deployment folder is created on nodes for each web application
      file:
        path: "{{release_location}}/Release{{release_version}}/{{item}}/webapp"
        state: directory
        mode: 0755
      with_items:
       - "{{ myapps }}"

    - name: Copying the release war files from local server to tomcat nodes
      copy: src={{local_server_release_location}}/{{release_version}}/{{item}}-{{release_version}}.war dest={{release_location}}/Release{{release_version}}/{{item}}
      with_items:
       - "{{ myapps }}"

    - name: Overriding the directory name
      command: mv /temp/myapp-web /temp/myapp
</code>```

display_skipped_hosts = False won't work here because the task header will still be shown regardless of whether or not the task is skipped.

How do i avoid showing below headers in my output as they are not being executed?

```<code>Ensuring that the web deployment folder is created on nodes for each web application...
Tuesday 02 June 2020  16:54:11 +0100 (0:00:00.216)       0:00:07.378 **********
Copying the MyVM release war files from local server to tomcat nodes...
Tuesday 02 June 2020  16:54:11 +0100 (0:00:00.204)       0:00:07.582 **********
Overriding the directory name...
Tuesday 02 June 2020  16:54:12 +0100 (0:00:00.205)       0:00:07.787 **********
</code>```

Let me know if someone can advice.

答: If you are unhappy with the provided selection of stdout callback plugins, then you can write your own that displays exactly the output you want, formatted exactly how you want. As far as I know, it's even possible to have them per playbook if you wanted to package the plugin to travel along your normal playbook distribution mechanism</p>

Body:
I am skipping a role in Ansible using when condition but it is still printing the task when i run the playbook. Is there a way to not log these task or may be if they are logging then add something like Task Skipped?

/roles/copyrepo/tasks/main.yml

---
- include: real_tasks.yml
  when: temp.stat.isdir is undefined

/roles/copyrepo/tasks/real_tasks.yml

    - name: Ensuring that the web deployment folder is created on nodes for each web application
      file:
        path: "{{release_location}}/Release{{release_version}}/{{item}}/webapp"
        state: directory
        mode: 0755
      with_items:
       - "{{ myapps }}"

    - name: Copying the release war files from local server to tomcat nodes
      copy: src={{local_server_release_location}}/{{release_version}}/{{item}}-{{release_version}}.war dest={{release_location}}/Release{{release_version}}/{{item}}
      with_items:
       - "{{ myapps }}"

    - name: Overriding the directory name
      command: mv /temp/myapp-web /temp/myapp

display_skipped_hosts = False won't work here because the task header will still be shown regardless of whether or not the task is skipped.

How do i avoid showing below headers in my output as they are not being executed?

Ensuring that the web deployment folder is created on nodes for each web application...
Tuesday 02 June 2020  16:54:11 +0100 (0:00:00.216)       0:00:07.378 **********
Copying the MyVM release war files from local server to tomcat nodes...
Tuesday 02 June 2020  16:54:11 +0100 (0:00:00.204)       0:00:07.582 **********
Overriding the directory name...
Tuesday 02 June 2020  16:54:12 +0100 (0:00:00.205)       0:00:07.787 **********

Let me know if someone can advice.


问:
Save the video while making a video call using AWS Kinesis Video stream with WebRTC
Im using aws kinesis video stream webRTC for making a video chat in reactjs .Everything is working fine.But i want to store the video in s3 bucket.How should i implement this video storage?</p>

答: Since the connection can be peer to peer, you have to store the video yourself to S3. You can try to use the KVS producer sdk for that purpose: https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp</p>


问:
How to start @KafkaListener based on start flag
I'm trying to start my KafkaListener only when a flag is set to true.

```<code>@Component
public class KafkaTopicConsumer {

//Somehow wrap the listener to only start when a property value is set to true

@KafkaListener(topics = "#{@consumerTopic}", groupId = "#{@groupName}")
public void consumeMessage(ConsumerRecord<String, String> message) throws IOException {
    logger.info("Consumed message from topic: {} with message: {}", message.topic(), message);
}
</code>```

Is there a way to only make sure the listener is started when said a property such as start.consumer property is set to true? I don't want the listener starting every time the application is started only when I specify that I want it to be started. Is there a good way to approach this use case?

答:
You can use ConditionalsBeans with a property </p>

```<code>@Bean
@ConditionalOnProperty(
  value="my.custom.flag",
  havingValue = "true")
public KafkaListener kafkaListener{
 .....
}
</code>```

<p>Conditional beans allow you start a bean based on properties or custom conditions.
Reference </p>

Body:
I'm trying to start my KafkaListener only when a flag is set to true.

@Component
public class KafkaTopicConsumer {

//Somehow wrap the listener to only start when a property value is set to true

@KafkaListener(topics = "#{@consumerTopic}", groupId = "#{@groupName}")
public void consumeMessage(ConsumerRecord<String, String> message) throws IOException {
    logger.info("Consumed message from topic: {} with message: {}", message.topic(), message);
}

Is there a way to only make sure the listener is started when said a property such as start.consumer property is set to true? I don't want the listener starting every time the application is started only when I specify that I want it to be started. Is there a good way to approach this use case?

Body:
You can use ConditionalsBeans with a property

@Bean
@ConditionalOnProperty(
  value="my.custom.flag",
  havingValue = "true")
public KafkaListener kafkaListener{
 .....
}

Conditional beans allow you start a bean based on properties or custom conditions.
Reference


问:
Appending variable to end of file on a newline in Python
I am trying to append the data from a variable to the end of a file Python - on a new line. I have used this method: (variable+"/n") but in the file it has all of the file data on one line including the /n symbol.

My code (this is an example! So it makes sense in exactly what I want to be answered):

```<code>list = ["apple","pear","strawberry"]
f = open("test.txt","a")
for x in list:
    f.write(x+"/n")
    print(x)
f.close()
</code>```

Output in test.txt:

```<code>apple/npear/nstrawberry/n
</code>```

What can I do so that the output looks like this:

```<code>apple
pear
strawberry
</code>```

Thank you in advance for your answers!

答: Try using \n instead of /n on line 5.</p>

Body:
I am trying to append the data from a variable to the end of a file Python - on a new line. I have used this method: (variable+"/n") but in the file it has all of the file data on one line including the /n symbol.

My code (this is an example! So it makes sense in exactly what I want to be answered):

list = ["apple","pear","strawberry"]
f = open("test.txt","a")
for x in list:
    f.write(x+"/n")
    print(x)
f.close()

Output in test.txt:

apple/npear/nstrawberry/n

What can I do so that the output looks like this:

apple
pear
strawberry

Thank you in advance for your answers!

Body: Try using \n instead of /n on line 5.