问:
StreamingDataflowWorker$KeyCommitTooLargeException. Commit request for stage S8 and key 8 is larger than 2GB in gcp Dataflow
Got the below error in one of the pipeline
org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker$KeyCommitTooLargeException: Commit request for stage S2 and key 8f7ac37b-b73b-4d6f-9ac5-c709ee5946d4 is larger than 2GB and cannot be processed. This may be caused by grouping a very large amount of data in a single window without using Combine, or by producing a large amount of data from a single input element.

Here is the snippet of the code:

```<code> private static String extractViewName(SyncDto json) {
    if (json.getViewName() != null) {
        return json.getViewName();
    } else if (isNotEmpty(json.getNetworkAvailabilityResponse())) {
        return json.getNetworkAvailabilityResponse().get(0).getViewName();
    } else if (isNotEmpty(json.getLocationAvailabilityResponse())) {
        return json.getLocationAvailabilityResponse().get(0).getViewName();
    }
    return null;
}
private static String getViewOrganisation(SyncDto json) {
    String viewName = extractViewName(json);
    if (viewName != null) {
        String[] splits = viewName.split(" ");
        return splits.length > 0 ? splits[0] : null;
    }
    return null;
}

private static MapElements<TryDto<SyncDto>, KV<String, TryDto<SyncDto>>> extractView() {
    return MapElements
        .into(new TypeDescriptor<KV<String, TryDto<SyncDto>>>() {
        })
        .via(tryDto -> {
            if (tryDto.isSuccess()) {
                SyncDto dto = tryDto.getTry().get();
                if (dto.getTransactionNumber() != null) {
                    return KV.of(dto.getTransactionNumber(), tryDto);
                }else {
                    log.error("TransactionNumber is null");
                }
            }
            return KV.of("unknown", tryDto);
        });
}

private PCollection<Iterable<TryDto<SyncDto>>> getViewPCollection(TupleTag<TryDto<SyncDto>> tag,
                                                                   PCollectionTuple batchesByView,long sessionMinutesDuration) {
    return batchesByView.get(tag)
        .apply("Extract " + tag.getId() + " by viewId", extractView())
        .apply("Accumulating " + tag.getId(), SyncSessionWindow.get(sessionMinutesDuration))
        .apply("Group " + tag.getId() + " by view id", GroupByKey.create())
        .apply("Extract " + tag.getId() + " Iterable value", Values.create());
}

private void tmwBopisFlow(PCollection<Iterable<TryDto<SyncDto>>> tmwBopisMessages, Integer skuFailedSyncThreshold) {
    LocationMessagesSyncCountSplitter countSplitter
        = new LocationMessagesSyncCountSplitter(TMW_BOPIS, skuFailedSyncThreshold);

    PCollectionTuple tmwBopisCounted = tmwBopisMessages.apply("Count TMW BOPIS", ParDo.of(countSplitter)
        .withOutputTags(countSplitter.getSuccessTag(), TupleTagList.of(countSplitter.getFailureTag())));

    tmwBopisCounted.get(countSplitter.getSuccessTag())
        .setCoder(TryDtoCoder.of(SerializableCoder.of(SyncDto.class)))
        .apply("Convert to model TMW BOPIS", ParDo.of(new LocationModelConverter()))
        .apply("Write to TMW BOPIS", tmwBopisSink);
</code>```

[]]1

答:
It looks like this is a case of "grouping a very large amount of data in a single window without using Combine." In your

```<code>        .apply("Extract " + tag.getId() + " Iterable value", Values.create());
</code>```

step you may have more than 2GB of values for a given key. Rather than materialize this (large) set of values, you should process them by iterating over the iterable in a DoFn. Even better if you can do a Combine.

Body:
Got the below error in one of the pipeline
org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker$KeyCommitTooLargeException: Commit request for stage S2 and key 8f7ac37b-b73b-4d6f-9ac5-c709ee5946d4 is larger than 2GB and cannot be processed. This may be caused by grouping a very large amount of data in a single window without using Combine, or by producing a large amount of data from a single input element.

Here is the snippet of the code:

 private static String extractViewName(SyncDto json) {
    if (json.getViewName() != null) {
        return json.getViewName();
    } else if (isNotEmpty(json.getNetworkAvailabilityResponse())) {
        return json.getNetworkAvailabilityResponse().get(0).getViewName();
    } else if (isNotEmpty(json.getLocationAvailabilityResponse())) {
        return json.getLocationAvailabilityResponse().get(0).getViewName();
    }
    return null;
}
private static String getViewOrganisation(SyncDto json) {
    String viewName = extractViewName(json);
    if (viewName != null) {
        String[] splits = viewName.split(" ");
        return splits.length > 0 ? splits[0] : null;
    }
    return null;
}

private static MapElements<TryDto<SyncDto>, KV<String, TryDto<SyncDto>>> extractView() {
    return MapElements
        .into(new TypeDescriptor<KV<String, TryDto<SyncDto>>>() {
        })
        .via(tryDto -> {
            if (tryDto.isSuccess()) {
                SyncDto dto = tryDto.getTry().get();
                if (dto.getTransactionNumber() != null) {
                    return KV.of(dto.getTransactionNumber(), tryDto);
                }else {
                    log.error("TransactionNumber is null");
                }
            }
            return KV.of("unknown", tryDto);
        });
}

private PCollection<Iterable<TryDto<SyncDto>>> getViewPCollection(TupleTag<TryDto<SyncDto>> tag,
                                                                   PCollectionTuple batchesByView,long sessionMinutesDuration) {
    return batchesByView.get(tag)
        .apply("Extract " + tag.getId() + " by viewId", extractView())
        .apply("Accumulating " + tag.getId(), SyncSessionWindow.get(sessionMinutesDuration))
        .apply("Group " + tag.getId() + " by view id", GroupByKey.create())
        .apply("Extract " + tag.getId() + " Iterable value", Values.create());
}

private void tmwBopisFlow(PCollection<Iterable<TryDto<SyncDto>>> tmwBopisMessages, Integer skuFailedSyncThreshold) {
    LocationMessagesSyncCountSplitter countSplitter
        = new LocationMessagesSyncCountSplitter(TMW_BOPIS, skuFailedSyncThreshold);

    PCollectionTuple tmwBopisCounted = tmwBopisMessages.apply("Count TMW BOPIS", ParDo.of(countSplitter)
        .withOutputTags(countSplitter.getSuccessTag(), TupleTagList.of(countSplitter.getFailureTag())));

    tmwBopisCounted.get(countSplitter.getSuccessTag())
        .setCoder(TryDtoCoder.of(SerializableCoder.of(SyncDto.class)))
        .apply("Convert to model TMW BOPIS", ParDo.of(new LocationModelConverter()))
        .apply("Write to TMW BOPIS", tmwBopisSink);

[]]1

Body:
It looks like this is a case of "grouping a very large amount of data in a single window without using Combine." In your

        .apply("Extract " + tag.getId() + " Iterable value", Values.create());

step you may have more than 2GB of values for a given key. Rather than materialize this (large) set of values, you should process them by iterating over the iterable in a DoFn. Even better if you can do a Combine.


来源: stackexchange

问:
Replace values in one pandas dataframe using boolean values from another dataframe?
I have two pandas dataframes, one containing data and another consisting of True/False values

iris

Sepal.Length
Sepal.Width
Petal.Length
Petal.Width
Species

5.1
3.5
1.4
0.2
setosa

4.9
3.0
1.4
0.2
setosa

4.7
3.2
1.3
0.2
setosa

iris_bool

Sepal.Length
Sepal.Width
Petal.Length
Petal.Width
Species

True
False
True
False
False

False
True
False
False
False

False
False
False
False
True

I would like to replace values in table 1 with NA/NaNs based on the corresponding boolean in table 2. Is there an easy way to do this?

答:
You can just assign</p>
```<code>iris[~iris_bool]=np.nan
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can just assign

iris[~iris_bool]=np.nan


问:
Center Image in the middle of the page
I'm attempting to place an image in the center of the page. vertically and horizontally, regardless of screen size. How is this possible?

```<code><label class="img-wrapper">
    <img src="logo.jpg">
</label>
</code>```
```<code>img {
    margin-top: 25%;
    margin-left: 25%;
    margin-right: 25%;
    margin-bottom: 25%;
    padding: 10px;
}
</code>```

Here's an image explaining what I'm trying to do. https://imgur.com/a/eVtfGdi

答:
You can easily achieve is with flexbox. Try this

.img-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="img-wrapper">
    <img src="logo.jpg">
</label></code>```

Title: Center Image in the middle of the page

Body:
I'm attempting to place an image in the center of the page. vertically and horizontally, regardless of screen size. How is this possible?

img {
    margin-top: 25%;
    margin-left: 25%;
    margin-right: 25%;
    margin-bottom: 25%;
    padding: 10px;
}

Here's an image explaining what I'm trying to do. https://imgur.com/a/eVtfGdi

Body:
You can easily achieve is with flexbox. Try this

.img-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

<label class="img-wrapper">
    <img src="logo.jpg">
</label>


问:
Xamarin Android RequestPermissions( ) doesn't work 2nd time. No permissions popup Dialog 2nd time
I am writing a Xamarin (android flavor) app, OS 12, and am trying to call ActivityCompat.RequestPermissions. Maybe I'm expecting the wrong behavior, since I'm not familiar with this stuff. I expect no matter how many times I run the app, that calling ActivityCompat.RequestPermissions( xxx, yyy, 1 ) will popup a system OS dialog box and ask the user to permit or deny the permissions I specify...

In my MainActivity for my Xamarin Forms (android) app, I correctly init Xamarin Essentials...

I override OnRequestPermissionsResult( )....

Now, in my one LoginViewModel, I call back into MainActivity (via a callback) and inside THAT callback, in MainActivity, it calls

