问:
Not able to create Specflow Feature File in Selenium
I am using Selenium for the first time ever in order to run some automated UI tests.  Unfortunately, I have come across a bump in the road. I am trying to create a Specflow Feauture File. In this tutorial, it says that under my features folder, I should add a new item and then select "SpecFlow Feature file" and it will be created.  When I try to add a new item, that option does not appear. Can somebody tell me what I may be doing wrong or why it is not working?

答:
The tutorial you used was done in 2017. Can you look at this one?

https://specflow.org/getting-started/

Make sure you are updated to current versions of everything.

Only use one test runner in your nuget package, ie NUnit, MSTest,
SpecRun

Also Click Extensions > Manage Extensions and search
SpecFlow. Install SpecFlow for Visual Studio.


来源: stackexchange

问:
Unexpected non-equality after assignment
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}
```

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

答:
It happens because you're trying to update a twice in the same statement. a in a.x= refers to the old instance. So, you're updating a to reference b and the old a object field x to reference b.

You can confirm with this:

```<code>void Main()
{
    var a = new MyClass(){s="a"};
    var b = new MyClass() {s="b"};
    var c =a;

    a.x = (a=b);
    Console.WriteLine($"a is {a.s}");
    Console.WriteLine(a.x == b);

    Console.WriteLine($"c is {c.s}");
    Console.WriteLine(c.x == b);
}

class MyClass
{
    public MyClass x;
    public string s;
}
</code>```

The answer will be:

```<code>a is b
False
c is a
True
</code>```

Edit: Just to make a little bit more clear, It's not about the operators' execution order, it's because of the two updates in the same variable in the same statement. The assigment (a=b) is executed before the a.x=, but it doesn't matter, because a.x is referencing the old instance, not the newly updated one. This happens, as @Joe Sewell answer explains, because evaluation, to find the assignment target, is left to right.

ContentLicense: CC BY-SA 4.0

Body:
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

Body:
It happens because you're trying to update a twice in the same statement. a in a.x= refers to the old instance. So, you're updating a to reference b and the old a object field x to reference b.

You can confirm with this:

void Main()
{
    var a = new MyClass(){s="a"};
    var b = new MyClass() {s="b"};
    var c =a;

    a.x = (a=b);
    Console.WriteLine($"a is {a.s}");
    Console.WriteLine(a.x == b);

    Console.WriteLine($"c is {c.s}");
    Console.WriteLine(c.x == b);
}

class MyClass
{
    public MyClass x;
    public string s;
}

The answer will be:

a is b
False
c is a
True

Edit: Just to make a little bit more clear, It's not about the operators' execution order, it's because of the two updates in the same variable in the same statement. The assigment (a=b) is executed before the a.x=, but it doesn't matter, because a.x is referencing the old instance, not the newly updated one. This happens, as @Joe Sewell answer explains, because evaluation, to find the assignment target, is left to right.


问:
Flask/Python - How can I run this python script in Flask and render output in html page
Im writting this code to get some values of stock prices, and how can I render output results in results.html page?
I'm using Heroku to make this app.

Please help me with this app.
This is the main file to call others files.

Please tell me if need more details to run this app.

Here are the codes I've made, to display the output in view.html page.
x.py

print('----EURO DO REMESSA ONLINE-----')
import melhor
print('-----COTAÇÃO DOLARHOJE.COM-----')
import cota
print('-----INDICADOR EURO COMERCIAL H1----')
import indicator
print('-----INVESTING VALOR EURO COM-----')
import invest
print( '-------------\n', 'Conhece a ti mesmo. (Tales de Mileto)', '\n-------------')
```

<hr>

<p>melhor.py</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bs
import time
import re
from Color import *
url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
print('Euro COMERCIAL: R$', Base.BOLD, ANSI_Compatible.Color(120), mult, ANSI_Compatible.END, Base.END)
eur_rate = 1.035145
eur_ra = str(mult * eur_rate)[:6]
print('Euro TURISMO: R$', Base.BOLD, eur_ra, Base.END)
current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
print(current)
with open('remessa.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + eur_ra + ' ' + 'Data:' + current + '\n')
</code>```

cota.py

import requests
import time

response = requests.get('http://dolarhoje.com/cotacao.txt')
data = response.text
print('1 USD comercial =',"R$",data )

response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
data = response.text
print('1 USD turismo =',"R$",data )

response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
data2 = response.text
print('1 EUR comercial =',"R$",data2 )

response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
data2 = response.text
print('1 EUR turismo =',"R$",data2 )

response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
data3 = response.text
print('1 BTC =',"R$",data3 )

current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")
with open('cota.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + data2 + ' ' + 'Data:' + current + '\n')
```

<hr>

<p>indicator.py</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
print(resumo)
</code>```

invest.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
print(resumo)
```

Thanks for your attention.

答: I hope I can be helpful, and I don't know much about Python. But it sounds like if you're doing Server-side rendering of the html page, you just need a template engine such as Jade, Pug, or something of that sort.</p>

Body:
Im writting this code to get some values of stock prices, and how can I render output results in results.html page?
I'm using Heroku to make this app.

Please help me with this app.
This is the main file to call others files.

Please tell me if need more details to run this app.

Here are the codes I've made, to display the output in view.html page.
x.py

print('----EURO DO REMESSA ONLINE-----')
import melhor
print('-----COTAÇÃO DOLARHOJE.COM-----')
import cota
print('-----INDICADOR EURO COMERCIAL H1----')
import indicator
print('-----INVESTING VALOR EURO COM-----')
import invest
print( '-------------\n', 'Conhece a ti mesmo. (Tales de Mileto)', '\n-------------')

melhor.py

import requests
from bs4 import BeautifulSoup as bs
import time
import re
from Color import *
url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
print('Euro COMERCIAL: R$', Base.BOLD, ANSI_Compatible.Color(120), mult, ANSI_Compatible.END, Base.END)
eur_rate = 1.035145
eur_ra = str(mult * eur_rate)[:6]
print('Euro TURISMO: R$', Base.BOLD, eur_ra, Base.END)
current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
print(current)
with open('remessa.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + eur_ra + ' ' + 'Data:' + current + '\n')

cota.py

import requests
import time

response = requests.get('http://dolarhoje.com/cotacao.txt')
data = response.text
print('1 USD comercial =',"R$",data )

response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
data = response.text
print('1 USD turismo =',"R$",data )

response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
data2 = response.text
print('1 EUR comercial =',"R$",data2 )

response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
data2 = response.text
print('1 EUR turismo =',"R$",data2 )

response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
data3 = response.text
print('1 BTC =',"R$",data3 )

current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")
with open('cota.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + data2 + ' ' + 'Data:' + current + '\n')

indicator.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
print(resumo)

invest.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
print(resumo)

Thanks for your attention.


问:
Interrupting last touch event in Android
My app shows ListPopupWindow as a context menu when user long clicks on list item. After the context menu is displayed, background is still avalable for dragging untill the user lifts his finger up. You can see behaviour in attached gifs.
I want to know how to interrup this dragging.

TrackListAdapter.java:

```<code>private final float[] longClickLastTouchDownXY = new float[2];

@Override
@CallSuper
public void onBindViewHolder(VH holder, int position) {
    holder.itemView.setOnTouchListener((v, event) -> {
        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            longClickLastTouchDownXY[0] = event.getX();
            longClickLastTouchDownXY[1] = event.getY();
        }
        return false;
    });
    holder.itemView.setOnLongClickListener(v -> {
        if (onItemLongClickListener != null) {
            onItemLongClickListener.onItemLongClick((ViewGroup) v,
                    (int) longClickLastTouchDownXY[0], (int) longClickLastTouchDownXY[1],
                    holder.getAdapterPosition());
            return true;
        }
        return false;
    });
}
</code>```

TrackListFragment.java:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.list_track, container, false);
    ButterKnife.bind(this, layout);

    tracksList.setAdapter(tracksAdapter);
    tracksAdapter.setOnItemLongClickListener(this::showTrackContextMenu);

    return layout;
}

private void showTrackContextMenu(ViewGroup rootView, float x, float y, int itemPosition) {
    Track selectedTrack = tracksAdapter.get(itemPosition);
    ListPopupWindow popupWindow = new ListPopupWindow(requireContext());
    ListPopupWindowAdapter adapter = new ListPopupWindowAdapter(requireContext(), R.menu.track_menu);
    popupWindow.setAdapter(adapter);

    View tempView = new View(requireContext());
    ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(0, 0);
    tempView.setLayoutParams(lp);
    tempView.setX(x - rootView.getPaddingLeft());
    tempView.setY(y - rootView.getPaddingTop());
    rootView.addView(tempView);

    popupWindow.setAnchorView(tempView);
    popupWindow.setModal(true);
    popupWindow.setOnDismissListener(() -> rootView.removeView(tempView));
    popupWindow.show();
}
</code>```

答:
This should work in theory, I didn't test this:

For freezing vertical scroll of RecyclerView:

RecyclerView has a method called setLayoutFrozen(boolean frozen);, this method seems to block the TouchEvent of the RecyclerView while it is active (when you set frozen to true).

Now I am assuming that your method showTrackContextMenu(.....) is called when you longClick an item in your list (it seems you made an interface for this). Anyway try to freeze the RecyclerView at the end of this method. Like this:

```<code>private void showTrackContextMenu(ViewGroup rootView, float x, float y, int itemPosition) {

.......
.......
.......

popupWindow.show();

//here
yourRecyclerView.setLayoutFrozen(true);

}
</code>```

If you want to remove the freeze so you can scroll again, just call this:

```<code>yourRecyclerView.setLayoutFrozen(false);
</code>```

For freezing ViewPager:

Okay I can't find a method that is built to freeze the ViewPager, the only thing you can really do is to make a custom ViewPager and use that instead and make it do what you want:

```<code>class MyViewPager extends ViewPager{

private boolean frozen = false;

public MyViewPager(Context context){
super(context);
}

public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}

public void freezeViewPager(boolean frozen){
this.frozen = frozen;
}

@Override
 public boolean onTouchEvent(MotionEvent event) {
if(frozen){
 return false;
}else{
 return super.onTouchEvent(event);
}

}

}
</code>```

Then you use the above ViewPager in xml instead of the default one that you are using.

To freeze it:

```<code>.......

popupWindow.show();