```<code>public void Foo()
{
    foreach (string s in m_szNeededAppPermissions)
    {
        bool b = ActivityCompat.ShouldShowRequestPermissionRationale(this, s);
        System.Diagnostics.Debug.WriteLine("should show request for " + s + ", = " + b);
    }
    ActivityCompat.RequestPermissions(this, m_szNeededAppPermissions.ToArray(), 1);
}
</code>```

Not that big of a deal, right? First time I run the app, the OS dialog for allowing permissions work GREAT. Now if I press "Deny" in those permissions dialogs, I get called back with OnRequestPermissionsResult( ) and the grantResults are -1. Super, that's what I'd expect.

Now, if I stop the app debugging and run it AGAIN, the 2nd time it calls Foo( ) which calls ActivityCompat.RequestPermissions( ), I get a callback immediately with OnRequestPermissionsResult( ) with denied grantResults. No OS dialogs. If I go in and delete the app and re-start debugging, I DO get the OS permission dialogs again.

I think it's because when I say "No" to the 1st-run OS permissions dialogs, it's taking that answer as "never ask again". I think somehow the OS itself is remembering not to show the OS dialogs a 2nd time, even though i'm ASKING it to! How weird!

I think my expectations must be off, or I'm missing 1 key step. Can anybody explain why?

```<code>public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    // OS dialog ran and told us which permissions user accepted vs which ones they denied.
    // We look at them and then call back with whether they all succeeded or not.

    bool bGotAllPermissions = true;
    foreach( Permission p in grantResults )
    {
        if( p != Permission.Granted )
        {
            bGotAllPermissions = false;
            break;
        }
    }

    // ps.OnRequestPermissionsResult(bGotAllPermissions);
}
</code>```

here is the main activity:

```<code>public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ICallbackApp
{
    PermissionsService ps;
    string[] m_szNeededAppPermissions = { Manifest.Permission.AccessFineLocation, Manifest.Permission.BluetoothAdmin };

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        DependencyService.RegisterSingleton<ICallbackApp>(this);

        ps = new PermissionsService(this, m_szNeededAppPermissions);

        LoadApplication(new App());
    }
</code>```

and in the view model:

```<code>public LoginViewModel()
{
    LoginCommand = new Command(OnLoginClicked);

    // m_pCrossPlatUtils = DependencyService.Get<ICrossPlatUtils>();
    // RefreshPermissions();

    Foo();
}

public void Foo()
{
    ICallbackApp p = DependencyService.Get<ICallbackApp>();
    p.Foo();
}
</code>```

答:
Yes,in xamarin, we recommend you use Xamarin.Essentials: Permissions just as json said,which provides the ability to check and request runtime permissions.

This API uses runtime permissions on Android. Please ensure that Xamarin.Essentials is fully initialized and permission handling is setup in your app.

In the Android project's MainLauncher or any Activity that is launched Xamarin.Essentials must be initialized in the OnCreate method:

```<code>protected override void OnCreate(Bundle savedInstanceState)
{
    //...
    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle
    //...
}
</code>```

To handle runtime permissions on Android, Xamarin.Essentials must receive any OnRequestPermissionsResult. Add the following code to all Activity classes:

```<code>public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
</code>```

For more,, you can check document:https://learn.microsoft.com/en-us/xamarin/essentials/permissions?tabs=android .

Body:
I am writing a Xamarin (android flavor) app, OS 12, and am trying to call ActivityCompat.RequestPermissions. Maybe I'm expecting the wrong behavior, since I'm not familiar with this stuff. I expect no matter how many times I run the app, that calling ActivityCompat.RequestPermissions( xxx, yyy, 1 ) will popup a system OS dialog box and ask the user to permit or deny the permissions I specify...

In my MainActivity for my Xamarin Forms (android) app, I correctly init Xamarin Essentials...

I override OnRequestPermissionsResult( )....

Now, in my one LoginViewModel, I call back into MainActivity (via a callback) and inside THAT callback, in MainActivity, it calls

public void Foo()
{
    foreach (string s in m_szNeededAppPermissions)
    {
        bool b = ActivityCompat.ShouldShowRequestPermissionRationale(this, s);
        System.Diagnostics.Debug.WriteLine("should show request for " + s + ", = " + b);
    }
    ActivityCompat.RequestPermissions(this, m_szNeededAppPermissions.ToArray(), 1);
}

Not that big of a deal, right? First time I run the app, the OS dialog for allowing permissions work GREAT. Now if I press "Deny" in those permissions dialogs, I get called back with OnRequestPermissionsResult( ) and the grantResults are -1. Super, that's what I'd expect.

Now, if I stop the app debugging and run it AGAIN, the 2nd time it calls Foo( ) which calls ActivityCompat.RequestPermissions( ), I get a callback immediately with OnRequestPermissionsResult( ) with denied grantResults. No OS dialogs. If I go in and delete the app and re-start debugging, I DO get the OS permission dialogs again.

I think it's because when I say "No" to the 1st-run OS permissions dialogs, it's taking that answer as "never ask again". I think somehow the OS itself is remembering not to show the OS dialogs a 2nd time, even though i'm ASKING it to! How weird!

I think my expectations must be off, or I'm missing 1 key step. Can anybody explain why?

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    // OS dialog ran and told us which permissions user accepted vs which ones they denied.
    // We look at them and then call back with whether they all succeeded or not.

    bool bGotAllPermissions = true;
    foreach( Permission p in grantResults )
    {
        if( p != Permission.Granted )
        {
            bGotAllPermissions = false;
            break;
        }
    }

    // ps.OnRequestPermissionsResult(bGotAllPermissions);
}

here is the main activity:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ICallbackApp
{
    PermissionsService ps;
    string[] m_szNeededAppPermissions = { Manifest.Permission.AccessFineLocation, Manifest.Permission.BluetoothAdmin };

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        DependencyService.RegisterSingleton<ICallbackApp>(this);

        ps = new PermissionsService(this, m_szNeededAppPermissions);

        LoadApplication(new App());
    }

and in the view model:

public LoginViewModel()
{
    LoginCommand = new Command(OnLoginClicked);

    // m_pCrossPlatUtils = DependencyService.Get<ICrossPlatUtils>();
    // RefreshPermissions();

    Foo();
}

public void Foo()
{
    ICallbackApp p = DependencyService.Get<ICallbackApp>();
    p.Foo();
}

Body:
Yes,in xamarin, we recommend you use Xamarin.Essentials: Permissions just as json said,which provides the ability to check and request runtime permissions.

This API uses runtime permissions on Android. Please ensure that Xamarin.Essentials is fully initialized and permission handling is setup in your app.

In the Android project's MainLauncher or any Activity that is launched Xamarin.Essentials must be initialized in the OnCreate method:

protected override void OnCreate(Bundle savedInstanceState)
{
    //...
    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle
    //...
}

To handle runtime permissions on Android, Xamarin.Essentials must receive any OnRequestPermissionsResult. Add the following code to all Activity classes:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

For more,, you can check document:https://learn.microsoft.com/en-us/xamarin/essentials/permissions?tabs=android .


问:
A href pointed to nowhere added # to url
I have a href which pointed to #

```<code><a href="#" id="bla" >Bla<a>
</code>```

I have onclick function which displaying popup on click on that a href.

```<code>function doingClick()
{
   //display popup
   return false;
}
</code>```

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

答: The # is used for linking the element ID's, and will always be added to your URL when used in "empty" hrefs. What you could do, if it REALLY annoys you, is to remove it from location.href in your doingClick function

ContentLicense: CC BY-SA 3.0

Body:
I have a href which pointed to #

Bla

I have onclick function which displaying popup on click on that a href.

function doingClick()
{
   //display popup
   return false;
}

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?


问:
Change .html URL depending on the active div
I have two html pages: index1.html and index2.html. In index1.html, I have two buttons: Get Started and Login. In index2.html, I have two divs (Sign-up form and Sign-in form), and either one of them is active (by setting them with active class). The default active is the sign-up form:
...</form>, and the other form, which is for signing-in is not yet set as active:
...

Note that index2.html is a double slider page, where it does not scroll down, as the divs are positioned beside each other.

I want my Get Started button from index1.html to redirect to index2.html, but on the active Sign-up form, and I want my Login button from index1.html to redirect to index2.html, but on the active Sign-in form.

The problem is I can't redirect them on a specific active div. The URL of index2.html only goes with "index2.html?#". How do I change the URL depending on the active div? ex. index2.html#sign-up if the Sign-up form is active and index2.html?#sign-in if the Sign-in form is active.

答:
If you want the url to follow your element classes, you have to get the elements first, and then get their classes, and then check which one have active classes

```<code><div id="sign-up-form" class="form sign-up-form active">Sign Up</div>
<div id="sign-in-form" class="form sign-in-form">Sign in</div>
</code>```

Get their classes

```<code>const signInForm = document.getElementById("sign-in-form").classList
const signUpForm = document.getElementById("sign-up-form").classList
</code>```

Check which one is active

```<code>if (signInForm.contains("active")) window.location.hash = "SignIn"
if (signUpForm.contains("active")) window.location.hash = "SignUp"
</code>```

You can change the url hashtag with this window.location.hash = "new word"

Body:
If you want the url to follow your element classes, you have to get the elements first, and then get their classes, and then check which one have active classes

<div id="sign-up-form" class="form sign-up-form active">Sign Up</div>
<div id="sign-in-form" class="form sign-in-form">Sign in</div>

Get their classes

const signInForm = document.getElementById("sign-in-form").classList
const signUpForm = document.getElementById("sign-up-form").classList

Check which one is active

if (signInForm.contains("active")) window.location.hash = "SignIn"
if (signUpForm.contains("active")) window.location.hash = "SignUp"

You can change the url hashtag with this window.location.hash = "new word"


问:
Appending a cloned row of a table to a specified position on table
```<code>function CreateInterface(){
    document.getElementById("welcome").innerHTML=
       '<form action="?" method="get" onsubmit=" return validate(this)">' +
       '<table id="dataTable" summary="" cellspacing="3" cellpadding="0" border="0">' +
       '<tr id="tablerow">' + '<td><INPUT type="checkbox" name="chk"/></td> '+
       '<th>Userid   : </th>' + '<td ><input name="userid" type="text" class="text" value="" maxlength="10" /></td>' +
       '</tr>' + '<tr><td colspan="2" align="center">'+
       '<INPUT type="button" value="Add" onclick="addRow()" />' +
       '<INPUT type="button" value="Delete" onclick="delRow()" />' +
       '<input type="submit" value="submit" />'+'</td></tr>' +
       '</table>' +
       '</form>';
}

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  document.getElementById("dataTable").appendChild(clnNode);
}
</code>```

This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this

答:
try the below code. I've just tweaked your existing addRow function</p>

```<code>function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  tableObj = document.getElementById("dataTable");
  tbodyObj = document.getElementById("dataTable").getElementsByTagName('tbody')[0]
  tableObj.insertBefore(clnNode, tbodyObj)
}
</code>```

Body:
function CreateInterface(){
    document.getElementById("welcome").innerHTML=
       '<form action="?" method="get" onsubmit=" return validate(this)">' +
       '
' +
       '
' + '<INPUT type="checkbox" name="chk"/>	 '+
       'Userid   : 	' + '<input name="userid" type="text" class="text" value="" maxlength="10" />	' +
       '
' + '
'+
       '<INPUT type="button" value="Add" onclick="addRow()" />' +
       '<INPUT type="button" value="Delete" onclick="delRow()" />' +
       '<input type="submit" value="submit" />'+'
' +
       '
' +
       '</form>';
}

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  document.getElementById("dataTable").appendChild(clnNode);
}

This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this

Body:
try the below code. I've just tweaked your existing addRow function

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  tableObj = document.getElementById("dataTable");
  tbodyObj = document.getElementById("dataTable").getElementsByTagName('tbody')[0]
  tableObj.insertBefore(clnNode, tbodyObj)
}


答:
You can make use of flexbox to align elements. See the snippet below:

*{
  margin: 0;
  padding: 0;
}
.img-wrapper{
  height: 100vh;
  display: flex;
  align-items: center; /*align items vertically*/
  justify-content: center; /*align item horizontally*/
}