//here freeze recyclerView
yourRecyclerView.setLayoutFrozen(true);
//here freeze view pager
myViewPager.freezeViewPager(true);
</code>```

To stop the freeze:

```<code>myViewPager.freezeViewPager(false);
</code>```

Body:
My app shows ListPopupWindow as a context menu when user long clicks on list item. After the context menu is displayed, background is still avalable for dragging untill the user lifts his finger up. You can see behaviour in attached gifs.
I want to know how to interrup this dragging.

TrackListAdapter.java:

private final float[] longClickLastTouchDownXY = new float[2];

@Override
@CallSuper
public void onBindViewHolder(VH holder, int position) {
    holder.itemView.setOnTouchListener((v, event) -> {
        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            longClickLastTouchDownXY[0] = event.getX();
            longClickLastTouchDownXY[1] = event.getY();
        }
        return false;
    });
    holder.itemView.setOnLongClickListener(v -> {
        if (onItemLongClickListener != null) {
            onItemLongClickListener.onItemLongClick((ViewGroup) v,
                    (int) longClickLastTouchDownXY[0], (int) longClickLastTouchDownXY[1],
                    holder.getAdapterPosition());
            return true;
        }
        return false;
    });
}

TrackListFragment.java:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.list_track, container, false);
    ButterKnife.bind(this, layout);

    tracksList.setAdapter(tracksAdapter);
    tracksAdapter.setOnItemLongClickListener(this::showTrackContextMenu);

    return layout;
}

private void showTrackContextMenu(ViewGroup rootView, float x, float y, int itemPosition) {
    Track selectedTrack = tracksAdapter.get(itemPosition);
    ListPopupWindow popupWindow = new ListPopupWindow(requireContext());
    ListPopupWindowAdapter adapter = new ListPopupWindowAdapter(requireContext(), R.menu.track_menu);
    popupWindow.setAdapter(adapter);

    View tempView = new View(requireContext());
    ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(0, 0);
    tempView.setLayoutParams(lp);
    tempView.setX(x - rootView.getPaddingLeft());
    tempView.setY(y - rootView.getPaddingTop());
    rootView.addView(tempView);

    popupWindow.setAnchorView(tempView);
    popupWindow.setModal(true);
    popupWindow.setOnDismissListener(() -> rootView.removeView(tempView));
    popupWindow.show();
}

Body:
This should work in theory, I didn't test this:

For freezing vertical scroll of RecyclerView:

RecyclerView has a method called setLayoutFrozen(boolean frozen);, this method seems to block the TouchEvent of the RecyclerView while it is active (when you set frozen to true).

Now I am assuming that your method showTrackContextMenu(.....) is called when you longClick an item in your list (it seems you made an interface for this). Anyway try to freeze the RecyclerView at the end of this method. Like this:

private void showTrackContextMenu(ViewGroup rootView, float x, float y, int itemPosition) {

.......
.......
.......

popupWindow.show();

//here
yourRecyclerView.setLayoutFrozen(true);

}

If you want to remove the freeze so you can scroll again, just call this:

yourRecyclerView.setLayoutFrozen(false);

For freezing ViewPager:

Okay I can't find a method that is built to freeze the ViewPager, the only thing you can really do is to make a custom ViewPager and use that instead and make it do what you want:

class MyViewPager extends ViewPager{

private boolean frozen = false;

public MyViewPager(Context context){
super(context);
}

public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}

public void freezeViewPager(boolean frozen){
this.frozen = frozen;
}

@Override
 public boolean onTouchEvent(MotionEvent event) {
if(frozen){
 return false;
}else{
 return super.onTouchEvent(event);
}

}

}

Then you use the above ViewPager in xml instead of the default one that you are using.

To freeze it:

.......

popupWindow.show();

//here freeze recyclerView
yourRecyclerView.setLayoutFrozen(true);
//here freeze view pager
myViewPager.freezeViewPager(true);

To stop the freeze:

myViewPager.freezeViewPager(false);


问:
Is it possible to send data to a specific login-required web service with C# using its defined method without HttpWebRequest?
I have access to WSDL file of a specific web service that contains a SendData method - basically I specify the TimeStamp and Value to be send. I uploaded the WSDL file to my project in Visual Studio 2019 as a connected service (Add->Connected Service->Microsoft WCF Web Service Reference Provider->Browse->I added location of the WSDL file and specified the service that included SendData method). After that I created a new client:

```<code>ServiceSoapClient client = new ServiceSoapClient(ServiceSoapClient.EndpointConfiguration.ServiceSoap);
</code>```

added credentials (the web service requires login):

```<code>client.ClientCredentials.UserName.UserName = "test"; client.ClientCredentials.UserName.Password = "test";
</code>```

created a new variable Data that contains TimeStamp and Value (in a specific format required by the method).

After that I invoked the method:

```<code>client.SendData(Data);
</code>```

but it doesn't work. There are no errors or exceptions thrown, but the Data is not visible on the web service (the web service also has a GUI). I started to wonder if it is possible to send data to a web service in such a way or is it maybe necessary to create an xml file with a request and use HttpWebRequest?

Perhaps someone could help me figure out what is wrong, is there a way to check, what is going on during compilation? Unfortunately, I cannot include the URI or WSDL file, but hopefully my description of the issue will be sufficient. Thanks in advance for any guidance!

答:
Okay, with the suggestion from Robert Harvey (thank you once again) and some trial and error I managed to solve my problem. Hopefully my answer will be useful to someone with the similar issue.

I found out that in some cases WCF web service's calls are not visible in Fiddler. In my case it was due to some packages not being up-to-date. These out-of-date packages were added automatically after connecting the web service via Microsoft WCF Web Service Reference Provider.

System.ServiceModel.Duplex/Http/NetTcp/Security all were installed in version 4.4 instead of 4.7. I updated them using Project->Manage NuGet Packages and now my requests are visible in Fiddler and I managed to verify that the way I used my method was correct, but the access to the web service (with the ability to save data) is currently limited, that is why the result was not visible directly on the web service (in the GUI).

Body:
I have access to WSDL file of a specific web service that contains a SendData method - basically I specify the TimeStamp and Value to be send. I uploaded the WSDL file to my project in Visual Studio 2019 as a connected service (Add->Connected Service->Microsoft WCF Web Service Reference Provider->Browse->I added location of the WSDL file and specified the service that included SendData method). After that I created a new client:

ServiceSoapClient client = new ServiceSoapClient(ServiceSoapClient.EndpointConfiguration.ServiceSoap);

added credentials (the web service requires login):

client.ClientCredentials.UserName.UserName = "test"; client.ClientCredentials.UserName.Password = "test";

created a new variable Data that contains TimeStamp and Value (in a specific format required by the method).

After that I invoked the method:

client.SendData(Data);

but it doesn't work. There are no errors or exceptions thrown, but the Data is not visible on the web service (the web service also has a GUI). I started to wonder if it is possible to send data to a web service in such a way or is it maybe necessary to create an xml file with a request and use HttpWebRequest?

Perhaps someone could help me figure out what is wrong, is there a way to check, what is going on during compilation? Unfortunately, I cannot include the URI or WSDL file, but hopefully my description of the issue will be sufficient. Thanks in advance for any guidance!


问:
angular2 xhrfields withcredentials true
I am trying to login to a system. In angular 1, there was ways to set

```<code>withCredentials:true
</code>```

But I could not find a working solution in angular2

```<code>export class LoginComponent {
    constructor(public _router: Router, public http: Http, ) {

    }

    onSubmit(event,username,password) {
        this.creds = {'Email': 'harikrishna@gmail.com','Password': '01010','RememberMe': true}
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');

        this.http.post('http://xyz/api/Users/Login', {}, this.creds)
              .subscribe(res => {
                  console.log(res.json().results);

              });
     }

}
</code>```

答:
```<code>getHeaders(): RequestOptions {
    let optionsArgs: RequestOptionsArgs = { withCredentials: true }
    let options = new RequestOptions(optionsArgs)
    return options;
  }

getAPIData(apiName): Observable<any> {`enter code here`
    console.log(Constants.API_URL + apiName);
    let headers = this.getHeaders();
    return this.http
      .get(Constants.API_URL + apiName, headers)
      .map((res: Response) => res.json())
  }