img {
   width: 50vh;
   height: 50vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="img-wrapper">
    <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fm.media-amazon.com%2Fimages%2FI%2F61yBDRJCKBL._SL500_.jpg&f=1&nofb=1">
</label></code>```

More on flexbox here.

Title: Center Image in the middle of the page

Body:
You can make use of flexbox to align elements. See the snippet below:

*{
  margin: 0;
  padding: 0;
}
.img-wrapper{
  height: 100vh;
  display: flex;
  align-items: center; /*align items vertically*/
  justify-content: center; /*align item horizontally*/
}

img {
   width: 50vh;
   height: 50vh;
}

<label class="img-wrapper">
    <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fm.media-amazon.com%2Fimages%2FI%2F61yBDRJCKBL._SL500_.jpg&f=1&nofb=1">
</label>

More on flexbox here.


问:
How can i create fake functions to test the components?
I have to test my component, but that component have a function for that it can work. This function need a key environment.

My component has a onMounted function

```<code> onMounted(async () => {

    const available = await getAvailableBills()
 }
</code>```

and the implementation is:

```<code>export const getAvailableBills = async () => {
  try {
    const bill = `${process.env.VAR_ENV}`
</code>```

I am getting this error:

```<code>Error: Provided address {VAR_ENV} is invalid
</code>```

But I Think I don't need to execute the real functions. I would like to create fake functions in my test

```<code>import { shallowMount } from '@vue/test-utils'
import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from '@/components/tables'

const store = createStore({
  state() {
    return {
      user: {},
    }
  },
  mutations: {},
})

let wrapper
const app = createApp(App)
app.use(store)
beforeEach(() => {
  wrapper = shallowMount(App, {
    propsData: {
      whitelist: [1,2,3],
    },
    global: {
      plugins: [store],
    },
  })
})

describe('Tables', () => {
  it('test 1', () => {
    expect(wrapper.props().list).toEqual([1,2,3])
  })
})
</code>```

答:
If you're trying to replace a function/method of your component, the short answer is: you don't!.

Never replace parts of your component in tests. The tests are there to check if your component fails, now and in the future, after you make changes to it. If you introduce a breaking change in the future, but the test replaces the part/method where you introduce the change, how will your test know the app is broken?

There are a few important principles you need to follow when testing:

Do not modify your component so it passes tests. Only modify it to fix real problems with it, found during testing.

Never replace parts of your component during testing. What you can (and should) do is mock anything external to it, replacing those parts with functions/modules performing what you expect those parts to do in a live environment 1. The gist of a mock is:

jest.mock('some-module', () => jest.fn().mockImplementation(() => yourMock )).

Full docs here.

Mocking needs to happen before your test calls import Something from 'some-module'.

Only test inputs/outputs of your component. Don't test how your component does it (a.k.a internal implementation) (this allows you to refactor it at some later point without breaking the test, as long as your component still outputs as expected for each provided input).

Also don't test if external stuff works. Your test is not concerned with that. External stuff has its own tests and is, typically, already tested. That's why you rely on it.

So, in your case, you want to modify process.env during the test. The only problem is process.env is global and if you make changes to it, those changes will persist after your test ends, unless you change everything back to how it was when you started the test.

Most importantly, you have to call jest.resetModules() before each test, to clear jest cache (by default, jest caches, so it runs tests faster).

Here's an example of how to test with controlled process.env. This should eliminate the need to replace the components' method:

```<code>describe('SomeComponent', () => {
  const REAL_ENV = process.env;

  beforeEach(() => {
    jest.resetModules();
    process.env = { ...process.env }; // copy, for your test
  });

  afterAll(() => {
    process.env = REAL_ENV; // restore initial values
  });

  it('should do stuff depending on process.env', () => {
    process.env.FOO = 'bar';

    wrapper = shallowMount(/*...*/);
    expect(/* wrapper to do stuff...*/)
  })
});
</code>```

Testing with controlled process.env values needs shallow mounting inside the test, rather than the typical shallow mounting in beforeAll, I normally create two separate testing suites: one for normal tests, shallow mounting in beforeAll, and one for special tests, which set up environment vars before shallow mounting:

```<code>describe('SomeComponent - normal tests', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallowMount(/*...*/)
  });
  it('should do stuff', () => {
    // component here has already been shallowMounted
  })
});

describe('SomeCompoent - process.env tests', () => {
  const REAL_ENV = process.env;
  let wrapper;

  beforeEach(/* ... */); // replace process.env
  afterEach(/* ... */); // restore process.env

  it('Does stuff with FOO = "bar"', () => {
    process.env.FOO = 'bar';
    wrapper = shallowMount(/* ... */);
    expect(/* wrapper to do stuff when process.env.FOO is 'bar' */)
  })

  it('Does stuff with FOO = "baz"', () => {
    process.env.FOO = 'baz';
    wrapper = shallowMount(/* ... */);
    expect(/* wrapper to do stuff when process.env.FOO is 'baz' */)
  })
})
</code>```

1 As an example, you don't want to use axios in your tests.  You don't want to test if the local machine is connected to the internet or if the servers your app is calling are actually up and running. You want a replacement for axios which does what axios is doing without making actual calls, allowing you to control the responses and errors returned, thus testing your component makes the correct calls and behaves as expected when receiving responses/errors from axios.

Body:
I have to test my component, but that component have a function for that it can work. This function need a key environment.

My component has a onMounted function

 onMounted(async () => {

    const available = await getAvailableBills()
 }

and the implementation is:

export const getAvailableBills = async () => {
  try {
    const bill = `${process.env.VAR_ENV}`

I am getting this error:

Error: Provided address {VAR_ENV} is invalid

But I Think I don't need to execute the real functions. I would like to create fake functions in my test

import { shallowMount } from '@vue/test-utils'
import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from '@/components/tables'

const store = createStore({
  state() {
    return {
      user: {},
    }
  },
  mutations: {},
})

let wrapper
const app = createApp(App)
app.use(store)
beforeEach(() => {
  wrapper = shallowMount(App, {
    propsData: {
      whitelist: [1,2,3],
    },
    global: {
      plugins: [store],
    },
  })
})

describe('Tables', () => {
  it('test 1', () => {
    expect(wrapper.props().list).toEqual([1,2,3])
  })
})

Body:
If you're trying to replace a function/method of your component, the short answer is: you don't!.

Never replace parts of your component in tests. The tests are there to check if your component fails, now and in the future, after you make changes to it. If you introduce a breaking change in the future, but the test replaces the part/method where you introduce the change, how will your test know the app is broken?

There are a few important principles you need to follow when testing:

Do not modify your component so it passes tests. Only modify it to fix real problems with it, found during testing.

Never replace parts of your component during testing. What you can (and should) do is mock anything external to it, replacing those parts with functions/modules performing what you expect those parts to do in a live environment 1. The gist of a mock is:

jest.mock('some-module', () => jest.fn().mockImplementation(() => yourMock )).

Full docs here.

Mocking needs to happen before your test calls import Something from 'some-module'.

Only test inputs/outputs of your component. Don't test how your component does it (a.k.a internal implementation) (this allows you to refactor it at some later point without breaking the test, as long as your component still outputs as expected for each provided input).

Also don't test if external stuff works. Your test is not concerned with that. External stuff has its own tests and is, typically, already tested. That's why you rely on it.

So, in your case, you want to modify process.env during the test. The only problem is process.env is global and if you make changes to it, those changes will persist after your test ends, unless you change everything back to how it was when you started the test.

Most importantly, you have to call jest.resetModules() before each test, to clear jest cache (by default, jest caches, so it runs tests faster).

Here's an example of how to test with controlled process.env. This should eliminate the need to replace the components' method:

describe('SomeComponent', () => {
  const REAL_ENV = process.env;

  beforeEach(() => {
    jest.resetModules();
    process.env = { ...process.env }; // copy, for your test
  });

  afterAll(() => {
    process.env = REAL_ENV; // restore initial values
  });

  it('should do stuff depending on process.env', () => {
    process.env.FOO = 'bar';

    wrapper = shallowMount(/*...*/);
    expect(/* wrapper to do stuff...*/)
  })
});

Testing with controlled process.env values needs shallow mounting inside the test, rather than the typical shallow mounting in beforeAll, I normally create two separate testing suites: one for normal tests, shallow mounting in beforeAll, and one for special tests, which set up environment vars before shallow mounting:

describe('SomeComponent - normal tests', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallowMount(/*...*/)
  });
  it('should do stuff', () => {
    // component here has already been shallowMounted
  })
});

describe('SomeCompoent - process.env tests', () => {
  const REAL_ENV = process.env;
  let wrapper;

  beforeEach(/* ... */); // replace process.env
  afterEach(/* ... */); // restore process.env

  it('Does stuff with FOO = "bar"', () => {
    process.env.FOO = 'bar';
    wrapper = shallowMount(/* ... */);
    expect(/* wrapper to do stuff when process.env.FOO is 'bar' */)
  })

  it('Does stuff with FOO = "baz"', () => {
    process.env.FOO = 'baz';
    wrapper = shallowMount(/* ... */);
    expect(/* wrapper to do stuff when process.env.FOO is 'baz' */)
  })
})

1 As an example, you don't want to use axios in your tests.  You don't want to test if the local machine is connected to the internet or if the servers your app is calling are actually up and running. You want a replacement for axios which does what axios is doing without making actual calls, allowing you to control the responses and errors returned, thus testing your component makes the correct calls and behaves as expected when receiving responses/errors from axios.


问:
How to find all instances of URLs with a particular domain in a freetext field in MySQL?
I have a MySQL DB, and a free text field which has a bunch of free text, and potentially URLs in it.

I would like to be able to find URLs that start with "https://hotspot.com", get the full URL, and any instances within the content. For example if we have 3 urls in the same field, I would like to get all 3 of them.

The table would look like:

```<code>CREATE TABLE IF NOT EXISTS `sample` (
  `id` int(6) unsigned NOT NULL,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `sample` (`id`, `content`) VALUES
  ('1', 'chimichangas and stuff https://hotspot.com/files/filename.pdf'),
  ('2', 'One hundred angels can dance on the head of a pin'),
  ('3', 'The last unihorn https://hotspot.com/files/anotherfile.pdf and its so cool https://hotspot.com/files/morefile.png'),
  ('4', 'The earth is like a ball. https://yahoo.com/files/filename/pdf');
</code>```

And I would like to get something like

1, https://hotspot.com/files/filename.pdf

3, https://hotspot.com/files/anotherfile.pdf

3, https://hotspot.com/files/morefile.png

(The id of the content, and the URLs it found in it. Although the format does not matter much as long as I get the info)
I was trying to get it with substring_index following some examples I found. But I am not sure I understand them. For example: Extract multiple URL of Text from MySQL column

答:
Your attempt at REGEXP_SUBSTR works. I don't know why it returns 0 rows, but here's my working example, I just take yours and change a little:

```<code>SELECT
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,1),
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,2),
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,3),
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,4)
FROM sample
</code>```

Result:

col1
col2
col3
col4

https://hotspot.com/files/filename.pdf
NULL
NULL    NULL

NULL
NULL
NULL
NULL

https://hotspot.com/files/anotherfile.pdf
https://hotspot.com/files/morefile.png
NULL
NULL

NULL
NULL
NULL
NULL

Explanation:

REGEXP_SUBSTR arguments are

string to be matched

regex pattern

starting index

index of occurrence

by selecting 1-4 index of occurrence we can capture up to 4 url in a single row

If you expect there is more, you can just add more columns

What I changed:

before:

(https?:\/\/(.+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[]@!$&'()*\+,;\=]*)?)

after:

(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)

I just changed your (.+?\.)? into ([A-Za-z0-9]+?\.)? to prevent greedy matching all when there's multiple url in one string (I guess this capture group is for matching subdomains of hotspot.com)

Body:
I have a MySQL DB, and a free text field which has a bunch of free text, and potentially URLs in it.

I would like to be able to find URLs that start with "https://hotspot.com", get the full URL, and any instances within the content. For example if we have 3 urls in the same field, I would like to get all 3 of them.

The table would look like:

CREATE TABLE IF NOT EXISTS `sample` (
  `id` int(6) unsigned NOT NULL,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `sample` (`id`, `content`) VALUES
  ('1', 'chimichangas and stuff https://hotspot.com/files/filename.pdf'),
  ('2', 'One hundred angels can dance on the head of a pin'),
  ('3', 'The last unihorn https://hotspot.com/files/anotherfile.pdf and its so cool https://hotspot.com/files/morefile.png'),
  ('4', 'The earth is like a ball. https://yahoo.com/files/filename/pdf');

And I would like to get something like

1, https://hotspot.com/files/filename.pdf

3, https://hotspot.com/files/anotherfile.pdf

3, https://hotspot.com/files/morefile.png

(The id of the content, and the URLs it found in it. Although the format does not matter much as long as I get the info)
I was trying to get it with substring_index following some examples I found. But I am not sure I understand them. For example: Extract multiple URL of Text from MySQL column

Body:
Your attempt at REGEXP_SUBSTR works. I don't know why it returns 0 rows, but here's my working example, I just take yours and change a little:

SELECT
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,1),
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,2),
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,3),
REGEXP_SUBSTR(content,'(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)',1,4)
FROM sample

Result:

col1
col2
col3
col4

https://hotspot.com/files/filename.pdf
NULL
NULL    NULL

NULL
NULL
NULL
NULL

https://hotspot.com/files/anotherfile.pdf
https://hotspot.com/files/morefile.png
NULL
NULL

NULL
NULL
NULL
NULL

Explanation:

REGEXP_SUBSTR arguments are

string to be matched

regex pattern

starting index

index of occurrence

by selecting 1-4 index of occurrence we can capture up to 4 url in a single row

If you expect there is more, you can just add more columns

What I changed:

before:

(https?:\/\/(.+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[]@!$&'()*\+,;\=]*)?)

after:

(https?:\/\/([A-Za-z0-9]+?\.)?hotspot\.com(\/[A-Za-z0-9\-\._~:\/\?#[@\]!$&()*\+,;\=]*)?)

I just changed your (.+?\.)? into ([A-Za-z0-9]+?\.)? to prevent greedy matching all when there's multiple url in one string (I guess this capture group is for matching subdomains of hotspot.com)


问:
Get branch on Origin not on local
I ran in to a situation where I was working on two separate machines and ended up with the following:

Laptop A:

main

branch_a

branch_b

Laptop B:

main

branch_c

Origin:

main

branch_a

branch_b

branch_c

I am now done working on Laptop B and will continue working on Laptop A. How do I go about getting just branch_c locally on to my Laptop A and then working from there only?

答:
Solving this "properly" (for whatever definition you want to use for "properly") requires understanding Git's names.  Branch names are just a specific subset of Git's names, which also include tag names, remote-tracking names, replacement names, internal names for bisection, and many others.

These names exist—or mostly exist, depending on whose definition you use—as one or another form of reference or ref.  A ref is, or mostly is, a name that starts with refs/ and goes on to include another component, such as stash or heads/ or tags/ and so on.  Each slash separates a component, much as with a Unix/Linux style path name: the only thing that's special here is that all of these refs start with refs/.

The exception, if you choose to define it this way—some parts of Git do and some don't—is that there are some special refs like HEAD, MERGE_HEAD, CHERRY_PICK_HEAD, and so on, that don't start with refs/.  Some Git documentation considers these ordinary refs, and some doesn't, but the important thing is that they do exist yet don't start with refs/.  Only the ones that do start with refs/, plus the special name HEAD, are allowed to "escape" from your Git repository to be seen by some other Git repository.

In other words, every Git repository has its own set of refs.  But, when you connect one Git repository to another Git repository—which you do with git fetch or git push—you may allow your names to be seen by the other Git repository, and the other Git repository may allow its names to be seen by your Git repository.

Meanwhile, each name stores one hash ID.  That's what they're good for: storing one hash ID.  Git needs the hash IDs to find commits.  Git does not need the names!  It only needs the hash IDs.  If you can supply the hash ID, without the name, that's sufficient.

You should thus hold the following picture in your head

Each Git repository has:

commits, which have hash IDs;

some names—i.e., refs—that let you, a human, tell Git a hash ID without you having to memorize the hash IDs yourself.

When you use git push or git fetch, or git pull which starts by running git fetch, you are telling your Git to connect to another Git repository.  That other Git repository also has commits (which have hash IDs) and names.  Your Git may look at their names and get commits from them—that's the git fetch operation—or may send commits to them and ask them to set some of their names: that's the git push operation.

Those names that start with refs/heads/ are branch names, and these are the names you use most often.  Git allows you (the human) to leave off the refs/heads/ part, and will stick that part on automatically as needed to find the commit locally.  You can explicitly write out refs/heads/ to force Git to use something as a branch name, if needed, but usually we just let Git do its thing and are lazy and type in main and not refs/heads/main.

Fetch and push are different

When you use git push, you will run it like this at least once:

```<code>git push -u origin somebranch
</code>```

The origin here is the name you are using to store a URL, by which your Git can call up some other Git repository over the Internet.  The somebranch part is short for refs/heads/somebranch: we let Git fill in the refs/heads/ for us.

Your Git uses this to find your latest commit for your somebranch branch.  Your Git then makes sure their Git repository has this commit and all the commits needed to lead up to that commit too, and then—once your Git is sure they have them, first sending over those commits and anything else needed—your Git will ask their Git to create or update their refs/heads/somebranch name.  That way, your Git and their Git will both have branches named somebranch, and both branch names will refer to the same commit.

It's the commits that matter to Git—not the branch names, just the commits!  The branch names only matter to humans.  But we want Git to serve us, not the other way around, so we want the branch names to match too.

Once you've done one git push -u like this, you can just run:

```<code>git push
</code>```

Your Git will figure out that your current branch is somebranch, and use its upstream setting—that's what the -u is for with git push -u origin somebranch, to set the upstream setting—to do git push origin somebranch for you.  Sometimes, creating a branch name in your repository automatically sets its upstream and then you can use git push without the -u.  Sometimes it doesn't, and you need the git push -u, or git branch --set-upstream-to, or some other method to set the branch's upstream.

But git fetch is different!  When you run git fetch you should usually just run it by itself, or with the name of the remote origin:

```<code>git fetch origin
</code>```

This has your Git call up the other Git repository, using the URL stored under the name origin as before.  But this time your Git is getting stuff from them.  Your Git asks them to list out all their branch names.  They do that, and then your Git takes each of their names and changes them.  Your Git turns their main—which is, strictly speaking, refs/heads/main—and turns that into your origin/main, which is short for refs/remotes/origin/main.  Your Git turns their branch_a, if they have one, into origin/branch_a.  This repeats for every branch name they have: every one of their refs/heads/* names becomes a refs/remotes/origin/* name.

Having made these changes, your Git also gets from them any commits they have, that you don't, that you'll need to create-or-update all your refs/remotes/origin/* names.  And, once you have all these commits and supporting objects, your Git will then create or update all these names.

These refs/remotes/origin/* names—which your Git lets you abbreviate as origin/main and so on—are your remote-tracking names for the remote named origin.  Because they include the word origin in their name, they're separate from any other remote-tracking names.

Adding more remotes

This separation means you can add more remotes.  Running:

```<code>git remote add computer1 <url>
</code>```

allows you to run:

```<code>git fetch computer1
</code>```

(assuming there's some URL by which your current computer—computer0?—can reach computer1).  That will let your Git get, from "their" (your-on-computer1) Git repository, all of their commits and all of their branch names.  Your Git will now create-or-update refs/remotes/computer1/* in your repository.

What if you can't log in from one of your computers to another?

What if you can't actually log in to your laptop-A to your laptop-B?  For instance, if they're both running Windows, they probably have no server-like capabilities.1  In this case, you'll need to use git push from the laptop that has the branch name, to send the branch to some hosting server that both laptops can reach.  This will also send any commits needed.

Then, once the commits and branch name exist where you can get them, you run git fetch to there.  That gets the commits and creates a remote-tracking name, such as origin/branch_c or laptopB/branch_c, locally.  Now you have a remote-tracking name on laptop A that finds the right commit, which you also have on laptop A.  So now you can create a branch name on laptop A:

```<code>git branch branch_c origin/branch_c
</code>```

for instance.

If you were able to start sshd directly on laptopB and created a laptopB remote and ran git fetch laptopB to get laptopB/branch_c on laptop A, you can run:

```<code>git branch branch_a laptopB/branch_c
</code>```

for instance.

Note that these git branch commands create branch_c locally, here on laptop A, with an upstream set.  The upstream that is set is origin/branch_c or laptopB/branch_c, whatever your second argument was.  If you want to change the upstream, just remember to run git push -u later as needed.  The -u option tells git push: If this push works, please run git branch --set-upstream-to for me, with the arguments to the git branch --set-upstream-to command setting the upstream of the current branch to whatever branch you just created-or-updated on whichever remote you just pushed-to.

1If they're both running Linux, or even just one of them is, you can start up an sshd on the Linux laptops and use ssh access, which will usually be the way to do what you want.

Title: Get branch on Origin not on local

Body:
Solving this "properly" (for whatever definition you want to use for "properly") requires understanding Git's names.  Branch names are just a specific subset of Git's names, which also include tag names, remote-tracking names, replacement names, internal names for bisection, and many others.

These names exist—or mostly exist, depending on whose definition you use—as one or another form of reference or ref.  A ref is, or mostly is, a name that starts with refs/ and goes on to include another component, such as stash or heads/ or tags/ and so on.  Each slash separates a component, much as with a Unix/Linux style path name: the only thing that's special here is that all of these refs start with refs/.

The exception, if you choose to define it this way—some parts of Git do and some don't—is that there are some special refs like HEAD, MERGE_HEAD, CHERRY_PICK_HEAD, and so on, that don't start with refs/.  Some Git documentation considers these ordinary refs, and some doesn't, but the important thing is that they do exist yet don't start with refs/.  Only the ones that do start with refs/, plus the special name HEAD, are allowed to "escape" from your Git repository to be seen by some other Git repository.

In other words, every Git repository has its own set of refs.  But, when you connect one Git repository to another Git repository—which you do with git fetch or git push—you may allow your names to be seen by the other Git repository, and the other Git repository may allow its names to be seen by your Git repository.

Meanwhile, each name stores one hash ID.  That's what they're good for: storing one hash ID.  Git needs the hash IDs to find commits.  Git does not need the names!  It only needs the hash IDs.  If you can supply the hash ID, without the name, that's sufficient.

You should thus hold the following picture in your head

Each Git repository has:

commits, which have hash IDs;

some names—i.e., refs—that let you, a human, tell Git a hash ID without you having to memorize the hash IDs yourself.

When you use git push or git fetch, or git pull which starts by running git fetch, you are telling your Git to connect to another Git repository.  That other Git repository also has commits (which have hash IDs) and names.  Your Git may look at their names and get commits from them—that's the git fetch operation—or may send commits to them and ask them to set some of their names: that's the git push operation.

Those names that start with refs/heads/ are branch names, and these are the names you use most often.  Git allows you (the human) to leave off the refs/heads/ part, and will stick that part on automatically as needed to find the commit locally.  You can explicitly write out refs/heads/ to force Git to use something as a branch name, if needed, but usually we just let Git do its thing and are lazy and type in main and not refs/heads/main.

Fetch and push are different

When you use git push, you will run it like this at least once:

git push -u origin somebranch

The origin here is the name you are using to store a URL, by which your Git can call up some other Git repository over the Internet.  The somebranch part is short for refs/heads/somebranch: we let Git fill in the refs/heads/ for us.

Your Git uses this to find your latest commit for your somebranch branch.  Your Git then makes sure their Git repository has this commit and all the commits needed to lead up to that commit too, and then—once your Git is sure they have them, first sending over those commits and anything else needed—your Git will ask their Git to create or update their refs/heads/somebranch name.  That way, your Git and their Git will both have branches named somebranch, and both branch names will refer to the same commit.

It's the commits that matter to Git—not the branch names, just the commits!  The branch names only matter to humans.  But we want Git to serve us, not the other way around, so we want the branch names to match too.

Once you've done one git push -u like this, you can just run:

git push

Your Git will figure out that your current branch is somebranch, and use its upstream setting—that's what the -u is for with git push -u origin somebranch, to set the upstream setting—to do git push origin somebranch for you.  Sometimes, creating a branch name in your repository automatically sets its upstream and then you can use git push without the -u.  Sometimes it doesn't, and you need the git push -u, or git branch --set-upstream-to, or some other method to set the branch's upstream.

But git fetch is different!  When you run git fetch you should usually just run it by itself, or with the name of the remote origin:

git fetch origin

This has your Git call up the other Git repository, using the URL stored under the name origin as before.  But this time your Git is getting stuff from them.  Your Git asks them to list out all their branch names.  They do that, and then your Git takes each of their names and changes them.  Your Git turns their main—which is, strictly speaking, refs/heads/main—and turns that into your origin/main, which is short for refs/remotes/origin/main.  Your Git turns their branch_a, if they have one, into origin/branch_a.  This repeats for every branch name they have: every one of their refs/heads/* names becomes a refs/remotes/origin/* name.

Having made these changes, your Git also gets from them any commits they have, that you don't, that you'll need to create-or-update all your refs/remotes/origin/* names.  And, once you have all these commits and supporting objects, your Git will then create or update all these names.

These refs/remotes/origin/* names—which your Git lets you abbreviate as origin/main and so on—are your remote-tracking names for the remote named origin.  Because they include the word origin in their name, they're separate from any other remote-tracking names.

Adding more remotes

This separation means you can add more remotes.  Running:

git remote add computer1 <url>

allows you to run:

git fetch computer1

(assuming there's some URL by which your current computer—computer0?—can reach computer1).  That will let your Git get, from "their" (your-on-computer1) Git repository, all of their commits and all of their branch names.  Your Git will now create-or-update refs/remotes/computer1/* in your repository.

What if you can't log in from one of your computers to another?

What if you can't actually log in to your laptop-A to your laptop-B?  For instance, if they're both running Windows, they probably have no server-like capabilities.1  In this case, you'll need to use git push from the laptop that has the branch name, to send the branch to some hosting server that both laptops can reach.  This will also send any commits needed.

Then, once the commits and branch name exist where you can get them, you run git fetch to there.  That gets the commits and creates a remote-tracking name, such as origin/branch_c or laptopB/branch_c, locally.  Now you have a remote-tracking name on laptop A that finds the right commit, which you also have on laptop A.  So now you can create a branch name on laptop A:

git branch branch_c origin/branch_c

for instance.

If you were able to start sshd directly on laptopB and created a laptopB remote and ran git fetch laptopB to get laptopB/branch_c on laptop A, you can run:

git branch branch_a laptopB/branch_c

for instance.

Note that these git branch commands create branch_c locally, here on laptop A, with an upstream set.  The upstream that is set is origin/branch_c or laptopB/branch_c, whatever your second argument was.  If you want to change the upstream, just remember to run git push -u later as needed.  The -u option tells git push: If this push works, please run git branch --set-upstream-to for me, with the arguments to the git branch --set-upstream-to command setting the upstream of the current branch to whatever branch you just created-or-updated on whichever remote you just pushed-to.

1If they're both running Linux, or even just one of them is, you can start up an sshd on the Linux laptops and use ssh access, which will usually be the way to do what you want.


问:
Filter dataframe based on matching values from two columns
I have a dataframe like as shown below

```<code>cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,2,3,0,0]})
</code>```

I would like to filter the dataframe based on the below criteria

```<code>cdf['Id']==cdf['Label']  # first 3 rows are matching for both columns in cdf
</code>```

I tried the below

```<code>flag = np.where[cdf['Id'].eq(cdf['Label'])==True,1,0]
final_df = cdf[cdf['flag']==1]
</code>```

but I got the below error

TypeError: 'function' object is not subscriptable

I expect my output to be like as shown below

```<code>     Id Label
0    1   1
1    2   2
2    3   3
</code>```

答:
I think you're overthinking this. Just compare the columns:

```<code>>>> cdf[cdf['Id'] == cdf['Label']]
   Id  Label
0   1      1
1   2      2
2   3      3
</code>```

Your particular error though is coming from the fact that you're using square brackets to call np.where, e.g. np.where[...], which is wrong. You should be using np.where(...) instead, but the above solution is bound to be as fast as it gets ;)

Body:
I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,2,3,0,0]})

I would like to filter the dataframe based on the below criteria

cdf['Id']==cdf['Label']  # first 3 rows are matching for both columns in cdf

I tried the below

flag = np.where[cdf['Id'].eq(cdf['Label'])==True,1,0]
final_df = cdf[cdf['flag']==1]

but I got the below error

TypeError: 'function' object is not subscriptable

I expect my output to be like as shown below

     Id Label
0    1   1
1    2   2
2    3   3

Body:
I think you're overthinking this. Just compare the columns:

>>> cdf[cdf['Id'] == cdf['Label']]
   Id  Label
0   1      1
1   2      2
2   3      3

Your particular error though is coming from the fact that you're using square brackets to call np.where, e.g. np.where[...], which is wrong. You should be using np.where(...) instead, but the above solution is bound to be as fast as it gets ;)


问:
Dynamically Change Pulumi Aws Az For multiple EC2 in same python file

server = aws.ec2.Instance(
   'rumbleInstance2',
   instance_type=size,
   vpc_security_group_ids=[group.id],
   region="Whateever region i want"
)
```