</code>```

Enabled cors in the webapi

Same code works fine in the chrome(normal),Internet explorer

But it is asking windows login prompt in the incognito chrome,firefox,edge.
Share the suggestions how to fix the issue

ContentLicense: CC BY-SA 3.0

Title: angular2 xhrfields withcredentials true

Body:
I am trying to login to a system. In angular 1, there was ways to set

withCredentials:true

But I could not find a working solution in angular2

export class LoginComponent {
    constructor(public _router: Router, public http: Http, ) {

    }

    onSubmit(event,username,password) {
        this.creds = {'Email': 'harikrishna@gmail.com','Password': '01010','RememberMe': true}
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');

        this.http.post('http://xyz/api/Users/Login', {}, this.creds)
              .subscribe(res => {
                  console.log(res.json().results);

              });
     }

}

Body:
getHeaders(): RequestOptions {
    let optionsArgs: RequestOptionsArgs = { withCredentials: true }
    let options = new RequestOptions(optionsArgs)
    return options;
  }

getAPIData(apiName): Observable<any> {`enter code here`
    console.log(Constants.API_URL + apiName);
    let headers = this.getHeaders();
    return this.http
      .get(Constants.API_URL + apiName, headers)
      .map((res: Response) => res.json())
  }

Enabled cors in the webapi

Same code works fine in the chrome(normal),Internet explorer

But it is asking windows login prompt in the incognito chrome,firefox,edge.
Share the suggestions how to fix the issue


问:
Heroku Force Clear Varnish Cache
Is it possible to force Heroku to clear out the Varnish cache from within an application (i.e. without pushing a new repository)?</p>

答:
Though this Heroku mailing list message is a year old, I haven't found anything to contradict it.

No, there's no official way to
  manually expire your cache on Varnish.
  If you need more control over your
  cache (ie setting when it expires is
  not enough) I'd recommend using
  Memcache instead.

I doubt this has changed. Since Varnish is run outside the context of the Rails app, there probably isn't a Varnish class or anything like that, so no method that would purge the cache. Looks like you're on your own.

Title: Heroku Force Clear Varnish Cache


Title: How to parse a text file using regex

Body:
I'm trying to parse some log files to get some numbers out and into a CSV file. The log files have a lot of log messages but below is an excerpt of the lines that need to parse.

I'm trying to get the loss and accuracy numbers out of this text file below into a CSV. Any recommendations for bash or python tricks?

1500/1500 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5
1500/1500 [==============================] - 1675s 1s/step - loss: 0.0409 - accuracy: 0.9881 - val_loss: 0.0533 - val_accuracy: 0.9855

Here is what I tried in python:

import re
text = r"""00 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5"""
regular_exp = re.compile(r'^.*val_accuracy.*$', re.M)
for match in regular_exp.finditer(text)
   print(match)

Body:
In Python, use named capturing groups:

(?m)^(?P<iteration>\d+(?:/\d+)?)\s+\[=+]\s+-\s+(?P<seconds>\d+)s\s+1s/step\s+-\s+loss:\s*(?P<loss>\d+\.\d+)\s+-\s+accuracy:\s*(?P<accuracy>\d+\.\d+)\s+-\s+val_loss:\s*(?P<val_loss>\d+\.\d+)\s*-\s*val_accuracy:\s*(?P<val_accuracy>\d+\.\d+)\r?\nEpoch\s+(?P<epoch_num>\d+):\s*saving model to\s*(?P<epoch_file>.*)

See proof.

Python code:

regular_exp = re.compile(r'^(?P<iteration>\d+(?:/\d+)?)\s+\[=+]\s+-\s+(?P<seconds>\d+)s\s+1s/step\s+-\s+loss:\s*(?P<loss>\d+\.\d+)\s+-\s+accuracy:\s*(?P<accuracy>\d+\.\d+)\s+-\s+val_loss:\s*(?P<val_loss>\d+\.\d+)\s*-\s*val_accuracy:\s*(?P<val_accuracy>\d+\.\d+)\r?\nEpoch\s+(?P<epoch_num>\d+):\s*saving model to\s*(?P<epoch_file>.*)', re.M)
with open(filepath, 'r') as file:
    results = [ match.groupdict() for match in re.finditer(file.read()) ]

See <a href="https://tio.run/##rZRBj6MgGIbv/RWkl9F2VBBBabbT0x432XvtGqO0NatigE5mfn0XrJ04rdlMJiVR4PMR87yK3bs@ihafz1XTCamB5DPN3zRYAzmfzyEE2/V/2w54ACUwVACpQGnemXktlFoB6OMIQzPNi@Ik8@LdlpKYYFN6zevsSiGE4FAak4zGcPazE8URQNPCFVD5a9UeQCNKXgMtQCCF0EGZ69wr8uLI@2Ggmy7oERUIe2UvPAT/ZiEMISRh7EGIGMIZDDPoQ8pChmgYmzFL/COZIQJhYE9f8qYxm/KGScRuvFmM2Y23eTie8k5gPPLGj/bG1puQJKaURd/2jia94yi882bo1psQNukdkZF39GjvqPfGCY0x6t83@443mvQmlNx6J9G9N572JuPvnDzam1y8Q0oJpldvs7Vnkh9OdS4z/tbZ3c79QjRdVXNHPv1xNr9/VJrLXFeifUnLpbNZBaZzN26qlul2vdyZ3jOHJRUvRFsqy7nK1IaEBqL3T9XCknZssdS37AB8pDFA1/kd@JHmAF7nY3BhwMWnjEfwxMpyk7Z9@oMLt@OsPTW9jb355nUMy124vcnrxV@4T882wF@uCVWdaq1MoFvQ5Lo4@gcpTl1ZFdpxwV7ISxVULRjl7@@rtrR5O/bf64LdrJNVq51hNfd8/gc" rel="nofollow noreferrer">Python proof online, output

[
    {'iteration': '00', 'seconds': '1802', 'loss': '0.3430', 'accuracy': '0.8753', 'val_loss': '0.1110', 'val_accuracy': '0.9670', 'epoch_num': '00002', 'epoch_file': '/root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5'},
    {'iteration': '1500/1500', 'seconds': '1679', 'loss': '0.0849', 'accuracy': '0.9739', 'val_loss': '0.0693', 'val_accuracy': '0.9807', 'epoch_num': '00003', 'epoch_file': '/root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5'},
    {'iteration': '1500/1500', 'seconds': '1674', 'loss': '0.0742', 'accuracy': '0.9791', 'val_loss': '0.0559', 'val_accuracy': '0.9845', 'epoch_num': '00004', 'epoch_file': '/root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5'},
    {'iteration': '1500/1500', 'seconds': '1671', 'loss': '0.0565', 'accuracy': '0.9841', 'val_loss': '0.0539', 'val_accuracy': '0.9850', 'epoch_num': '00005', 'epoch_file': '/root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5'}
]


问:
dplyr group_by and summarize with non-standard evaluation
Suppose I have this code:

```<code>> df<-data.frame(a=c(1,1,1,2,2,2), b=c(T,T,F,F,F,T))
> df %>% group_by(a) %>% summarize(trues=sum(b), falses=sum(!b))
# A tibble: 2 x 3
      a trues falses
  <dbl> <int>  <int>
1     1     2      1
2     2     1      2
</code>```

and I want to use a string variable to give b (in a for loop, for example).  It's exactly like this question I think, but I can't seem to get it to work.

Some failed attempts:

```<code>var <- 'b'

df %>% group_by(a) %>% summarize_(trues=sum(var), falses=sum(!var))
df %>% group_by(a) %>% summarize(trues=sum({{var}}), falses=sum(!{{var}}))
df %>% group_by(a) %>% summarize_(trues=sum({{var}}), falses=sum(!{{var}}))
foo1 <- function(df, var) {
  df %>% group_by(a) %>% summarize(trues=sum({{var}}), falses=sum(!{{var}}))
}
foo1(df, 'b')
foo2 <- function(df, var) {
  var <- enquo(var)
  df %>% group_by(a) %>% summarize(trues=sum(!!var), falses=sum(! !!var))
}
foo2(df, 'b')
</code>```

Perhaps I could use the lazyeval package in the other question, but I'd rather know how to do it with just the tidyverse.

答:
In this case, it is better to use ensym as we are passing a string.  Also, the ensym works with unquoted argument as well

```<code>foo2 <- function(df, var) {
   var <- ensym(var)
   df %>%
         group_by(a) %>%
         summarize(trues=sum(!!var),
                   falses=sum(! (!!var)))
  }
foo2(df, 'b')
# A tibble: 2 x 3
#      a trues falses
#* <dbl> <int>  <int>
#1     1     2      1
#2     2     1      2

foo2(df, b)
# A tibble: 2 x 3
#      a trues falses
#* <dbl> <int>  <int>
#1     1     2      1
#2     2     1      2
</code>```

If the argument passed is an object, evaluate (!!) while passing into the function to avoid the literal evaluation

```<code>foo2(df, !!var)
# A tibble: 2 x 3
#      a trues falses
#* <dbl> <int>  <int>
#1     1     2      1
#2     2     1      2
</code>```

Body:
Suppose I have this code:

> df<-data.frame(a=c(1,1,1,2,2,2), b=c(T,T,F,F,F,T))
> df %>% group_by(a) %>% summarize(trues=sum(b), falses=sum(!b))
# A tibble: 2 x 3
      a trues falses
  <dbl> <int>  <int>
1     1     2      1
2     2     1      2

and I want to use a string variable to give b (in a for loop, for example).  It's exactly like this question I think, but I can't seem to get it to work.

Some failed attempts:

var <- 'b'

df %>% group_by(a) %>% summarize_(trues=sum(var), falses=sum(!var))
df %>% group_by(a) %>% summarize(trues=sum({{var}}), falses=sum(!{{var}}))
df %>% group_by(a) %>% summarize_(trues=sum({{var}}), falses=sum(!{{var}}))
foo1 <- function(df, var) {
  df %>% group_by(a) %>% summarize(trues=sum({{var}}), falses=sum(!{{var}}))
}
foo1(df, 'b')
foo2 <- function(df, var) {
  var <- enquo(var)
  df %>% group_by(a) %>% summarize(trues=sum(!!var), falses=sum(! !!var))
}
foo2(df, 'b')

Perhaps I could use the lazyeval package in the other question, but I'd rather know how to do it with just the tidyverse.

Body:
In this case, it is better to use ensym as we are passing a string.  Also, the ensym works with unquoted argument as well

foo2 <- function(df, var) {
   var <- ensym(var)
   df %>%
         group_by(a) %>%
         summarize(trues=sum(!!var),
                   falses=sum(! (!!var)))
  }
foo2(df, 'b')
# A tibble: 2 x 3
#      a trues falses
#* <dbl> <int>  <int>
#1     1     2      1
#2     2     1      2

foo2(df, b)
# A tibble: 2 x 3
#      a trues falses
#* <dbl> <int>  <int>
#1     1     2      1
#2     2     1      2

If the argument passed is an object, evaluate (!!) while passing into the function to avoid the literal evaluation

foo2(df, !!var)
# A tibble: 2 x 3
#      a trues falses
#* <dbl> <int>  <int>
#1     1     2      1
#2     2     1      2


问:
Select subsets from List[Int] by increasing length upto List[Int] length
I have a List of integers as:

```<code>val list= List(5,-2,10,-1,4)
</code>```

And I want the desired result as a List of following subsets from the list

```<code>List(
(5),
(5,-2),
(5,-2,10),
(5,-2,10,-1),
(5,-2,10,-1,4),
(-2,10,-1,4),
(10,-1,4),
(-1,4),
(4)
)
</code>```

How can I write a code using functional programming aspect of Scala?
Or by using any for loop constructs?

答:
As I always say, the Scaladoc is your friend.

```<code>list.toSet.subSets.map(_.toList).toList
</code>```

(Note, since this is an expressive operation, it may be better to use the Iterator that subsets returns, instead of consuming it all once into a big list of lists)

Body:
I have a List of integers as:

val list= List(5,-2,10,-1,4)

And I want the desired result as a List of following subsets from the list

List(
(5),
(5,-2),
(5,-2,10),
(5,-2,10,-1),
(5,-2,10,-1,4),
(-2,10,-1,4),
(10,-1,4),
(-1,4),
(4)
)

How can I write a code using functional programming aspect of Scala?
Or by using any for loop constructs?

Body:
As I always say, the Scaladoc is your friend.

list.toSet.subSets.map(_.toList).toList

(Note, since this is an expressive operation, it may be better to use the Iterator that subsets returns, instead of consuming it all once into a big list of lists)


问:
How to touch and hold to select text in React Native
I'm new to Android and trying to implement a rich editor using Text component of React Native.
However when I touch the text and hold for a moment, the text was not highlighted and the top bar with selection actions was not shown like what behaves in a webview or other applications.
What am I missing or do I need to implement this feature by myself? If so could you point a direction?</p>

答:
Be careful if the text is nested you should add selectable attribute to the top `

```<code><Text selectable>
    <Text>
        some selectable text
    </Text>
</Text>
</code>```