Some option that i can think of are overloading provider function (i am not sure if i am doing it right)

答:
import pulumi_aws as aws

available = aws.get_availability_zones(state="available")
primary = aws.ec2.Subnet("primary", availability_zone=available.names[0])

server = aws.ec2.Instance(
   'rumbleInstance2',
   instance_type=size,
   vpc_security_group_ids=[group.id],
   region="Whateever region i want",
   availabilityZone=primary
)
```

Body:
server = aws.ec2.Instance(
   'rumbleInstance2',
   instance_type=size,
   vpc_security_group_ids=[group.id],
   region="Whateever region i want"
)

Some option that i can think of are overloading provider function (i am not sure if i am doing it right)


问:
Remove mobile phone number or Update mobile phone number with empty string using microsoft graph api
I am using Microsoft graph API and using 'users' resource. Endpoint is https://graph.microsoft.com/v1.0/users. I am able to create user and update user's related field. Now I am trying to remove "mobilephone" number so, I sent empty string as a request info. but I am getting the following error.

Invalid value specified for property 'mobilePhone' of resource 'User'. "The mobilePhone should be between 1 and 64 characters.

Can I set empty string value to that field? How can I remove that field's value?

答:
phoneNumber.replaceAll("[\\s\\-()]");
```

The regular expression defines a character class consisting of any whitespace character (\s, which is escaped as \\s because we're passing in a String)

Check String.replaceAll(String, String).

Body:
phoneNumber.replaceAll("[\\s\\-()]");

The regular expression defines a character class consisting of any whitespace character (\s, which is escaped as \\s because we're passing in a String)

Check String.replaceAll(String, String).


问:
Convert IEnumerable<Dictionary<int, string>> to List<Dictionary<int, string>>
```<code>var a = GetIEnumerableDictionary();
</code>```

a is IEnumerable<Dictionary<int, string>>.
How do I convert a to List<Dictionary<int, string>> ?

答:
a.ToList() should do the trick.

The ToList() extension method lives  in the System.Linq namespace.  If Linq is not available, the List<T> constructor takes an IEnumerable<T> as a parameter, as Jalal has already answered on this page.

Body:
var a = GetIEnumerableDictionary();

a is IEnumerable<Dictionary<int, string>>.
How do I convert a to List<Dictionary<int, string>> ?


问:
Specify tsconfig.json location for Cypress
I'm trying to use Cypress w/ Typescript but Cypress can't find the tsconfig.json file I've created for it. I also have a custom directory structure (because I hate when there's a bunch of config files in the root, so I put them in a config directory).

Project Directory Structure

/
├── package.json
├── configs/
│   ├── cypress.json
├── src/
│   ├── cypress/
│   │   ├── tsconfig.json
```
<p><strong>Cypress Open command</strong></p>
<pre class="lang-js prettyprint-override"><code>//  package.json

"scripts": {
    "cypress:open": "cypress open --config-file configs/cypress.json"
},
</code>```

In the script above, the --config-file flag tells cypress the location of the cypress.json config file, which is AWESOME because I can put that file anywhere I want it. However, now I need to instruct Cypress on where to find it's tsconfig.json file.

/configs/cypress.json (tells Cypress where the cypress/ directory is)

```<code>{
  "fixturesFolder": "src/cypress/fixtures",
  "integrationFolder": "src/cypress/integration",
  "pluginsFile": "src/cypress/plugins/index.js",
  "screenshotsFolder": "src/cypress/screenshots",
  "videosFolder": "src/cypress/videos",
  "supportFile": "src/cypress/support/index.js"
}

// is there no option to set tsconfig.json path????
</code>```

The official documentation says to just put it in the cypress/ directory. According to the docs, that should be at /cypress/tsconfig.json, but in my project it's in /src/cypress/tsconfig.json.

Here's the location I've tried to put the tsconfig.json file:

/src/cypress/tsconfig.json //Error: "Couldn't find tsconfig.json. tsconfig-paths will be skipped"

/src/tsconfig.json //Error: "Couldn't find tsconfig.json. tsconfig-paths will be skipped"

/cypress/tsconfig.json //Error: "Couldn't find tsconfig.json. tsconfig-paths will be skipped"

/tsconfig.json // Works!! But not where I want this file to live...
```

How can I instruct Cypress on where to look for the tsconf.json file I want it to use? Is there an option in the cypress.json config file, or a CLI flag I can use????

I don't want to clutter my project root with miscellaneous config files, and I actually have separate tsconfig files for my project and my test suite. It would be great to set the file path explicitly.

答:
This can be achieved without a root level tsconfig. The idea is that we can cd into our test folder before running the open command:

With the below file structure your test command would look something like this:

cd ./src/cypress && cypress open --config-file ../../configs/cypress.json
```
```/
├── package.json
├── configs/
│   ├── cypress.json
├── src/
│   ├── cypress/
│   │   ├── tsconfig.json
```

Just be sure to update your support paths etc in the cypress.json, they will now be relative to src/cypress

Body:
I'm trying to use Cypress w/ Typescript but Cypress can't find the tsconfig.json file I've created for it. I also have a custom directory structure (because I hate when there's a bunch of config files in the root, so I put them in a config directory).

Project Directory Structure

/
├── package.json
├── configs/
│   ├── cypress.json
├── src/
│   ├── cypress/
│   │   ├── tsconfig.json

Cypress Open command

//  package.json

"scripts": {
    "cypress:open": "cypress open --config-file configs/cypress.json"
},

In the script above, the --config-file flag tells cypress the location of the cypress.json config file, which is AWESOME because I can put that file anywhere I want it. However, now I need to instruct Cypress on where to find it's tsconfig.json file.

/configs/cypress.json (tells Cypress where the cypress/ directory is)

{
  "fixturesFolder": "src/cypress/fixtures",
  "integrationFolder": "src/cypress/integration",
  "pluginsFile": "src/cypress/plugins/index.js",
  "screenshotsFolder": "src/cypress/screenshots",
  "videosFolder": "src/cypress/videos",
  "supportFile": "src/cypress/support/index.js"
}

// is there no option to set tsconfig.json path????

The official documentation says to just put it in the cypress/ directory. According to the docs, that should be at /cypress/tsconfig.json, but in my project it's in /src/cypress/tsconfig.json.

Here's the location I've tried to put the tsconfig.json file:

/src/cypress/tsconfig.json //Error: "Couldn't find tsconfig.json. tsconfig-paths will be skipped"

/src/tsconfig.json //Error: "Couldn't find tsconfig.json. tsconfig-paths will be skipped"

/cypress/tsconfig.json //Error: "Couldn't find tsconfig.json. tsconfig-paths will be skipped"

/tsconfig.json // Works!! But not where I want this file to live...

How can I instruct Cypress on where to look for the tsconf.json file I want it to use? Is there an option in the cypress.json config file, or a CLI flag I can use????

I don't want to clutter my project root with miscellaneous config files, and I actually have separate tsconfig files for my project and my test suite. It would be great to set the file path explicitly.

Body:
This can be achieved without a root level tsconfig. The idea is that we can cd into our test folder before running the open command:

With the below file structure your test command would look something like this:

cd ./src/cypress && cypress open --config-file ../../configs/cypress.json

/
├── package.json
├── configs/
│   ├── cypress.json
├── src/
│   ├── cypress/
│   │   ├── tsconfig.json

Just be sure to update your support paths etc in the cypress.json, they will now be relative to src/cypress


问:
How to get email body text and attachments using mimemessage class in java
In my SMTP server code, I have a MimeMessage instance that I want to use for extracting the incoming mailbody(mail text) and mail attachments. To do this, I use the below implementation on client and server sides. However, I am only able to retrieve mail attachments. The code somehow detects CustomerEngineer.ahmet thing two times and none of them contains the mail body which is : "This is a message body".  I can retrieve the image though.

In my java mail client, I created a mail with the following schema:

```<code>try {
        // Create a default MimeMessage object
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject
        message.setSubject("Hi JAXenter");

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("This is a message body");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        DataSource source = new FileDataSource(new File(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\CustomerEngineer.png")));
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("CustomerEngineer.ahmet");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
</code>```

On my server side I use the following logic:

```<code> MimeMessage message = new MimeMessage(session, data);

public void seperateBodyAndAttachments(MimeMessage message) throws MessagingException, IOException {
    String mimeType = message.getContentType();
    Date dt = new Date();

    if (message.isMimeType("text/*")) {
        System.out.println("this containst a text file");
    }  else if (message.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) message.getContent();
        int idx = 0;
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart part = mp.getBodyPart(i);
            String name = part.getDataHandler().getName();
            if (part.isMimeType("text/*")) {
                if (name == null) {
                    name = "text-" + (++idx) + ".txt";
                }
                System.out.println(name);
            } else {
                if (name == null) {
                    name = "attachment-" + (++idx);
                }
                FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\resources\\DevEnvironmentConfigFile\\" + name));
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                part.getDataHandler().writeTo(bos);
                bos.close();
            }
        }
    } else if (message.isMimeType("message/rfc822")) {
        // Not implemented
    } else {
        Object o = message.getContent();
        if (o instanceof String) {
            FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  + "text.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write((String)o);
            bw.close();
        } else if (o instanceof InputStream) {
            FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  +"message.dat"));
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            message.getDataHandler().writeTo(bos);
            bos.close();
        } else {
            FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  +"unknown.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write((String)o);
            bw.close();
        }
    }
}
</code>```

答:
In my case I needed to extract a MimeBodyPart from a MimeMessage. It was trickier than I thought but I ended up robbing these 2 methods from BouncyCastle

```<code> /**
 * extract an appropriate body part from the passed in MimeMessage
 */
protected MimeBodyPart makeContentBodyPart(
    MimeMessage message)
    throws SMIMEException
{
    MimeBodyPart content = new MimeBodyPart();
    //
    // add the headers to the body part.
    //
    try
    {
        message.removeHeader("Message-Id");
        message.removeHeader("Mime-Version");

        // JavaMail has a habit of reparsing some content types, if the bodypart is
        // a multipart it might be signed, we rebuild the body part using the raw input stream for the message.
        try
        {
            if (message.getContent() instanceof Multipart)
            {
                content.setContent(message.getRawInputStream(), message.getContentType());
                extractHeaders(content, message);
                return content;
            }
        }
        catch (MessagingException e)
        {
            // fall back to usual method below
        }
        content.setContent(message.getContent(), message.getContentType());
        content.setDataHandler(message.getDataHandler());
        extractHeaders(content, message);
    }
    catch (MessagingException e)
    {
        throw new SMIMEException("exception saving message state.", e);
    }
    catch (IOException e)
    {
        throw new SMIMEException("exception getting message content.", e);
    }

    return content;
}

private void extractHeaders(MimeBodyPart content, MimeMessage message)
    throws MessagingException
{
    Enumeration e = message.getAllHeaders();

    while (e.hasMoreElements())
    {
        Header hdr = (Header)e.nextElement();
        content.addHeader(hdr.getName(), hdr.getValue());
    }
}
</code>```

Body:
In my SMTP server code, I have a MimeMessage instance that I want to use for extracting the incoming mailbody(mail text) and mail attachments. To do this, I use the below implementation on client and server sides. However, I am only able to retrieve mail attachments. The code somehow detects CustomerEngineer.ahmet thing two times and none of them contains the mail body which is : "This is a message body".  I can retrieve the image though.

In my java mail client, I created a mail with the following schema:

try {
        // Create a default MimeMessage object
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject
        message.setSubject("Hi JAXenter");

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("This is a message body");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        DataSource source = new FileDataSource(new File(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\CustomerEngineer.png")));
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("CustomerEngineer.ahmet");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

On my server side I use the following logic:

 MimeMessage message = new MimeMessage(session, data);

public void seperateBodyAndAttachments(MimeMessage message) throws MessagingException, IOException {
    String mimeType = message.getContentType();
    Date dt = new Date();

    if (message.isMimeType("text/*")) {
        System.out.println("this containst a text file");
    }  else if (message.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) message.getContent();
        int idx = 0;
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart part = mp.getBodyPart(i);
            String name = part.getDataHandler().getName();
            if (part.isMimeType("text/*")) {
                if (name == null) {
                    name = "text-" + (++idx) + ".txt";
                }
                System.out.println(name);
            } else {
                if (name == null) {
                    name = "attachment-" + (++idx);
                }
                FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\resources\\DevEnvironmentConfigFile\\" + name));
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                part.getDataHandler().writeTo(bos);
                bos.close();
            }
        }
    } else if (message.isMimeType("message/rfc822")) {
        // Not implemented
    } else {
        Object o = message.getContent();
        if (o instanceof String) {
            FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  + "text.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write((String)o);
            bw.close();
        } else if (o instanceof InputStream) {
            FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  +"message.dat"));
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            message.getDataHandler().writeTo(bos);
            bos.close();
        } else {
            FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  +"unknown.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write((String)o);
            bw.close();
        }
    }
}

Body:
In my case I needed to extract a MimeBodyPart from a MimeMessage. It was trickier than I thought but I ended up robbing these 2 methods from BouncyCastle

 /**
 * extract an appropriate body part from the passed in MimeMessage
 */
protected MimeBodyPart makeContentBodyPart(
    MimeMessage message)
    throws SMIMEException
{
    MimeBodyPart content = new MimeBodyPart();
    //
    // add the headers to the body part.
    //
    try
    {
        message.removeHeader("Message-Id");
        message.removeHeader("Mime-Version");

        // JavaMail has a habit of reparsing some content types, if the bodypart is
        // a multipart it might be signed, we rebuild the body part using the raw input stream for the message.
        try
        {
            if (message.getContent() instanceof Multipart)
            {
                content.setContent(message.getRawInputStream(), message.getContentType());
                extractHeaders(content, message);
                return content;
            }
        }
        catch (MessagingException e)
        {
            // fall back to usual method below
        }
        content.setContent(message.getContent(), message.getContentType());
        content.setDataHandler(message.getDataHandler());
        extractHeaders(content, message);
    }
    catch (MessagingException e)
    {
        throw new SMIMEException("exception saving message state.", e);
    }
    catch (IOException e)
    {
        throw new SMIMEException("exception getting message content.", e);
    }

    return content;
}

private void extractHeaders(MimeBodyPart content, MimeMessage message)
    throws MessagingException
{
    Enumeration e = message.getAllHeaders();

    while (e.hasMoreElements())
    {
        Header hdr = (Header)e.nextElement();
        content.addHeader(hdr.getName(), hdr.getValue());
    }
}


问:
How to format 'const' argument in Terra::Predict?
Question:
How do I format the 'const' argument for the predict function in the Terra package?

Background and details:

I am using Terra's predict function to create spatial maps from a model. The function worked as expected when I created full rasters for my three constant values. When I saw predict has an argument 'const' for constants, I decided to use that instead. Unfortunately, the help document doesn't specify how to structure the data beyond that they should be in a dataframe.

Argument description for 'const' from ?terra::predict:

data.frame. Can be used to add a constant value as a predictor variable so that you do not need to make a SpatRaster layer for it

The argument is not used in any of the examples listed at the bottom of the document either.

What I tried:

I tried formating the dataframe as a single row with named columns for each constant value that is required in the model. The function accepted it with the warning:

Warning messages:
1: In data.frame(..., check.names = FALSE) :
row names were found from a short variable and have been discarded

But this produced clearly incorrect values in the resulting outputs. Possibly it was just using the first value for all three constants, but I don't know.

I also tried formating the dataframe with two columns, one for the variable name and one for the variable values. This failed with the following error:

Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'writeRaster': arguments imply differing number of rows: 10000, 3

10000 may be referring to the dimenions of the raster data (10k x 10k) and the 3 is likely referring to the three rows in the constant dataframe I supplied.

I don't want to go back to writing rasters for each constant because I am producing many maps and each one would require 3 10k x 10k rasters to be generated with the constant values, which is time consuming and may lead to memory issues.

Any suggestions would be greatly appreciated!

答:
Here is an illustration

```<code>library(terra)
logo <- rast(system.file("ex/logo.tif", package="terra"))
names(logo) <- c("red", "green", "blue")
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9,  99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21,37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2)
xy <- rbind(cbind(1, p), cbind(0, a))
e <- extract(logo, xy[,2:3])
v <- data.frame(cbind(pa=xy[,1], e))

model <- glm(formula=pa~., data=v)

names(model$coefficients)[-1]
#[1] "red"   "green" "blue"
names(logo)
#[1] "red"   "green" "blue"

# standard approach
r <- predict(logo, model)

# one or more constants
r <- predict(logo[[2:3]], model, const=data.frame(red=0))
r <- predict(logo$blue, model, const=data.frame(red=100, green=0))

# you could even use constants only
x <- logo[[1]]
names(x) <- "A"
r <- predict(x, model, const=data.frame(blue=50, red=100, green=0))
</code>```

The output is as expected:

```<code>predict(model, data.frame(blue=50, red=100, green=0))
#        1
#-4.538653

r[1]
#          A
#1 -4.538653
</code>```