Body:
Be careful if the text is nested you should add selectable attribute to the top `

<Text selectable>
    <Text>
        some selectable text
    </Text>
</Text>


问:
Also define the standard property 'grid-row' for compatibility
I'm getting the following warning on VS Code

"Also define the standard property 'grid-row' for compatibility"

For this code:

header {
  -ms-grid-row: 1;       /* warning here */
  -ms-grid-column: 1;    /* warning here */
  -ms-grid-column-span: 2;
  grid-area: header;
}
```

How can I fix it?

答:
You can get rid of that, if you want, by setting this setting to ignore:

CSS > Lint: Vendor Prefix

```<code>  When using a vendor-specific prefix, also include the standard property.
</code>```

You are getting the warnings because you use one or more of these keys

```<code>-ms-grid-row
-ms-grid-column
</code>```

in your elements without also using the standard non-prefixed versions at the same time:

```<code>grid-row
grid-column
</code>```

So in every element where you have -ms-grid-row also include, after it in the same selector, grid-row and the same with -ms-grid-column put a grid-column after it in the same selector.  And the warnings will go away.  This is good practice anyways.  For example:

```<code>header {
  -ms-grid-row: 1;   /* warning has gone away */
  grid-row: 1;

  -ms-grid-column: 1;
  -ms-grid-column-span: 2;

  grid-column: 2;
  grid-area: header;
}
</code>```

Or set the CSS > Lint: Vendor Prefix to ignore and you won't see the warnings - but I do not recommend doing that.  You should be including the standard non-prefixed versions of those keys.

Body:
I'm getting the following warning on VS Code

"Also define the standard property 'grid-row' for compatibility"

For this code:

header {
  -ms-grid-row: 1;       /* warning here */
  -ms-grid-column: 1;    /* warning here */
  -ms-grid-column-span: 2;
  grid-area: header;
}

How can I fix it?

Body:
You can get rid of that, if you want, by setting this setting to ignore:

CSS > Lint: Vendor Prefix

  When using a vendor-specific prefix, also include the standard property.

You are getting the warnings because you use one or more of these keys

-ms-grid-row
-ms-grid-column

in your elements without also using the standard non-prefixed versions at the same time:

grid-row
grid-column

So in every element where you have -ms-grid-row also include, after it in the same selector, grid-row and the same with -ms-grid-column put a grid-column after it in the same selector.  And the warnings will go away.  This is good practice anyways.  For example:

header {
  -ms-grid-row: 1;   /* warning has gone away */
  grid-row: 1;

  -ms-grid-column: 1;
  -ms-grid-column-span: 2;

  grid-column: 2;
  grid-area: header;
}

Or set the CSS > Lint: Vendor Prefix to ignore and you won't see the warnings - but I do not recommend doing that.  You should be including the standard non-prefixed versions of those keys.


问:
Access Contents of  with Javascript
```<code><noscript><div id="example">I want to get this innerHTML</div></noscript>

<script type="text/javascript"> alert($('example').innerHTML);</script>
</code>```

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s. I'm using prototype on this particular project.

答:
From the HTML 4.0 spec:

The NOSCRIPT element allows authors to provide alternate content when a script is not executed. The content of a NOSCRIPT element should only be rendered by a script-aware user agent in the following cases:

The user agent is configured not to evaluate scripts.

The user agent doesn't support a scripting language invoked by a SCRIPT element earlier in the document.

It seems to me that this implies that the entire contents of the NOSCRIPT tag (in this case, your div) are ignored altogether if scripting is enabled in the browser.  Have you verified that the "example" div is accessible through the DOM at all in your case?

OwnerDisplayName: macinjosh

ContentLicense: CC BY-SA 2.5

Title: Access Contents of <noscript> with Javascript

Body:
I want to get this innerHTML

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s. I'm using prototype on this particular project.

OwnerDisplayName: rmz


问:
Library to parse and check Haskell code?
Is there any library in hackage that can parse haskell code and check if it is valid code or not?

I'm willing to play a bit with an evolutionary model and I want to check if produced strings of code will compile without having to write them to the disk and run the compiler.

Ideally it would be nice to be able to run the code in the strings too, but only checking the validity of the code is ok.

If you know about parser libraries (in haskell) that check for other languages (lisp, C,...)it would be nice too.

答:
For parsing Haskell code, you can use either

haskell-src

or haskell-src-exts

The latter handles all of the GHC extensions (and then some), while the former parses only Haskell 98. Here's an example of usage:

```<code>Prelude> import Language.Haskell.Exts.Parser

Prelude Language.Haskell.Exts.Parser> parseModule "main = putStrLn \"Hello\""
ParseOk (Module (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (ModuleName "Main") [] Nothing (Just [EVar (UnQual (Ident "main"))]) [] [PatBind (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (PVar (Ident "main")) Nothing (UnGuardedRhs (App (Var (UnQual (Ident "putStrLn"))) (Lit (String "Hello")))) (BDecls [])])

Prelude Language.Haskell.Exts.Parser> parseModule "main == putStrLn \"Hello\""
ParseFailed (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 25}) "TemplateHaskell is not enabled"
</code>```

Note that even if the code parses correctly, it doesn't mean it will typecheck:

```<code>Prelude Language.Haskell.Exts.Parser> parseModule "main = putStrLn2 \"Hello\""
ParseOk (Module (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (ModuleName "Main") [] Nothing (Just [EVar (UnQual (Ident "main"))]) [] [PatBind (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (PVar (Ident "main")) Nothing (UnGuardedRhs (App (Var (UnQual (Ident "putStrLn2"))) (Lit (String "Hello")))) (BDecls [])])
</code>```

So for your specific use case, it is probably better to use GHC API which also lets you typecheck parsed code, or just run ghc -c on your file.

For parsing C code, there is language-c.

If you need to parse some other language, take a look at this category on Hackage. For example, here's a parser for S-expressions.

Body:
For parsing Haskell code, you can use either

haskell-src

or haskell-src-exts

The latter handles all of the GHC extensions (and then some), while the former parses only Haskell 98. Here's an example of usage:

Prelude> import Language.Haskell.Exts.Parser