Body:
Here is an illustration

library(terra)
logo <- rast(system.file("ex/logo.tif", package="terra"))
names(logo) <- c("red", "green", "blue")
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9,  99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21,37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2)
xy <- rbind(cbind(1, p), cbind(0, a))
e <- extract(logo, xy[,2:3])
v <- data.frame(cbind(pa=xy[,1], e))

model <- glm(formula=pa~., data=v)

names(model$coefficients)[-1]
#[1] "red"   "green" "blue"
names(logo)
#[1] "red"   "green" "blue"

# standard approach
r <- predict(logo, model)

# one or more constants
r <- predict(logo[[2:3]], model, const=data.frame(red=0))
r <- predict(logo$blue, model, const=data.frame(red=100, green=0))

# you could even use constants only
x <- logo[[1]]
names(x) <- "A"
r <- predict(x, model, const=data.frame(blue=50, red=100, green=0))

The output is as expected:

predict(model, data.frame(blue=50, red=100, green=0))
#        1
#-4.538653

r[1]
#          A
#1 -4.538653


问:
Linked list c++ insertback
I am really new to data structures. I am trying to figure out why my insertback() function doesn't work. The first print does 3,2,1 but the second doesn't print anything. I think it has something to do with head, but I'm not really sure. Please help.

```<code>#include <iostream>
using namespace std;

struct Node
{
    int data;
    Node* next;
};

class lst
{
public:
    void Insertfron(int x);
    void Print();
    void Insertback(int x);
private:
    Node* head;
};

void lst::Insertfron(int x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = head;
    head = temp;
}

void lst::Print()
{
    Node* temp = head;
    while(temp->next!=NULL)
    {
        cout<<temp->data<<' ';
        temp=temp->next;
    }
    cout<< endl;
}

void lst::Insertback(int x)
{
    Node* backinst = new Node;
    backinst->data = x;
    backinst->next = NULL;
    Node* temp = head;
    while(temp->next!=NULL)
    {
        temp = temp->next;
    }
    temp->next = backinst;
}

int main()
{
    lst listt;
    listt.Insertfron(1);
    listt.Insertfron(2);
    listt.Insertfron(3);
    listt.Print();
    listt.Insertback(4);
    listt.Print();
    return 0;
}
</code>```

答:
You are not initializing head to NULL to indicate an empty list, so ``head` will have a random garbage value, and thus all of your methods exhibit undefined behavior.

Once that is fixed, your while loops in both Print() and Insertback() are buggy, as they are not account for head being NULL when the list is empty.

Also, you are leaking every node you create.  You need to add a destructor to free the nodes when you are done using the list.

With that said, try something more like this instead:

```<code>#include <iostream>
using namespace std;

struct Node
{
    int data;
    Node* next;
};

class lst
{
public:
    lst();
    ~lst();
    void Insertfron(int x);
    void Print();
    void Insertback(int x);
private:
    Node* head;
};

lst::lst()
    : head(NULL)
{
}

lst::~lst()
{
    while (head != NULL)
    {
        Node *next = head->next;
        delete head;
        head = next;
    }
}

void lst::Insertfron(int x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = head;
    head = temp;
}

void lst::Print()
{
    Node* temp = head;
    while (temp != NULL)
    {
        cout << temp->data << ' ';
        temp = temp->next;
    }
    cout << endl;
}

void lst::Insertback(int x)
{
    Node* backinst = new Node;
    backinst->data = x;
    backinst->next = NULL;
    if (head == NULL)
    {
        head = backinst;
    }
    else
    {
        Node* temp = head;
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = backinst;
    }
}

int main()
{
    lst listt;
    listt.Insertfron(1);
    listt.Insertfron(2);
    listt.Insertfron(3);
    listt.Print();
    listt.Insertback(4);
    listt.Print();
    return 0;
}
</code>```

That being said, Insertback() can be simplified to avoid the extra if by using an extra level of pointer indirection:

```<code>void lst::Insertback(int x)
{
    Node **temp = &head;
    while (*temp != NULL)
    {
        temp = &((*temp)->next);
    }
    Node* backinst = new Node;
    backinst->data = x;
    backinst->next = NULL;
    *temp = backinst;
}
</code>```

Title: Linked list c++ insertback

Body:
I am really new to data structures. I am trying to figure out why my insertback() function doesn't work. The first print does 3,2,1 but the second doesn't print anything. I think it has something to do with head, but I'm not really sure. Please help.

#include <iostream>
using namespace std;

struct Node
{
    int data;
    Node* next;
};

class lst
{
public:
    void Insertfron(int x);
    void Print();
    void Insertback(int x);
private:
    Node* head;
};

void lst::Insertfron(int x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = head;
    head = temp;
}

void lst::Print()
{
    Node* temp = head;
    while(temp->next!=NULL)
    {
        cout<<temp->data<<' ';
        temp=temp->next;
    }
    cout<< endl;
}

void lst::Insertback(int x)
{
    Node* backinst = new Node;
    backinst->data = x;
    backinst->next = NULL;
    Node* temp = head;
    while(temp->next!=NULL)
    {
        temp = temp->next;
    }
    temp->next = backinst;
}

int main()
{
    lst listt;
    listt.Insertfron(1);
    listt.Insertfron(2);
    listt.Insertfron(3);
    listt.Print();
    listt.Insertback(4);
    listt.Print();
    return 0;
}

Body:
You are not initializing head to NULL to indicate an empty list, so ``head` will have a random garbage value, and thus all of your methods exhibit undefined behavior.

Once that is fixed, your while loops in both Print() and Insertback() are buggy, as they are not account for head being NULL when the list is empty.

Also, you are leaking every node you create.  You need to add a destructor to free the nodes when you are done using the list.

With that said, try something more like this instead:

#include <iostream>
using namespace std;

struct Node
{
    int data;
    Node* next;
};

class lst
{
public:
    lst();
    ~lst();
    void Insertfron(int x);
    void Print();
    void Insertback(int x);
private:
    Node* head;
};

lst::lst()
    : head(NULL)
{
}

lst::~lst()
{
    while (head != NULL)
    {
        Node *next = head->next;
        delete head;
        head = next;
    }
}

void lst::Insertfron(int x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = head;
    head = temp;
}

void lst::Print()
{
    Node* temp = head;
    while (temp != NULL)
    {
        cout << temp->data << ' ';
        temp = temp->next;
    }
    cout << endl;
}

void lst::Insertback(int x)
{
    Node* backinst = new Node;
    backinst->data = x;
    backinst->next = NULL;
    if (head == NULL)
    {
        head = backinst;
    }
    else
    {
        Node* temp = head;
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = backinst;
    }
}

int main()
{
    lst listt;
    listt.Insertfron(1);
    listt.Insertfron(2);
    listt.Insertfron(3);
    listt.Print();
    listt.Insertback(4);
    listt.Print();
    return 0;
}

That being said, Insertback() can be simplified to avoid the extra if by using an extra level of pointer indirection:

void lst::Insertback(int x)
{
    Node **temp = &head;
    while (*temp != NULL)
    {
        temp = &((*temp)->next);
    }
    Node* backinst = new Node;
    backinst->data = x;
    backinst->next = NULL;
    *temp = backinst;
}


问:
When do I need to worry about thread-safety in an iOS application?
When writing the usual view controller code, can I assume that this will only be called from a single event-loop thread? What kind of classes do I need to make thread-safe? What are the usual situations where multiple threads are involved?</p>

答:
If you are writing normal UIViewController code, you don't need to worry about thread-safety in iOS. In iOS, any message about UI should be running on the main thread.

If you don't perform some message in background by you self, normally, you don't have to worry about thread, in most situations, it will always be on the main thread.

P.S. Some Frameworks like Game Kit will some times perform messages in background, but it's not about UI and the document from Apple will warn you to make sure if the message is running on main thread.


问:
MYSQL SubQuery with Max
I running into some time  issues using my simple select:

```<code>SELECT *
FROM ltowert
WHERE bat = 3
  AND id >= (SELECT id
             FROM ltowert
             WHERE bat = 3 AND ident = 'v0'
             ORDER BY id DESC
             LIMIT 1)
ORDER BY ident;
</code>```

It takes nearly 12 seconds (depending on the index, etc..)

If I run the subquery (0.00075 sec) and put the result in the statement:

```<code>SELECT *
FROM ltowert
WHERE bat = 3  AND id >= 20979399
ORDER BY ident;
</code>```

it runs in just 0.00095 sec, in addition: 0.0017 sec

So it seems, using the subquery avoid the Optimizer to use the index ?
How can I fix it and get quicker results ?

Thanks for any answers.

JR

答:
You need both of these:

```<code>INDEX(bat, ident, id)
INDEX(bat, id)
</code>```

If they don't suffice, please provide

```<code>SHOW CREATE TABLE ltowert;
EXPLAIN SELECT ...;
</code>```

Title: MYSQL SubQuery with Max

Body:
I running into some time  issues using my simple select:

SELECT *
FROM ltowert
WHERE bat = 3
  AND id >= (SELECT id
             FROM ltowert
             WHERE bat = 3 AND ident = 'v0'
             ORDER BY id DESC
             LIMIT 1)
ORDER BY ident;

It takes nearly 12 seconds (depending on the index, etc..)

If I run the subquery (0.00075 sec) and put the result in the statement:

SELECT *
FROM ltowert
WHERE bat = 3  AND id >= 20979399
ORDER BY ident;

it runs in just 0.00095 sec, in addition: 0.0017 sec

So it seems, using the subquery avoid the Optimizer to use the index ?
How can I fix it and get quicker results ?

Thanks for any answers.

JR

Body:
You need both of these:

INDEX(bat, ident, id)
INDEX(bat, id)

If they don't suffice, please provide

SHOW CREATE TABLE ltowert;
EXPLAIN SELECT ...;