Prelude Language.Haskell.Exts.Parser> parseModule "main = putStrLn \"Hello\""
ParseOk (Module (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (ModuleName "Main") [] Nothing (Just [EVar (UnQual (Ident "main"))]) [] [PatBind (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (PVar (Ident "main")) Nothing (UnGuardedRhs (App (Var (UnQual (Ident "putStrLn"))) (Lit (String "Hello")))) (BDecls [])])

Prelude Language.Haskell.Exts.Parser> parseModule "main == putStrLn \"Hello\""
ParseFailed (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 25}) "TemplateHaskell is not enabled"

Note that even if the code parses correctly, it doesn't mean it will typecheck:

Prelude Language.Haskell.Exts.Parser> parseModule "main = putStrLn2 \"Hello\""
ParseOk (Module (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (ModuleName "Main") [] Nothing (Just [EVar (UnQual (Ident "main"))]) [] [PatBind (SrcLoc {srcFilename = "<unknown>.hs", srcLine = 1, srcColumn = 1}) (PVar (Ident "main")) Nothing (UnGuardedRhs (App (Var (UnQual (Ident "putStrLn2"))) (Lit (String "Hello")))) (BDecls [])])

So for your specific use case, it is probably better to use GHC API which also lets you typecheck parsed code, or just run ghc -c on your file.

For parsing C code, there is language-c.

If you need to parse some other language, take a look at this category on Hackage. For example, here's a parser for S-expressions.


问:
Different kernels for different features - scikit-learn SVM
I am trying to build a classifier using sklearn.svm.SVC but I would like to train the kernel separately on different subsets of features to better represent the feature space (as described here).

I have read the User Guide page and I understand that I can create kernels that are sums of individual kernels or feed into the SVC a precomputed kernel (kernel = 'precomputed'), but I do not understand how I apply different kernels to different features? Is there a way to implement this in sklearn?

I have found a way to calculate kernels in sklearn (https://scikit-learn.org/stable/modules/gaussian_process.html#gp-kernels), and so I could calculate the kernel on each set separately. However, once I output the distance matrix, I am not sure how I would use it to train the SVM.

Do I have to create a custom kernel like:

```<code>if feature == condition1:
   use kernel X
else:
   use kernel Y
</code>```

and add it to the SVM?

Or is there any other python libraries I could be using for this?

答:
You are referring to the problem of Multiple Kernel Learning (MKL). Where you can train different kernels for different groups of features. I have used this in a multi-modal case, where I wanted different kernels for image and text.

I am not sure if you actually can do it via scikit-learn.

There are some libraries provided on GitHub, for example, this one: https://github.com/IvanoLauriola/MKLpy1

Hopefully, it can help you to achieve your goal.

Body:
I am trying to build a classifier using sklearn.svm.SVC but I would like to train the kernel separately on different subsets of features to better represent the feature space (as described here).

I have read the User Guide page and I understand that I can create kernels that are sums of individual kernels or feed into the SVC a precomputed kernel (kernel = 'precomputed'), but I do not understand how I apply different kernels to different features? Is there a way to implement this in sklearn?

I have found a way to calculate kernels in sklearn (https://scikit-learn.org/stable/modules/gaussian_process.html#gp-kernels), and so I could calculate the kernel on each set separately. However, once I output the distance matrix, I am not sure how I would use it to train the SVM.

Do I have to create a custom kernel like:

if feature == condition1:
   use kernel X
else:
   use kernel Y

and add it to the SVM?

Or is there any other python libraries I could be using for this?


问:
SwiftUI double navigation bar
I am having trouble with navigation in SwiftUI. I have a button on a navigation bar, if clicked it pushes a new navigation view with list of items. When one of those items is tapped, it pushes a detail view.

But I am ending up with something like this.

Below is the code

```<code>struct FirstView: View {

   var body: some View {
       NavigationView {
           List {
            ...
           }
           .navigationBarTitle(Text("First View"))
           .navigationBarItems(trailing: MyButton())
       }
    }
}

struct MyButton: View {
    var body: some View {
        NavigationLink("SecondView", destination: SecondView())
    }
}

struct SecondView: View {
   var body: some View {
       NavigationView {
           Text("My View")
       }
   }
}
</code>```

答:
Quinn is right.
but if You don't want a big area above:

add:

```<code>struct SecondView: View {
   var body: some View {
       Text("My View")
        .navigationBarTitle("Second View", displayMode: .inline)
   }
}
</code>```

Title: SwiftUI double navigation bar

Body:
I am having trouble with navigation in SwiftUI. I have a button on a navigation bar, if clicked it pushes a new navigation view with list of items. When one of those items is tapped, it pushes a detail view.

But I am ending up with something like this.

Below is the code

struct FirstView: View {

   var body: some View {
       NavigationView {
           List {
            ...
           }
           .navigationBarTitle(Text("First View"))
           .navigationBarItems(trailing: MyButton())
       }
    }
}

struct MyButton: View {
    var body: some View {
        NavigationLink("SecondView", destination: SecondView())
    }
}

struct SecondView: View {
   var body: some View {
       NavigationView {
           Text("My View")
       }
   }
}

Body:
Quinn is right.
but if You don't want a big area above:

add:

struct SecondView: View {
   var body: some View {
       Text("My View")
        .navigationBarTitle("Second View", displayMode: .inline)
   }
}


问:
How do I combine information from multiple rows (concatrelated) without getting duplicate values in my report?
I have created a database that has these tables:

Student list

Student booklet numbers

Student needs

Teacher Information

In the Student Needs Table I have information entered similar to this:

```<code>Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary
123456             Mouse      Mickey      Extra Time
123456             Mouse      Mickey      Small group
123456             Mouse      Mickey      Type Answer Choices
654321             Duck       Daffy       Dictionary
654321             Duck       Daffy       Thesaurus
654321             Duck       Daffy       Small Group
</code>```

I need this to be pulled similar to this:

```<code>Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
</code>```

I used the concatrelated function in my report control source and it works to put all of the needs together, but because my query has the student listed multiple times, it is listing the student multiple times on the report.  Like this:

```<code>Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
</code>```

I have tried all that I can think of to fix this - to the point of exporting the report and deleting duplicates - but then the export cuts off at 255 characters- so that doesn't work.  Surely I am missing something that would be relatively easy- but I can't figure it out!

答:
Use my DJoin function and a query like this:

SELECT
    [Student Needs].[Student ID],
    [Student Needs].[Last Name],
    [Student Needs].[First Name],
    DJoin("[Reading Special Need]","[Student Needs]","[Student ID] = " & [Student ID] & "",", ") AS [Reading Special Needs]
FROM
    [Student Needs]
GROUP BY
    [Student Needs].[Student ID],
    [Student Needs].[Last Name],
    [Student Needs].[First Name];
```

Output:

Body:
I have created a database that has these tables:

Student list

Student booklet numbers

Student needs

Teacher Information

In the Student Needs Table I have information entered similar to this:

Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary
123456             Mouse      Mickey      Extra Time
123456             Mouse      Mickey      Small group
123456             Mouse      Mickey      Type Answer Choices
654321             Duck       Daffy       Dictionary
654321             Duck       Daffy       Thesaurus
654321             Duck       Daffy       Small Group

I need this to be pulled similar to this:

Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group

I used the concatrelated function in my report control source and it works to put all of the needs together, but because my query has the student listed multiple times, it is listing the student multiple times on the report.  Like this:

Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group

I have tried all that I can think of to fix this - to the point of exporting the report and deleting duplicates - but then the export cuts off at 255 characters- so that doesn't work.  Surely I am missing something that would be relatively easy- but I can't figure it out!

Body:
Use my DJoin function and a query like this:

SELECT
    [Student Needs].[Student ID],
    [Student Needs].[Last Name],
    [Student Needs].[First Name],
    DJoin("[Reading Special Need]","[Student Needs]","[Student ID] = " & [Student ID] & "",", ") AS [Reading Special Needs]
FROM
    [Student Needs]
GROUP BY
    [Student Needs].[Student ID],
    [Student Needs].[Last Name],
    [Student Needs].[First Name];

Output:


问:
Jump to a
 when a Textfield gets clicked
so i dont know how to approach it. I got my HTML

```<code><input type="text">
</code>```

Is it possible to jump to a

```<code><section>
</code>```

when i click on the textfield so the textfield jumps to the top of the screen so its easier to see?
thanks for reading

答:
I made a little example for you in codepen

//Replace something with your textfields id.
const inputTag = document.getElementById('something');
inputTag.addEventListener('click', ()=>{
  //The sections id on your page
  window.location = "#about-section";
});
```

Title: Jump to a <Section> when a Textfield gets clicked

Body:
so i dont know how to approach it. I got my HTML

<input type="text">

Is it possible to jump to a

when i click on the textfield so the textfield jumps to the top of the screen so its easier to see?
thanks for reading


问:
Azure Front Door WAF is blocking .AspNet.ApplicationCookie
I'm wondering if anyone else has had this issue with Azure Front Door and the Azure Web Application Firewall and has a solution.

The WAF is blocking simple GET requests to our ASP.NET web application.  The rule that is being triggered is DefaultRuleSet-1.0-SQLI-942440 SQL Comment Sequence Detected.

The only place that I can find an sql comment sequence is in the .AspNet.ApplicationCookie as per this truncated example: RZI5CL3Uk8cJjmX3B8S-q0ou--OO--bctU5sx8FhazvyvfAH7wH.  If I remove the 2 dashes '--' in the cookie value, the request successfully gets through the firewall.  As soon as I add them back the request gets blocked by the same firewall rule.

It seems that I have 2 options.  Disable the rule (or change it from Block to Log) which I don't want to do, or change the .AspNet.ApplicationCookie value to ensure that it does not contain any text that would trigger a firewall rule.  The cookie is generated by the Microsoft.Owin.Security.Cookies library and I'm not sure if I can change how it is generated.

答:
I ran into same problem as well.

If you have a look to the cookie value: RZI5CL3Uk8cJjmX3B8S-q0ou--OO--bctU5sx8FhazvyvfAH7wH there are two -- which is the potentially dangerous SQL command that can comment out your SQL command that you're going to query. An attacker may run their command instead of your command - after commenting out your query.

But, obviously, this cookie won't run any query on the SQL side and we are sure about that. So we can create rule exclusions that won't run specific conditions.

Go to your WAF > Click Managed Rules on the left blade > Click manage exclusions on the top > and click add

In your case, adding this rule would be fine:

Match variable: Request cookie name
Operator: Starts With
Selector: .AspNet.ApplicationCookie

However, I use Asp.Net Core 3.1 and I use Asp.Net Core Identity. I encountered other issues as well, such as __RequestVerificationToken.

Here is my full list of exclusions. I hope it helps.

PS I think there is a glitch at the moment. If you have an IP restriction on your environment, such as UAT, because of these exclusions Web Application Firewall is by-passing the IP restriction and your UAT site becomes open to the public even if you have still custom IP restriction rule on your WAF.


问:
Compiling static libs of ffmpeg with x264 in Msys2 for Visual Studio, but libx264 is never found
Having previously downloaded and compiled ffmpeg 4.2.2 to static libraries using MSYS2 and the Visual Studio 2015 x64 tool chain. I want to add the x264 codec from VLC/VideoLan, compiling that to a static library as well. However, running Configure for ffmpeg produces an error saying "libx264 not found."

I built ffmpeg without VideoLAN's x264 at "/c/ThirdParty/opt/ffmpeg-4.2.2" with "make install" installing to "/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build" .

I am using the following steps to compile from source x264 and add it to the ffmpeg build using the same VS2015 tool chain:

Launch an "VS2015 x64 Natice Tools Command Prompt"

From that VS2015 command prompt, run "c:\msys64\msys2_shell.cmd -mingw64 -use-full-path"

From inside the MSYS2 shell, run "cd /c/ThirdParty/opt"

git clone http://git.videolan.org/git/x264.git

cd x264

CC=cl ./configure --enable-static --prefix=/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build --disable-cli

make

make install

cd ../ffmpeg-4.2.2

PKG_CONFIG_PATH=/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib \
./configure --prefix=./ffmpeg_build --toolchain=msvc --arch=x86_64 \
--target-os=win64 --extra-cflags=-MT --extra-cxxflags=-MT \
--extra-ldflags=-L/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib \
--enable-x86asm --enable-asm --enable-static --disable-shared \
--disable-debug --enable-gpl --enable-avresample --enable-libx264

The steps work, compiling x264 fine, but the output for ffmpeg's Configure is "ERROR: libx264 not found".

I have also tried the variation of using these two lines in place of steps 6 and 10 above:

CC=cl ./configure --enable-static --prefix=/usr/local --disable-cli

PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH ./configure --prefix=./ffmpeg_build --toolchain=msvc --arch=x86_64 --target-os=win64 --extra-cflags=-MT  --extra-libs=/usr/local/lib/libx264.lib --extra-cxxflags=-MT --enable-x86asm --enable-asm --enable-static --disable-shared --disable-debug --enable-gpl --enable-avresample --enable-libx264

This version will get past Configure, where I am able to run "make", but the make fails with a series of unresolved X264_* functions while linking ffmpeg_g.exe, 14 unresolved functions in total. The errors at shown at the bottom, but first:

When I look in /c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib I see:

```<code>$ ls -l ./ffmpeg_build/lib
total 50988
-rw-r--r-- 1 blake blake 27184250 May 11 16:29 libavcodec.a
-rw-r--r-- 1 blake blake   231304 May 11 16:29 libavdevice.a
-rw-r--r-- 1 blake blake  8574628 May 11 16:29 libavfilter.a
-rw-r--r-- 1 blake blake  8081930 May 11 16:29 libavformat.a
-rw-r--r-- 1 blake blake  1300118 May 11 16:29 libavutil.a
-rw-r--r-- 1 blake blake    61844 May 11 16:29 libpostproc.a
-rw-r--r-- 1 blake blake   348732 May 11 16:29 libswresample.a
-rw-r--r-- 1 blake blake  1316008 May 11 16:29 libswscale.a
-rw-r--r-- 1 blake blake  5086976 May 28 18:08 libx264.lib
drwxr-xr-x 1 blake blake        0 May 28 18:08 pkgconfig
</code>```

Likewise for /c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib/pkgconfig:

```<code>$ ls -l ./ffmpeg_build/lib/pkgconfig/
total 9
-rw-r--r-- 1 blake blake 353 May 11 16:29 libavcodec.pc
-rw-r--r-- 1 blake blake 554 May 11 16:29 libavdevice.pc
-rw-r--r-- 1 blake blake 449 May 11 16:29 libavfilter.pc
-rw-r--r-- 1 blake blake 393 May 11 16:29 libavformat.pc
-rw-r--r-- 1 blake blake 306 May 11 16:29 libavutil.pc
-rw-r--r-- 1 blake blake 317 May 11 16:29 libpostproc.pc
-rw-r--r-- 1 blake blake 322 May 11 16:29 libswresample.pc
-rw-r--r-- 1 blake blake 315 May 11 16:29 libswscale.pc
-rw-r--r-- 1 blake blake 300 May 28 18:08 x264.pc
</code>```

And looking in /usr/local/lib I see libx264.lib and the pkgconfig directory.

The errors generated by my most recent attempts look like:

```<code>LD      ffmpeg_g.exe
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_default referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_parse referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_default_preset referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_apply_fastfirstpass referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_apply_profile referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_picture_init referenced in function X264_frame
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_open_160 referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_reconfig referenced in function reconfig_encoder
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_headers referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_encode referenced in function X264_frame
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_close referenced in function X264_close
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_delayed_frames referenced in function X264_frame
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_maximum_delayed_frames referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_levels referenced in function X264_init
ffmpeg_g.exe : fatal error LNK1120: 14 unresolved externals
make: *** [Makefile:111: ffmpeg_g.exe] Error 96
</code>```

Maybe something wrong with the --extra-ldflags or --extra-libs options of ffmpeg's Configure, but after trying variations and google searching, I come asking you. Do you know what is wrong with this ffmpeg Configure line? Step 10, above.

答:
Comment or remove this lines in libavcodec\libx264.c:

```<code>#if defined(_MSC_VER)
#define X264_API_IMPORTS 1
#endif
</code>```

This probably should help with your unresolved external symbol errors.
As for errors with original item 10 than you set wrong value for PKG_CONFIG_PATH pointing to lib dir instead of pkgconfig dir.

Body:
Having previously downloaded and compiled ffmpeg 4.2.2 to static libraries using MSYS2 and the Visual Studio 2015 x64 tool chain. I want to add the x264 codec from VLC/VideoLan, compiling that to a static library as well. However, running Configure for ffmpeg produces an error saying "libx264 not found."

I built ffmpeg without VideoLAN's x264 at "/c/ThirdParty/opt/ffmpeg-4.2.2" with "make install" installing to "/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build" .

I am using the following steps to compile from source x264 and add it to the ffmpeg build using the same VS2015 tool chain:

Launch an "VS2015 x64 Natice Tools Command Prompt"

From that VS2015 command prompt, run "c:\msys64\msys2_shell.cmd -mingw64 -use-full-path"

From inside the MSYS2 shell, run "cd /c/ThirdParty/opt"

git clone http://git.videolan.org/git/x264.git

cd x264

CC=cl ./configure --enable-static --prefix=/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build --disable-cli

make

make install

cd ../ffmpeg-4.2.2

PKG_CONFIG_PATH=/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib \
./configure --prefix=./ffmpeg_build --toolchain=msvc --arch=x86_64 \
--target-os=win64 --extra-cflags=-MT --extra-cxxflags=-MT \
--extra-ldflags=-L/c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib \
--enable-x86asm --enable-asm --enable-static --disable-shared \
--disable-debug --enable-gpl --enable-avresample --enable-libx264

The steps work, compiling x264 fine, but the output for ffmpeg's Configure is "ERROR: libx264 not found".

I have also tried the variation of using these two lines in place of steps 6 and 10 above:

CC=cl ./configure --enable-static --prefix=/usr/local --disable-cli

PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH ./configure --prefix=./ffmpeg_build --toolchain=msvc --arch=x86_64 --target-os=win64 --extra-cflags=-MT  --extra-libs=/usr/local/lib/libx264.lib --extra-cxxflags=-MT --enable-x86asm --enable-asm --enable-static --disable-shared --disable-debug --enable-gpl --enable-avresample --enable-libx264

This version will get past Configure, where I am able to run "make", but the make fails with a series of unresolved X264_* functions while linking ffmpeg_g.exe, 14 unresolved functions in total. The errors at shown at the bottom, but first:

When I look in /c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib I see:

$ ls -l ./ffmpeg_build/lib
total 50988
-rw-r--r-- 1 blake blake 27184250 May 11 16:29 libavcodec.a
-rw-r--r-- 1 blake blake   231304 May 11 16:29 libavdevice.a
-rw-r--r-- 1 blake blake  8574628 May 11 16:29 libavfilter.a
-rw-r--r-- 1 blake blake  8081930 May 11 16:29 libavformat.a
-rw-r--r-- 1 blake blake  1300118 May 11 16:29 libavutil.a
-rw-r--r-- 1 blake blake    61844 May 11 16:29 libpostproc.a
-rw-r--r-- 1 blake blake   348732 May 11 16:29 libswresample.a
-rw-r--r-- 1 blake blake  1316008 May 11 16:29 libswscale.a
-rw-r--r-- 1 blake blake  5086976 May 28 18:08 libx264.lib
drwxr-xr-x 1 blake blake        0 May 28 18:08 pkgconfig

Likewise for /c/ThirdParty/opt/ffmpeg-4.2.2/ffmpeg_build/lib/pkgconfig:

$ ls -l ./ffmpeg_build/lib/pkgconfig/
total 9
-rw-r--r-- 1 blake blake 353 May 11 16:29 libavcodec.pc
-rw-r--r-- 1 blake blake 554 May 11 16:29 libavdevice.pc
-rw-r--r-- 1 blake blake 449 May 11 16:29 libavfilter.pc
-rw-r--r-- 1 blake blake 393 May 11 16:29 libavformat.pc
-rw-r--r-- 1 blake blake 306 May 11 16:29 libavutil.pc
-rw-r--r-- 1 blake blake 317 May 11 16:29 libpostproc.pc
-rw-r--r-- 1 blake blake 322 May 11 16:29 libswresample.pc
-rw-r--r-- 1 blake blake 315 May 11 16:29 libswscale.pc
-rw-r--r-- 1 blake blake 300 May 28 18:08 x264.pc

And looking in /usr/local/lib I see libx264.lib and the pkgconfig directory.

The errors generated by my most recent attempts look like:

LD      ffmpeg_g.exe
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_default referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_parse referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_default_preset referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_apply_fastfirstpass referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_param_apply_profile referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_picture_init referenced in function X264_frame
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_open_160 referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_reconfig referenced in function reconfig_encoder
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_headers referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_encode referenced in function X264_frame
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_close referenced in function X264_close
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_delayed_frames referenced in function X264_frame
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_encoder_maximum_delayed_frames referenced in function X264_init
libavcodec.a(libx264.o) : error LNK2019: unresolved external symbol __imp_x264_levels referenced in function X264_init
ffmpeg_g.exe : fatal error LNK1120: 14 unresolved externals
make: *** [Makefile:111: ffmpeg_g.exe] Error 96

Maybe something wrong with the --extra-ldflags or --extra-libs options of ffmpeg's Configure, but after trying variations and google searching, I come asking you. Do you know what is wrong with this ffmpeg Configure line? Step 10, above.

Body:
Comment or remove this lines in libavcodec\libx264.c:

#if defined(_MSC_VER)
#define X264_API_IMPORTS 1
#endif

This probably should help with your unresolved external symbol errors.
As for errors with original item 10 than you set wrong value for PKG_CONFIG_PATH pointing to lib dir instead of pkgconfig dir.


问:
Time Series within R (ColumnSorting)
I have a csv of real-time data inputs with timestamps and I am looking to group these data in a time series of 30 mins for analysis.

A sample of the real-time data is

```<code>Date:
2019-06-01 08:03:04
2019-06-01 08:20:04
2019-06-01 08:33:04
2019-06-01 08:54:04
...
</code>```

I am looking to group them in a table with a step increment of 30 mins (i.e. 08:30, 09:00, etc..) to seek out the number of occurences during each period. I created a new csv file to access through R. This is so that I will not corrupt the formatting of the orginal dataset.

```<code>Date:
2019-06-01 08:00
2019-06-01 08:30
2019-06-01 09:00
2019-06-01 09:30
</code>```

I have firstly constructed a list of 30 mins intervals by:

```<code>sheet_csv$Date <- as.POSIXct(paste(sheet_csv$Date), format = "%Y-%m-%d %H:%M", tz = "GMT") #to change to POSIXct
sheet_csv$Date <- timeDate::timeSequence(from = "2019-06-01 08:00", to = "2019-12-03 09:30", by = 1800,
                           format = "%Y-%m-%d %H:%M", zone = "GMT")
</code>```

I encountered an error "Error in x[[idx]][[1]] : this S4 class is not subsettable" for this interval.

I am relatively new to R. Please do help out where you can. Greatly Appreciated.

答:
You probably don't need the timeDate package for something like this. One package that is very helpful to manipulate dates and times is lubridate - you may want to consider going forward.

I used your example and added another date/time for illustration.

To create your 30 minute intervals, you could use cut and seq.POSIXt to create a sequence of date/times with 30 minute breaks. I used your minimum date/time to start with (rounding down to nearest hour) but you can also specify another date/time here.

Use of table will give you frequencies after cut.

```<code>sheet_csv <- data.frame(
  Date = c("2019-06-01 08:03:04",
           "2019-06-01 08:20:04",
           "2019-06-01 08:33:04",
           "2019-06-01 08:54:04",
           "2019-06-01 10:21:04")
)

sheet_csv$Date <- as.POSIXct(sheet_csv$Date, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")

as.data.frame(table(cut(sheet_csv$Date,
                        breaks = seq.POSIXt(from = round(min(sheet_csv$Date), "hours"),
                                     to = max(sheet_csv$Date) + .5 * 60 * 60,
                                     by = "30 min"))))
</code>```

Output

```<code>                 Var1 Freq
1 2019-06-01 08:00:00    2
2 2019-06-01 08:30:00    2
3 2019-06-01 09:00:00    0
4 2019-06-01 09:30:00    0
5 2019-06-01 10:00:00    1
</code>```

Title: Time Series within R (ColumnSorting)

Body:
I have a csv of real-time data inputs with timestamps and I am looking to group these data in a time series of 30 mins for analysis.

A sample of the real-time data is

Date:
2019-06-01 08:03:04
2019-06-01 08:20:04
2019-06-01 08:33:04
2019-06-01 08:54:04
...

I am looking to group them in a table with a step increment of 30 mins (i.e. 08:30, 09:00, etc..) to seek out the number of occurences during each period. I created a new csv file to access through R. This is so that I will not corrupt the formatting of the orginal dataset.

Date:
2019-06-01 08:00
2019-06-01 08:30
2019-06-01 09:00
2019-06-01 09:30

I have firstly constructed a list of 30 mins intervals by:

sheet_csv$Date <- as.POSIXct(paste(sheet_csv$Date), format = "%Y-%m-%d %H:%M", tz = "GMT") #to change to POSIXct
sheet_csv$Date <- timeDate::timeSequence(from = "2019-06-01 08:00", to = "2019-12-03 09:30", by = 1800,
                           format = "%Y-%m-%d %H:%M", zone = "GMT")

I encountered an error "Error in x[[idx]][[1]] : this S4 class is not subsettable" for this interval.

I am relatively new to R. Please do help out where you can. Greatly Appreciated.

Body:
You probably don't need the timeDate package for something like this. One package that is very helpful to manipulate dates and times is lubridate - you may want to consider going forward.

I used your example and added another date/time for illustration.

To create your 30 minute intervals, you could use cut and seq.POSIXt to create a sequence of date/times with 30 minute breaks. I used your minimum date/time to start with (rounding down to nearest hour) but you can also specify another date/time here.

Use of table will give you frequencies after cut.

sheet_csv <- data.frame(
  Date = c("2019-06-01 08:03:04",
           "2019-06-01 08:20:04",
           "2019-06-01 08:33:04",
           "2019-06-01 08:54:04",
           "2019-06-01 10:21:04")
)

sheet_csv$Date <- as.POSIXct(sheet_csv$Date, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")

as.data.frame(table(cut(sheet_csv$Date,
                        breaks = seq.POSIXt(from = round(min(sheet_csv$Date), "hours"),
                                     to = max(sheet_csv$Date) + .5 * 60 * 60,
                                     by = "30 min"))))

Output

                 Var1 Freq
1 2019-06-01 08:00:00    2
2 2019-06-01 08:30:00    2
3 2019-06-01 09:00:00    0
4 2019-06-01 09:30:00    0
5 2019-06-01 10:00:00    1


问:
i'm not getting files count using in JQuery?
I'm not getting files to count using in JQuery and I'm using the below html code and jquery function

```<code>        <div class="customerimagebox">
        <input multiple="multiple" type="file" name="Update_Merchandising_to_match_AIMM_images[]" class="Update_Merchandising_to_match_AIMM_images" id="Update_Merchandising_to_match_AIMM_images">
        <i class="fa fa-camera" onclick="fileuploadonclick('Update_Merchandising_to_match_AIMM_images',event)" style="color: black;text-align: center;"></i>
        </div>
        <div class="customerimagebox">
        <input multiple="multiple" type="file" name="Employees_in_Proper_Dress_Code_images[]" class="Employees_in_Proper_Dress_Code_images" id="Employees_in_Proper_Dress_Code_images">
        <i class="fa fa-camera" onclick="fileuploadonclick('Employees_in_Proper_Dress_Code_images',event)" style="color: black;text-align: center;"></i>
        </div>

<script>
function fileuploadonclick(classname,event) {
    event.preventDefault();
    $("."+classname+"").val('').click();
    $(document).on("change","."+classname+"",function (){
        var numFiles = $("input#Update_Merchandising_to_match_AIMM_images",this)[0].files.length;
        alert(numFiles);
    });
</script>
}
</code>```

I'm only getting this error. please check the below image

答:
It works if you adjust your function like this:</p>

```<code> function fileuploadonclick(classname, event) {
    event.preventDefault();
    $("." + classname + "").val('').click();
    $(document).on("change", "." + classname + "", function() {
       var numFiles = $("input#Update_Merchandising_to_match_AIMM_images").prop("files").length;
       alert(numFiles);
    });
 }
</code>```

Body:
I'm not getting files to count using in JQuery and I'm using the below html code and jquery function

        <input multiple="multiple" type="file" name="Update_Merchandising_to_match_AIMM_images[]" class="Update_Merchandising_to_match_AIMM_images" id="Update_Merchandising_to_match_AIMM_images">

        <input multiple="multiple" type="file" name="Employees_in_Proper_Dress_Code_images[]" class="Employees_in_Proper_Dress_Code_images" id="Employees_in_Proper_Dress_Code_images">

}

I'm only getting this error. please check the below image

Body:
It works if you adjust your function like this:

 function fileuploadonclick(classname, event) {
    event.preventDefault();
    $("." + classname + "").val('').click();
    $(document).on("change", "." + classname + "", function() {
       var numFiles = $("input#Update_Merchandising_to_match_AIMM_images").prop("files").length;
       alert(numFiles);
    });
 }


问:
Can't make hidden part of a web page active using selenium in python
I'm trying to use selenium in python to extract data from AllTrails.com/us/florida/state-parks.  What I need is the recordings data.  The site looks like the picture below when you first open it, with "reviews" active.

Webpage Visual

The html code for the portion of interest is:

webpage HTML

Right now you can see in the html that 'reviews' is active (I need recordings active)

When I physically click on the "recordings" it activates recordings, but when I try to virtually "click" on it with selenium, it does not give an error, but it is not activated and subsequent parts of the code then will not work. The relevant portion of my code is below:

```<code>def get_trail_links (driver, trails_url):
    time.sleep(1)
    driver.get(trails_url)
    page_count = 0

#here is where i am trying to click on the "recordings" button, no error happens here.
    driver.find_element_by_xpath("//h3[a/@name='Recordings']").click()

    recordings = driver.find_elements_by_xpath("//*[@id ='tracks']")
    while page_count < 2:
        for record in recordings:

#here is where my button won't work because the recordings is not active in the html.

            button = driver.find_element_by_xpath("//button[@title='Show more recordings']")
            button.click()
            time.sleep(1)
            page_count += 1
</code>```

答:
Use this code. Also you can change the number of times the button click by changing the value in the while loop.

```<code>import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome(executable_path= r"D:\Selenium Learning\chromedriver_win32 (2)\chromedriver.exe")
driver.get('https://www.alltrails.com/us/florida/state-parks')

wait = WebDriverWait(driver, 5000)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class,'row trail-row')]/div/div[3]")))
driver.find_element_by_xpath("//div[contains(@class,'row trail-row')]/div/div[3]").click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='tracks']/div[1]/div[1]/div[2]/div[1]/div[1]/h4")))

page_count=0
while page_count < 2:
    button = driver.find_element_by_xpath("//button[@title='Show more recordings']")
    button.click()
    time.sleep(1)
    page_count += 1
recordings = driver.find_elements_by_xpath("//*[@id='tracks']/div/div/div/div/div/h4")
for recording in recordings:
    print(recording.text)
</code>```

PS: While executing please change the executable path to your local chrome driver path.

Body:
I'm trying to use selenium in python to extract data from AllTrails.com/us/florida/state-parks.  What I need is the recordings data.  The site looks like the picture below when you first open it, with "reviews" active.

Webpage Visual

The html code for the portion of interest is:

webpage HTML

Right now you can see in the html that 'reviews' is active (I need recordings active)

When I physically click on the "recordings" it activates recordings, but when I try to virtually "click" on it with selenium, it does not give an error, but it is not activated and subsequent parts of the code then will not work. The relevant portion of my code is below:

def get_trail_links (driver, trails_url):
    time.sleep(1)
    driver.get(trails_url)
    page_count = 0

#here is where i am trying to click on the "recordings" button, no error happens here.
    driver.find_element_by_xpath("//h3[a/@name='Recordings']").click()

    recordings = driver.find_elements_by_xpath("//*[@id ='tracks']")
    while page_count < 2:
        for record in recordings:

#here is where my button won't work because the recordings is not active in the html.

            button = driver.find_element_by_xpath("//button[@title='Show more recordings']")
            button.click()
            time.sleep(1)
            page_count += 1

Body:
Use this code. Also you can change the number of times the button click by changing the value in the while loop.

import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome(executable_path= r"D:\Selenium Learning\chromedriver_win32 (2)\chromedriver.exe")
driver.get('https://www.alltrails.com/us/florida/state-parks')

wait = WebDriverWait(driver, 5000)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class,'row trail-row')]/div/div[3]")))
driver.find_element_by_xpath("//div[contains(@class,'row trail-row')]/div/div[3]").click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='tracks']/div[1]/div[1]/div[2]/div[1]/div[1]/h4")))

page_count=0
while page_count < 2:
    button = driver.find_element_by_xpath("//button[@title='Show more recordings']")
    button.click()
    time.sleep(1)
    page_count += 1
recordings = driver.find_elements_by_xpath("//*[@id='tracks']/div/div/div/div/div/h4")
for recording in recordings:
    print(recording.text)

PS: While executing please change the executable path to your local chrome driver path.


问:
How to find the closest element to a given key value in a binary search tree?
Given a bst with integer values as keys how do I find the closest node to that key in a bst ?
The BST is represented using a object of nodes (Java). Closest will be for eg 4,5,9 and if the key is 6 it will return 5 .. </p>

答:
Traverse the tree as you would to find the element. While you do that record the value that is closest to your key. Now when you didn't find a node for the key itself return the recorded value.

So if you were looking for the key 3 in the following tree you would end up on the node 6 without finding a match but your recorded value would be 2 since this was the closest key of all nodes that you had traversed (2,7,6).

```<code>                 2
              1      7
                   6   8
</code>```

Body:
Traverse the tree as you would to find the element. While you do that record the value that is closest to your key. Now when you didn't find a node for the key itself return the recorded value.

So if you were looking for the key 3 in the following tree you would end up on the node 6 without finding a match but your recorded value would be 2 since this was the closest key of all nodes that you had traversed (2,7,6).

                 2
              1      7
                   6   8


问:
JavaScript file doesn't load after page transition (barba.js)
Everything is working fine on my index.html. On the first .onload page all the images are draggable and all over the page

HERE THE PROBLEM:

However, when I WENT TO THE PAGE ABOUT.html AND GO BACK TO THE INDEX.html my script look like isn't working anymore and I can see only one image that is not even draggable anymore.

Have a closer look to my project here:
https://codepen.io/cat999/project/editor/AEeEdg

** HOW DO I FIX ISSUE? COULD SOMEBODY HELP ME TO FIX MY CODE? **

```<code>var winWidth = window.innerWidth,
    winHeight = window.innerHeight,
    threeWinHeight = winHeight*3;

$(window).on('resize', function(){
  winHeight = window.innerHeight,
  twiceWinHeight = winHeight*2;
});

$('.shape').each(function(){
  var topPos = Math.floor(Math.random()*1300),

      //BE CAREFUL 7000px is less then total body height or  CAUSING OVERFLOW
      leftPos = Math.floor(Math.random() * winWidth);
  $(this).css('top', topPos + 'px');
  $(this).css('left', leftPos + 'px');
});

Draggable.create('.shape', {
  //type:"rotation",
  bounds: '.section-2',
  edgeResistance:0.65,
  throwProps:true,
});

var number = Math.floor((Math.random() *15) + 2);
var number2 = Math.floor((Math.random() * 0) + -15);
var number3 = Math.floor((Math.random() * 0) + 15);
var number4 = Math.floor((Math.random() * 0) + 6);
$(".shape--circle").css("transform", "rotate(" + number2 + "deg)");
$(".shape--square").css("transform", "rotate(" + number3 + "deg)");
$(".shape--circle-2").css("transform", "rotate(" + number4 + "deg)");

</code>```

Additionally, the index and the about section has using barba.js.
Here the list of my script:

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.4/TweenMax.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.4/utils/Draggable.min.js"></script>
<script type="text/javascript" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/ThrowPropsPlugin.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://unpkg.com/@barba/core"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.4/gsap.min.js"></script>
<script src="main.js"></script>
</code>```

答:
Marlene, you need to put this JS code below in a separate JS file and name it draggable.js for example and then insert a path to that JS file only into a script.src parameter that is stated in that code example above inside barba.init function.</p>

```<code>
var winWidth = window.innerWidth,
    winHeight = window.innerHeight,
    threeWinHeight = winHeight*3;

$(window).on('resize', function(){
  winHeight = window.innerHeight,
  twiceWinHeight = winHeight*2;
});

$('.shape').each(function(){
  var topPos = Math.floor(Math.random()*1300),

      //BE CAREFUL 7000px is less then total body height or  CAUSING OVERFLOW
      leftPos = Math.floor(Math.random() * winWidth);
  $(this).css('top', topPos + 'px');
  $(this).css('left', leftPos + 'px');
});

Draggable.create('.shape', {
  //type:"rotation",
  bounds: '.section-2',
  edgeResistance:0.65,
  throwProps:true,
});

var number = Math.floor((Math.random() *15) + 2);
var number2 = Math.floor((Math.random() * 0) + -15);
var number3 = Math.floor((Math.random() * 0) + 15);
var number4 = Math.floor((Math.random() * 0) + 6);
$(".shape--circle").css("transform", "rotate(" + number2 + "deg)");
$(".shape--square").css("transform", "rotate(" + number3 + "deg)");
$(".shape--circle-2").css("transform", "rotate(" + number4 + "deg)");

</code>```

Body:
Everything is working fine on my index.html. On the first .onload page all the images are draggable and all over the page

HERE THE PROBLEM:

However, when I WENT TO THE PAGE ABOUT.html AND GO BACK TO THE INDEX.html my script look like isn't working anymore and I can see only one image that is not even draggable anymore.

Have a closer look to my project here:
https://codepen.io/cat999/project/editor/AEeEdg

** HOW DO I FIX ISSUE? COULD SOMEBODY HELP ME TO FIX MY CODE? **

var winWidth = window.innerWidth,
    winHeight = window.innerHeight,
    threeWinHeight = winHeight*3;

$(window).on('resize', function(){
  winHeight = window.innerHeight,
  twiceWinHeight = winHeight*2;
});

$('.shape').each(function(){
  var topPos = Math.floor(Math.random()*1300),

      //BE CAREFUL 7000px is less then total body height or  CAUSING OVERFLOW
      leftPos = Math.floor(Math.random() * winWidth);
  $(this).css('top', topPos + 'px');
  $(this).css('left', leftPos + 'px');
});

Draggable.create('.shape', {
  //type:"rotation",
  bounds: '.section-2',
  edgeResistance:0.65,
  throwProps:true,
});

var number = Math.floor((Math.random() *15) + 2);
var number2 = Math.floor((Math.random() * 0) + -15);
var number3 = Math.floor((Math.random() * 0) + 15);
var number4 = Math.floor((Math.random() * 0) + 6);
$(".shape--circle").css("transform", "rotate(" + number2 + "deg)");
$(".shape--square").css("transform", "rotate(" + number3 + "deg)");
$(".shape--circle-2").css("transform", "rotate(" + number4 + "deg)");

Additionally, the index and the about section has using barba.js.
Here the list of my script:

Body:
Marlene, you need to put this JS code below in a separate JS file and name it draggable.js for example and then insert a path to that JS file only into a script.src parameter that is stated in that code example above inside barba.init function.

var winWidth = window.innerWidth,
    winHeight = window.innerHeight,
    threeWinHeight = winHeight*3;

$(window).on('resize', function(){
  winHeight = window.innerHeight,
  twiceWinHeight = winHeight*2;
});

$('.shape').each(function(){
  var topPos = Math.floor(Math.random()*1300),

      //BE CAREFUL 7000px is less then total body height or  CAUSING OVERFLOW
      leftPos = Math.floor(Math.random() * winWidth);
  $(this).css('top', topPos + 'px');
  $(this).css('left', leftPos + 'px');
});

Draggable.create('.shape', {
  //type:"rotation",
  bounds: '.section-2',
  edgeResistance:0.65,
  throwProps:true,
});

var number = Math.floor((Math.random() *15) + 2);
var number2 = Math.floor((Math.random() * 0) + -15);
var number3 = Math.floor((Math.random() * 0) + 15);
var number4 = Math.floor((Math.random() * 0) + 6);
$(".shape--circle").css("transform", "rotate(" + number2 + "deg)");
$(".shape--square").css("transform", "rotate(" + number3 + "deg)");
$(".shape--circle-2").css("transform", "rotate(" + number4 + "deg)");


问:
Can't get an element's value by class name with Javascript?
I have a patient number that is posted on my website coming from a Caspio database.  I want to pull this number and save it as a Javascript var patientNumber.  I have tried to do this by ClassName, ID, Name and nothing works.  I get 'undefined' returned to me.

Here is a screenshot from the Inspector screen.
https://recordit.co/MUAGMqpUgn

The HTML tag I'm targeting:

ClinicA11-PF-TR1-P1

```

<p>Here is the code I've tried.</p>

```<?php
add_action( 'wp_head', function () { ?>

<?php } );
```

答:
Your expression:

```<code>document.getElementsByClassName("dd.cbResultSetData.cbResultSetNestedAlign")
</code>```

will not select the element you are seeking. As written, it is looking for elements with:

```<code>class="dd.cbResultSetData.cbResultSetNestedAlign"
</code>```

which is not your desired element.

This expression:

```<code>document.getElementsByClassName("cbResultSetData cbResultSetNestedAlign")
</code>```

will select all elements with:

```<code>class="cbResultSetData cbResultSetNestedAlign"
</code>```

But to select the first
 element with those classes, you can use:

```<code>document.querySelector("dd.cbResultSetData.cbResultSetNestedAlign");
</code>```

which will select the first element that looks like this:

```<code><dd class="cbResultSetData cbResultSetNestedAlign">
</code>```

let dd = document.querySelector('dd.cbResultSetData.cbResultSetNestedAlign');
console.log('dd:', dd);

let results = document.getElementById('results');
results.innerHTML = dd.innerHTML;```
<pre class="snippet-code-html lang-html prettyprint-override"><code>The DD tag:<br/>
<dd class="cbResultSetData cbResultSetNestedAlign">ClinicA11-PF-TR1-P1</dd>

<br/>
Results: <span id="results"></span></code>```

Body:
I have a patient number that is posted on my website coming from a Caspio database.  I want to pull this number and save it as a Javascript var patientNumber.  I have tried to do this by ClassName, ID, Name and nothing works.  I get 'undefined' returned to me.

Here is a screenshot from the Inspector screen.
https://recordit.co/MUAGMqpUgn

The HTML tag I'm targeting:

ClinicA11-PF-TR1-P1

Here is the code I've tried.

<?php
add_action( 'wp_head', function () { ?>

<?php } );

Body:
Your expression:

document.getElementsByClassName("dd.cbResultSetData.cbResultSetNestedAlign")

will not select the element you are seeking. As written, it is looking for elements with:

class="dd.cbResultSetData.cbResultSetNestedAlign"

which is not your desired element.

This expression:

document.getElementsByClassName("cbResultSetData cbResultSetNestedAlign")

will select all elements with:

class="cbResultSetData cbResultSetNestedAlign"

But to select the first <dd> element with those classes, you can use:

document.querySelector("dd.cbResultSetData.cbResultSetNestedAlign");

which will select the first element that looks like this:

<dd class="cbResultSetData cbResultSetNestedAlign">

let dd = document.querySelector('dd.cbResultSetData.cbResultSetNestedAlign');
console.log('dd:', dd);

let results = document.getElementById('results');
results.innerHTML = dd.innerHTML;

The DD tag:<br/>
<dd class="cbResultSetData cbResultSetNestedAlign">ClinicA11-PF-TR1-P1</dd>

<br/>
Results: <span id="results"></span>


问:
What is the point of slice type in Go?
I have read this but still not fully aware of the advantage of slice against array.So I am expecting somebody in SO explain better than it and I am sure you can :)

答: I think slices and arrays are described much better and in more detail in this post on the Go Blog.</p>

Title: What is the point of slice type in Go?


问:
Splitting a single column (name) into two (forename, surname) in SQL
Currently I'm working on a database redesign project. A large bulk of this project is pulling data from the old database and importing it into the new one.

One of the columns in a table from the old database is called 'name'. It contains a forename and a surname all in one field (ugh). The new table has two columns; forenames and surname. I need to come up with a clean, efficient way to split this single column into two.

For now I'd like to do everything in the same table and then I can easily transfer it across.

3 columns:

Name (the forename and surname)

Forename (currently empty, first half of name should go here)

Surname (currently empty, second half of name should go here)

What I need to do: Split name in half and place into forename and surname

If anyone could shed some light on how to do this kind of thing I would really appreciate it as I haven't done anything like this in SQL before.

Database engine: MySQL

Storage engine: InnoDB

答:
SUBSTRING_INDEX didn't work for me in SQL 2018, so I used this:

```<code>declare @fullName varchar(50) = 'First Last1 Last2'
declare @first varchar(50)
declare @last varchar(50)

select @last = right(@fullName, len(@fullName)-charindex(' ',@fullName, 1)), @first = left(@fullName, (charindex(' ', @fullName, 1))-1);
</code>```

Yields @first = 'First', @last = 'Last1 Last2'

Body:
SUBSTRING_INDEX didn't work for me in SQL 2018, so I used this:

declare @fullName varchar(50) = 'First Last1 Last2'
declare @first varchar(50)
declare @last varchar(50)

select @last = right(@fullName, len(@fullName)-charindex(' ',@fullName, 1)), @first = left(@fullName, (charindex(' ', @fullName, 1))-1);

Yields @first = 'First', @last = 'Last1 Last2'