问:
Getting "fatal: Authentication failed" -error when sending git commands in Windows 10
After updating domain password, accessing git-repo is no longer possible. VS Code and Source Tree as well as Visual Studio are returning the following error message on pull, push, fetch etc..

fatal: Authentication failed

Normally a credentials pop-up should appear however this is not happening. Also the common recommendation is not working:

```<code>git config --global credential.helper wincred
</code>```

答:
I had the same issue when Cloning the repository via Bash/VS Code with "fatal:Authentication failed". I used SSH Key authentication instead to connect my repository following the article: [https://learn.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops&tabs=current-page][1]
I didn't get any errors after with any bash commands!

Above solution works only if your machine can SSH.

Body:
After updating domain password, accessing git-repo is no longer possible. VS Code and Source Tree as well as Visual Studio are returning the following error message on pull, push, fetch etc..

fatal: Authentication failed

Normally a credentials pop-up should appear however this is not happening. Also the common recommendation is not working:

git config --global credential.helper wincred


来源: stackexchange

问:
How to Navigating from SwiftUI View to UIKit UIViewController
As of now, I have an application built entirely using UIKit. However, I wish to be able to start implementing some SwiftUI Views to replace some UIViewControllers.

I've been able to do this to navigate from the UIViewController to SwiftUI View on button tap:

```<code>    @IBAction func buttonTapped(_ sender: Any) {
        let newView = UIHostingController(rootView: SwiftUIView(viewObj: self.view, sb: self.storyboard, dismiss: self.dismiss) )
        view.window?.rootViewController = newView
        view.window?.makeKeyAndVisible()
    }
</code>```

My question is, how would I transition from a single SwiftUI View to a UIViewController?(Since the rest of the application is in UIKit)? I've got a button in the SwiftUI View, to navigate back to the UIViewController on tap. I've tried:

Passing the view and storyboard objects to the SwiftUI View, then calling doing something similar to the code above to change the current view controller. However, when tried on the simulator nothing happens.

Using .present to show the SwiftUI View modally. This works and I can allow the SwiftUI View to .dismiss itself. However, this only works modally, and I hope to make this work properly (i.e change screen)

Here is my simple SwiftUI View:

```<code>struct SwiftUIView: View {
    var viewObj:UIView? // Perhaps use this for transition back?
    var sb:UIStoryboard?
    var dismiss: (() -> Void)?

    var body: some View {

        Button(action: {
            // Do something here to Transition
        }) {
            Text("This is a SwiftUI view.")
        }
    }
}
</code>```

I'm having trouble understanding how to properly integrate SwiftUI into UIKit NOT the other way around, and I'm not sure if UIViewControllerRepresentable is the answer to this. Any solution to this, alternatives or helpful knowledge is very much appreciated. Thanks again!

答:
Ciao,

I tried to follow your approach by using closure callbacks.

```<code>struct SwiftUIView: View {
    var dismiss: (() -> Void)?
    var present: (()->Void)?

    var body: some View {
        VStack(spacing: 20) {
            Button(action: {
                self.dismiss?()
            }) {
                Text("Dismiss me")
            }
            Button(action: {
                self.present?()
            }) {
                Text("Present some UIViewController")
            }
        }
    }
}
</code>```

When you present your UIHostingController, you want to implement the 2 closure callbacks:

```<code>@IBAction func buttonTapped(_ sender: Any) {
    let hostingController = UIHostingController(rootView: SwiftUIView())
    hostingController.rootView.dismiss = {
        hostingController.dismiss(animated: true, completion: nil)
    }
    hostingController.rootView.present = {
        let destination = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "VC_TO_PRESENT")
        hostingController.present(destination, animated: true, completion: nil)
    }

    present(hostingController, animated: true, completion: nil)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
As of now, I have an application built entirely using UIKit. However, I wish to be able to start implementing some SwiftUI Views to replace some UIViewControllers.

I've been able to do this to navigate from the UIViewController to SwiftUI View on button tap:

    @IBAction func buttonTapped(_ sender: Any) {
        let newView = UIHostingController(rootView: SwiftUIView(viewObj: self.view, sb: self.storyboard, dismiss: self.dismiss) )
        view.window?.rootViewController = newView
        view.window?.makeKeyAndVisible()
    }

My question is, how would I transition from a single SwiftUI View to a UIViewController?(Since the rest of the application is in UIKit)? I've got a button in the SwiftUI View, to navigate back to the UIViewController on tap. I've tried:

Passing the view and storyboard objects to the SwiftUI View, then calling doing something similar to the code above to change the current view controller. However, when tried on the simulator nothing happens.

Using .present to show the SwiftUI View modally. This works and I can allow the SwiftUI View to .dismiss itself. However, this only works modally, and I hope to make this work properly (i.e change screen)

Here is my simple SwiftUI View:

struct SwiftUIView: View {
    var viewObj:UIView? // Perhaps use this for transition back?
    var sb:UIStoryboard?
    var dismiss: (() -> Void)?

    var body: some View {

        Button(action: {
            // Do something here to Transition
        }) {
            Text("This is a SwiftUI view.")
        }
    }
}

I'm having trouble understanding how to properly integrate SwiftUI into UIKit NOT the other way around, and I'm not sure if UIViewControllerRepresentable is the answer to this. Any solution to this, alternatives or helpful knowledge is very much appreciated. Thanks again!

Body:
Ciao,

I tried to follow your approach by using closure callbacks.

struct SwiftUIView: View {
    var dismiss: (() -> Void)?
    var present: (()->Void)?

    var body: some View {
        VStack(spacing: 20) {
            Button(action: {
                self.dismiss?()
            }) {
                Text("Dismiss me")
            }
            Button(action: {
                self.present?()
            }) {
                Text("Present some UIViewController")
            }
        }
    }
}

When you present your UIHostingController, you want to implement the 2 closure callbacks:

@IBAction func buttonTapped(_ sender: Any) {
    let hostingController = UIHostingController(rootView: SwiftUIView())
    hostingController.rootView.dismiss = {
        hostingController.dismiss(animated: true, completion: nil)
    }
    hostingController.rootView.present = {
        let destination = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "VC_TO_PRESENT")
        hostingController.present(destination, animated: true, completion: nil)
    }

    present(hostingController, animated: true, completion: nil)
}


问:
List comprehension where the condition depends on the list being generated
I am new to Python programming. I want to rewrite the following code as a list comprehension:

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz = []
for x in lx:
    if x in ly and x not in lz:
        lz.append(x)
```

This will create a new list with common elements of lx and ly; but the condition x not in lz depends on the list that is being built. How can this code be rewritten as a list comprehension?

答:
The correct answer here is to use sets, because (1) sets naturally have distinct elements, and (2) sets are more efficient than lists for membership tests. So the simple solution is list(set(lx) & set(ly)).

However, sets do not preserve the order that elements are inserted in, so in case the order is important, here's a solution which preserves the order from lx. (If you want the order from ly, simply swap the roles of the two lists.)

def ordered_intersection(lx, ly):
    ly_set = set(ly)
    return [ly_set.remove(x) or x for x in lx if x in ly_set]
```

<p>Example:</p>

<pre class="lang-py prettyprint-override"><code>>>> ordered_intersection(lx, ly)
[2, 4, 5]
>>> ordered_intersection(ly, lx)
[2, 5, 4]
</code>```

It works because ly_set.remove(x) always returns None, which is falsy, so ly_set.remove(x) or x always has the value of x.

The reason you cannot do this with a simpler list comprehension like lz = [... if x in lz] is because the whole list comprehension will be evaluated before the resulting list is assigned to the variable lz; so the x in lz test will give a NameError because there is no such variable yet.

That said, it is possible to rewrite your code to directly use a generator expression (which is somewhat like a list comprehension) instead of a for loop; but it is bad code and you shouldn't do this:

def ordered_intersection_bad_dont_do_this(lx, ly):
    lz = []
    lz.extend(x for x in lx if x in ly and x not in lz)
    return lz
```

This is not just bad because of repeatedly testing membership of lists; it is worse, because it depends on an unspecified behaviour of the extend method. In particular, it adds each element one by one rather than exhausting the iterator first and then adding them all at once. The docs don't say that this is guaranteed to happen, so this bad solution won't necessarily work in other versions of Python.

Body:
I am new to Python programming. I want to rewrite the following code as a list comprehension:

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz = []
for x in lx:
    if x in ly and x not in lz:
        lz.append(x)

This will create a new list with common elements of lx and ly; but the condition x not in lz depends on the list that is being built. How can this code be rewritten as a list comprehension?

Body:
The correct answer here is to use sets, because (1) sets naturally have distinct elements, and (2) sets are more efficient than lists for membership tests. So the simple solution is list(set(lx) & set(ly)).

However, sets do not preserve the order that elements are inserted in, so in case the order is important, here's a solution which preserves the order from lx. (If you want the order from ly, simply swap the roles of the two lists.)

def ordered_intersection(lx, ly):
    ly_set = set(ly)
    return [ly_set.remove(x) or x for x in lx if x in ly_set]

Example:

>>> ordered_intersection(lx, ly)
[2, 4, 5]
>>> ordered_intersection(ly, lx)
[2, 5, 4]

It works because ly_set.remove(x) always returns None, which is falsy, so ly_set.remove(x) or x always has the value of x.

The reason you cannot do this with a simpler list comprehension like lz = [... if x in lz] is because the whole list comprehension will be evaluated before the resulting list is assigned to the variable lz; so the x in lz test will give a NameError because there is no such variable yet.

That said, it is possible to rewrite your code to directly use a generator expression (which is somewhat like a list comprehension) instead of a for loop; but it is bad code and you shouldn't do this:

def ordered_intersection_bad_dont_do_this(lx, ly):
    lz = []
    lz.extend(x for x in lx if x in ly and x not in lz)
    return lz

This is not just bad because of repeatedly testing membership of lists; it is worse, because it depends on an unspecified behaviour of the extend method. In particular, it adds each element one by one rather than exhausting the iterator first and then adding them all at once. The docs don't say that this is guaranteed to happen, so this bad solution won't necessarily work in other versions of Python.


问:
Access is denied while executing pip -V in virtual environment in Python
I created a virtual environment for my development with the following commands in python 3.8 version. I also activated and upgraded pip. But while executing any command using pip, I get Access is denied error. Please suggest me in this case.

```<code>py -m venv env <= Created virtual environment name env

.\env\Scripts\activate <= Activated virtual env

python -m pip install --upgrade pip <= upgraded to Pip version 20

pip -V <= Giving Access is denied
</code>```

Find below the image.

答: All problems are due to latest version of Python 3.8.1 version. When I installed Python version 3.7.4, all worked fine. I am able to create virtual environment and also able to update pip.

Body:
I created a virtual environment for my development with the following commands in python 3.8 version. I also activated and upgraded pip. But while executing any command using pip, I get Access is denied error. Please suggest me in this case.

py -m venv env <= Created virtual environment name env

.\env\Scripts\activate <= Activated virtual env

python -m pip install --upgrade pip <= upgraded to Pip version 20

pip -V <= Giving Access is denied

Find below the image.


问:
How to make gridview searchable?
I've got a gridview that draws from multiple tables, I'd like to make it searchable in three fields, one from each table. I plan on using a dropdown to select which field to search for, and a textbox of course for search input, but what then? Here's my gridview code in C# ASP.NET:</p>

```<code> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
    EmptyDataText="There are no data records to display." AllowPaging="True"
    BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
    CellPadding="3" GridLines="Vertical" HorizontalAlign="Center"
    DataKeyNames="SubId" AllowSorting="True">
    <AlternatingRowStyle BackColor="#DCDCDC" />

    <Columns>

        <asp:BoundField DataField="SubId" HeaderText="Submission ID"
            SortExpression="SubId" >
        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" />
        </asp:BoundField>
        <asp:BoundField DataField="CustName" HeaderText="Customer"
            SortExpression="CustName" />
        <asp:BoundField DataField="CustCity" HeaderText="Customer City"
            SortExpression="CustCity" />
        <asp:BoundField DataField="CustState" HeaderText="Customer State"
            SortExpression="CustState" />
        <asp:BoundField DataField="BroName" HeaderText="Broker "
            SortExpression="BroName" />
        <asp:BoundField DataField="BroState" HeaderText="Broker State"
            SortExpression="BroState" />
        <asp:BoundField DataField="EntityType" HeaderText="EntityType"
            SortExpression="EntityType" />
        <asp:BoundField DataField="Coverage" DataFormatString="{0:c}"
            HeaderText="Coverage" SortExpression="Coverage" />
        <asp:BoundField DataField="Status" HeaderText="Status"
            SortExpression="Status" />

        <asp:HyperLinkField DataNavigateUrlFields="SubId"
            DataNavigateUrlFormatString="View.aspx?SubId={0}" Text="View" />
        <asp:HyperLinkField DataNavigateUrlFields="SubId"
            DataNavigateUrlFormatString="ViewEdit.aspx?SubId={0}" Text="Edit" />

    </Columns>
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#0000A9" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ProductInstanceString.ProviderName %>"

    SelectCommand="SELECT Customer.SubId, Customer.CustName, Customer.CustCity, Customer.CustState, Broker.BroName, Broker.BroState, Broker.EntityType, Submission.Coverage, Submission.Status FROM Submission INNER JOIN Broker ON Broker.SubId = Submission.SubmissionId INNER JOIN Customer ON Customer.SubId = Submission.SubmissionId">

</asp:SqlDataSource>
</code>```

答:
Use dropdown on the page and on the codebehind use DataView object to filter rows of grid, see below syntax:</p>

```<code>DataView dvData = new DataView(dtData);
dvData.RowFilter = "[ColumnName]=[Condition, this will be your dropdown value]";
gv.DataSource = dvData;
gv.DataBind();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to make gridview searchable?

Body:
I've got a gridview that draws from multiple tables, I'd like to make it searchable in three fields, one from each table. I plan on using a dropdown to select which field to search for, and a textbox of course for search input, but what then? Here's my gridview code in C# ASP.NET:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
    EmptyDataText="There are no data records to display." AllowPaging="True"
    BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
    CellPadding="3" GridLines="Vertical" HorizontalAlign="Center"
    DataKeyNames="SubId" AllowSorting="True">
    <AlternatingRowStyle BackColor="#DCDCDC" />

    <Columns>

        <asp:BoundField DataField="SubId" HeaderText="Submission ID"
            SortExpression="SubId" >
        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" />
        </asp:BoundField>
        <asp:BoundField DataField="CustName" HeaderText="Customer"
            SortExpression="CustName" />
        <asp:BoundField DataField="CustCity" HeaderText="Customer City"
            SortExpression="CustCity" />
        <asp:BoundField DataField="CustState" HeaderText="Customer State"
            SortExpression="CustState" />
        <asp:BoundField DataField="BroName" HeaderText="Broker "
            SortExpression="BroName" />
        <asp:BoundField DataField="BroState" HeaderText="Broker State"
            SortExpression="BroState" />
        <asp:BoundField DataField="EntityType" HeaderText="EntityType"
            SortExpression="EntityType" />
        <asp:BoundField DataField="Coverage" DataFormatString="{0:c}"
            HeaderText="Coverage" SortExpression="Coverage" />
        <asp:BoundField DataField="Status" HeaderText="Status"
            SortExpression="Status" />

        <asp:HyperLinkField DataNavigateUrlFields="SubId"
            DataNavigateUrlFormatString="View.aspx?SubId={0}" Text="View" />
        <asp:HyperLinkField DataNavigateUrlFields="SubId"
            DataNavigateUrlFormatString="ViewEdit.aspx?SubId={0}" Text="Edit" />

    </Columns>
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#0000A9" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ProductInstanceString.ProviderName %>"

    SelectCommand="SELECT Customer.SubId, Customer.CustName, Customer.CustCity, Customer.CustState, Broker.BroName, Broker.BroState, Broker.EntityType, Submission.Coverage, Submission.Status FROM Submission INNER JOIN Broker ON Broker.SubId = Submission.SubmissionId INNER JOIN Customer ON Customer.SubId = Submission.SubmissionId">

</asp:SqlDataSource>

Body:
Use dropdown on the page and on the codebehind use DataView object to filter rows of grid, see below syntax:

DataView dvData = new DataView(dtData);
dvData.RowFilter = "[ColumnName]=[Condition, this will be your dropdown value]";
gv.DataSource = dvData;
gv.DataBind();


问:
PHP encourage loop part way through the loop
I am wanting to get a loop to loop without going through all the code for the loop. For instance in the example code I want to continue the loop without have to go through any of the if statements below the one that matches.

NOTE: I know something similar to this example would be better done using a switch statement but my set of if statements are not as simple as this.

```<code>foreach($array as $key=>$value){
    if(is_varchar($value)){loop;}
    if(is_text($value)){loop;}
    if(is_mediumText($value)){loop;}
    if(is_boolean($value)){loop;}
    if(is_integer($value)){loop;}
    if(is_float($value)){loop;}
    if(is_double($value)){loop;}
}
</code>```

答:
Dont see a reason NOT to use switch here.

```<code>foreach ($x as $y) {
  switch ($y) {
    case 0: continue; break;
    case 1: continue; break;
    case 2: continue; break;
    case 3: continue; break;
  }
}
</code>```

You can completely omit continue;, if the switch-statement is the only one within the foreach-loop

```<code>foreach ($x as $y) {
  switch ($y) {
    case 0: doSomethingA(); break;
    case 1: doSomethingB(); break;
    case 2: doSomethingC(); break;
    case 3: doSomethingD(); break;
  }
}
</code>```

Update (after the update of the question):

The switch-statement is still useable (and in my opinion more readable)

```<code>foreach($array as $key=>$value){
  switch (true) {
    case is_varchar($value): continue; break;
    case is_text($value): continue; break;
    // And so on
  }
}
</code>```

As long as the code simply does nothing you can also simplify it a little bit.

```<code>foreach($array as $key=>$value){
  switch (true) {
    case is_varchar($value):
    case is_text($value):
      continue;
    break;
    // And so on
  }
}
</code>```

Body:
I am wanting to get a loop to loop without going through all the code for the loop. For instance in the example code I want to continue the loop without have to go through any of the if statements below the one that matches.

NOTE: I know something similar to this example would be better done using a switch statement but my set of if statements are not as simple as this.

foreach($array as $key=>$value){
    if(is_varchar($value)){loop;}
    if(is_text($value)){loop;}
    if(is_mediumText($value)){loop;}
    if(is_boolean($value)){loop;}
    if(is_integer($value)){loop;}
    if(is_float($value)){loop;}
    if(is_double($value)){loop;}
}

Body:
Dont see a reason NOT to use switch here.

foreach ($x as $y) {
  switch ($y) {
    case 0: continue; break;
    case 1: continue; break;
    case 2: continue; break;
    case 3: continue; break;
  }
}

You can completely omit continue;, if the switch-statement is the only one within the foreach-loop

foreach ($x as $y) {
  switch ($y) {
    case 0: doSomethingA(); break;
    case 1: doSomethingB(); break;
    case 2: doSomethingC(); break;
    case 3: doSomethingD(); break;
  }
}

Update (after the update of the question):

The switch-statement is still useable (and in my opinion more readable)

foreach($array as $key=>$value){
  switch (true) {
    case is_varchar($value): continue; break;
    case is_text($value): continue; break;
    // And so on
  }
}

As long as the code simply does nothing you can also simplify it a little bit.

foreach($array as $key=>$value){
  switch (true) {
    case is_varchar($value):
    case is_text($value):
      continue;
    break;
    // And so on
  }
}


问:
how to convert mysql TIMESTAMPDIFF to oraclesql query
TIMESTAMPDIFF(HOUR, pk.consprtydate, rs.consprtydate)

wanted the difference of hours from two dates and extract the hours in oracle sql

答:
In oracle, you can easily achieve it by substracting two date fields as following:

```<code>Date2 - Date1  -- returns number of days between dates
(Date2 - Date1)/24 -- returns number of days between dates
MONTHS_BETWEEN(Date1, Date2) -- returns number of months between dates
</code>```

Cheers!!

Body:
In oracle, you can easily achieve it by substracting two date fields as following:

Date2 - Date1  -- returns number of days between dates
(Date2 - Date1)/24 -- returns number of days between dates
MONTHS_BETWEEN(Date1, Date2) -- returns number of months between dates

Cheers!!


问:
Converting Object Data type to float data type in pandas results NaN values
I'm doing a classification on the Ecoli data set as an assignment
The Data Set is collected from the UCI repository. To create a decision tree classifier I need to convert the object data types into float. While converting the data types changes into float but the string in the column changes all to 'NaN'
So that I couldn't use that column in fit() function

```<code>data_file = pd.read_csv('/home/root-user/Documents/ecoli.csv')
df1 = pd.DataFrame(data_file)
df1_cleaned = df1.drop('SEQUENCE_NAME',axis=1)
df1_cleaned['PROTEIN_SEQUENCE'] = pd.to_numeric(df1_cleaned['PROTEIN_SEQUENCE'], errors='coerce')
cleaned_list = df1_cleaned.values.tolist()
print(df1_cleaned)
</code>```

Then the output is like this

data set after converting object dtype into float

答:
pd.to_numeric attempts to convert a sequence to numeric and coerces when told to do so.

errors = 'coerce' will convert anything it can to float, and anything it can't to NaNs

If you'd like to keep whatever it couldn't convert to float in its
original form for debugging, do errors = 'ignore'

Also, can you please post the original data in PROTEIN_SEQUENCE column? Perhaps, cleaning it a bit before conversion would be helpful.

Body:
I'm doing a classification on the Ecoli data set as an assignment
The Data Set is collected from the UCI repository. To create a decision tree classifier I need to convert the object data types into float. While converting the data types changes into float but the string in the column changes all to 'NaN'
So that I couldn't use that column in fit() function

data_file = pd.read_csv('/home/root-user/Documents/ecoli.csv')
df1 = pd.DataFrame(data_file)
df1_cleaned = df1.drop('SEQUENCE_NAME',axis=1)
df1_cleaned['PROTEIN_SEQUENCE'] = pd.to_numeric(df1_cleaned['PROTEIN_SEQUENCE'], errors='coerce')
cleaned_list = df1_cleaned.values.tolist()
print(df1_cleaned)

Then the output is like this

data set after converting object dtype into float


问:
What is the best approach for getting context to estabish icon for swipe to delete
I have implemented a recyclerview within a fragment. Working to implement a swipetodelete for rows within the recycler view.  When using some example code for the swipe, it is looking to establish context for the ContextCompat.getDrawable() method.  What is the best way to set the context?

The problem line of code for setting the icon in the Swipe To Delete code is

```<code>icon = ContextCompat.getDrawable(mAdapter.getContext(),R.drawable.baseline_delete_sweep_white_24dp));
</code>```

Here is the CheckInListAdapter code for the recyclerview.

```<code>package com.example.checkingin;

import android.content.Context;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.snackbar.Snackbar;

import java.util.List;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
    private int checkInListLayout;
    private List<CheckInTable> checkInList;
    private CoordinatorLayout coordinatorLayout;
    private CheckInTable mRecentlyDeletedItem;
    private int mRecentlyDeletedItemPosition;

    public CheckInListAdapter(int layoutId) {
        Log.i(TAG, "CheckInListAdapter: ");
        checkInListLayout = layoutId;
    }

    public void setCheckInList(List<CheckInTable> allCheckIn) {
        checkInList = allCheckIn;
        Log.i(TAG, "setCheckInList: ");
        notifyDataSetChanged();
    }
    //public Context getContext() {return this.getContext();}

    @Override
    public int getItemCount() {
        return checkInList == null ? 0 : checkInList.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.i(TAG, "onCreateViewHolder: ");
        View view = LayoutInflater.from(
                parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
        ViewHolder checkInListViewHolder = new ViewHolder(view);
        return checkInListViewHolder;

    }
    public void deleteItem(int position) {
        mRecentlyDeletedItem = checkInList.get(position);
        mRecentlyDeletedItemPosition = position;

        checkInList.remove(position);
        notifyItemRemoved(position);
        showUndoSnackbar();
    }
    //private getContext(Context context) {
    //    context = this.getContext();
    //    return context;
   // }
    private void showUndoSnackbar() {
        //View view = mActivity.findViewById(R.id.check_in_recent_recycler_view);
        Snackbar snackbar = Snackbar
                .make(coordinatorLayout, "Item was removed from the list.", Snackbar.LENGTH_LONG);
        //Snackbar snackbar = Snackbar.make(view, R.string.checkin_recent_swipetodelete,
        //        Snackbar.LENGTH_LONG);
        snackbar.setAction(R.string.snack_bar_undo, v -> undoDelete());
        snackbar.show();
    }

    private void undoDelete() {
        checkInList.add(mRecentlyDeletedItemPosition,
                mRecentlyDeletedItem);
        notifyItemInserted(mRecentlyDeletedItemPosition);
    }
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int listPosition) {

        TextView checkInLastDateTime = holder.checkInLastDateTime;
        TextView checkInTitle = holder.checkInTitle;
        TextView checkInDestinationName = holder.checkInDestinationName;
        TextView checkInComments = holder.checkInComments;
        holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
        holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);

        Log.i(TAG, "onBindViewHolder: ");

        checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
        checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
        checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
        checkInComments.setText(checkInList.get(listPosition).getCheckInComments());

        ImageView checkInEditButton = holder.checkInEditButton;
        ImageView checkInResendButton = holder.checkInResendButton;

        ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
        ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);

        editCheckInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //put in edit check in logic
                Log.i(TAG, "onClick: for edit check in");
                //put in logic to switch to activity for add/edit checkin

            }
        }
        );
        resendCheckInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //put in resend logic
                Log.i(TAG, "onClick:  for resend");
                //add logic to store new check in table row and verify refresh of check in rows
                // on check in recent list

            }
        });

        }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView checkInLastDateTime;
        TextView checkInTitle;
        TextView checkInDestinationName;
        TextView checkInComments;
        ImageView checkInEditButton;
        ImageView checkInResendButton;
        ViewHolder(View itemView) {
            super(itemView);
            Log.i(TAG, "ViewHolder: ");
            checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
            checkInTitle = itemView.findViewById(R.id.checkInTitle);
            checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
            checkInComments = itemView.findViewById(R.id.checkInComments);
            checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
            checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
            //recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

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

Here is the Swipe To Delete code

```<code>package com.example.checkingin;

import android.graphics.Canvas;
import android.graphics.Color;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class CheckInRequestSwipeToDelete extends ItemTouchHelper.SimpleCallback {
    private CheckInListAdapter mAdapter;
    private Drawable icon;
    private final ColorDrawable background;

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int position = viewHolder.getAdapterPosition();
        mAdapter.deleteItem(position);
    }
    public CheckInRequestSwipeToDelete(CheckInListAdapter adapter) {
        super(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
        mAdapter = adapter;
        icon = ContextCompat.getDrawable(mAdapter.getContext(),R.drawable.baseline_delete_sweep_white_24dp));
        background = new ColorDrawable(Color.RED);
    }
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        // used for up and down movements
        return false;
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX,
                dY, actionState, isCurrentlyActive);
        View itemView = viewHolder.itemView;
        int backgroundCornerOffset = 20;
        if (dX > 0) { // Swiping to the right
            background.setBounds(itemView.getLeft(), itemView.getTop(),
                    itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
                    itemView.getBottom());

        } else if (dX < 0) { // Swiping to the left
            background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                    itemView.getTop(), itemView.getRight(), itemView.getBottom());
        } else { // view is unSwiped
            icon.setBounds(0, 0, 0, 0);
            background.setBounds(0, 0, 0, 0);
        }
        background.draw(c);
        int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconBottom = iconTop + icon.getIntrinsicHeight();

        if (dX > 0) { // Swiping to the right
            int iconLeft = itemView.getLeft() + iconMargin;
            int iconRight = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth();

            icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

            background.setBounds(itemView.getLeft(), itemView.getTop(),
                    itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
                    itemView.getBottom());
        } else if (dX < 0) { // Swiping to the left
            int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
            int iconRight = itemView.getRight() - iconMargin;
            icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

            background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                    itemView.getTop(), itemView.getRight(), itemView.getBottom());
        } else { // view is unSwiped
            background.setBounds(0, 0, 0, 0);
        }

        background.draw(c);
    }

}
</code>```

答: You can pass icon Drawable via constructor, it's better instead of getting context from adapter</p>

Body:
I have implemented a recyclerview within a fragment. Working to implement a swipetodelete for rows within the recycler view.  When using some example code for the swipe, it is looking to establish context for the ContextCompat.getDrawable() method.  What is the best way to set the context?

The problem line of code for setting the icon in the Swipe To Delete code is

icon = ContextCompat.getDrawable(mAdapter.getContext(),R.drawable.baseline_delete_sweep_white_24dp));

Here is the CheckInListAdapter code for the recyclerview.

package com.example.checkingin;

import android.content.Context;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.snackbar.Snackbar;

import java.util.List;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
    private int checkInListLayout;
    private List<CheckInTable> checkInList;
    private CoordinatorLayout coordinatorLayout;
    private CheckInTable mRecentlyDeletedItem;
    private int mRecentlyDeletedItemPosition;

    public CheckInListAdapter(int layoutId) {
        Log.i(TAG, "CheckInListAdapter: ");
        checkInListLayout = layoutId;
    }

    public void setCheckInList(List<CheckInTable> allCheckIn) {
        checkInList = allCheckIn;
        Log.i(TAG, "setCheckInList: ");
        notifyDataSetChanged();
    }
    //public Context getContext() {return this.getContext();}

    @Override
    public int getItemCount() {
        return checkInList == null ? 0 : checkInList.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.i(TAG, "onCreateViewHolder: ");
        View view = LayoutInflater.from(
                parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
        ViewHolder checkInListViewHolder = new ViewHolder(view);
        return checkInListViewHolder;

    }
    public void deleteItem(int position) {
        mRecentlyDeletedItem = checkInList.get(position);
        mRecentlyDeletedItemPosition = position;

        checkInList.remove(position);
        notifyItemRemoved(position);
        showUndoSnackbar();
    }
    //private getContext(Context context) {
    //    context = this.getContext();
    //    return context;
   // }
    private void showUndoSnackbar() {
        //View view = mActivity.findViewById(R.id.check_in_recent_recycler_view);
        Snackbar snackbar = Snackbar
                .make(coordinatorLayout, "Item was removed from the list.", Snackbar.LENGTH_LONG);
        //Snackbar snackbar = Snackbar.make(view, R.string.checkin_recent_swipetodelete,
        //        Snackbar.LENGTH_LONG);
        snackbar.setAction(R.string.snack_bar_undo, v -> undoDelete());
        snackbar.show();
    }

    private void undoDelete() {
        checkInList.add(mRecentlyDeletedItemPosition,
                mRecentlyDeletedItem);
        notifyItemInserted(mRecentlyDeletedItemPosition);
    }
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int listPosition) {

        TextView checkInLastDateTime = holder.checkInLastDateTime;
        TextView checkInTitle = holder.checkInTitle;
        TextView checkInDestinationName = holder.checkInDestinationName;
        TextView checkInComments = holder.checkInComments;
        holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
        holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);

        Log.i(TAG, "onBindViewHolder: ");

        checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
        checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
        checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
        checkInComments.setText(checkInList.get(listPosition).getCheckInComments());

        ImageView checkInEditButton = holder.checkInEditButton;
        ImageView checkInResendButton = holder.checkInResendButton;

        ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
        ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);

        editCheckInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //put in edit check in logic
                Log.i(TAG, "onClick: for edit check in");
                //put in logic to switch to activity for add/edit checkin

            }
        }
        );
        resendCheckInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //put in resend logic
                Log.i(TAG, "onClick:  for resend");
                //add logic to store new check in table row and verify refresh of check in rows
                // on check in recent list

            }
        });

        }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView checkInLastDateTime;
        TextView checkInTitle;
        TextView checkInDestinationName;
        TextView checkInComments;
        ImageView checkInEditButton;
        ImageView checkInResendButton;
        ViewHolder(View itemView) {
            super(itemView);
            Log.i(TAG, "ViewHolder: ");
            checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
            checkInTitle = itemView.findViewById(R.id.checkInTitle);
            checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
            checkInComments = itemView.findViewById(R.id.checkInComments);
            checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
            checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
            //recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
        }
    }
}

Here is the Swipe To Delete code

package com.example.checkingin;

import android.graphics.Canvas;
import android.graphics.Color;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class CheckInRequestSwipeToDelete extends ItemTouchHelper.SimpleCallback {
    private CheckInListAdapter mAdapter;
    private Drawable icon;
    private final ColorDrawable background;

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int position = viewHolder.getAdapterPosition();
        mAdapter.deleteItem(position);
    }
    public CheckInRequestSwipeToDelete(CheckInListAdapter adapter) {
        super(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
        mAdapter = adapter;
        icon = ContextCompat.getDrawable(mAdapter.getContext(),R.drawable.baseline_delete_sweep_white_24dp));
        background = new ColorDrawable(Color.RED);
    }
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        // used for up and down movements
        return false;
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX,
                dY, actionState, isCurrentlyActive);
        View itemView = viewHolder.itemView;
        int backgroundCornerOffset = 20;
        if (dX > 0) { // Swiping to the right
            background.setBounds(itemView.getLeft(), itemView.getTop(),
                    itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
                    itemView.getBottom());

        } else if (dX < 0) { // Swiping to the left
            background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                    itemView.getTop(), itemView.getRight(), itemView.getBottom());
        } else { // view is unSwiped
            icon.setBounds(0, 0, 0, 0);
            background.setBounds(0, 0, 0, 0);
        }
        background.draw(c);
        int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconBottom = iconTop + icon.getIntrinsicHeight();

        if (dX > 0) { // Swiping to the right
            int iconLeft = itemView.getLeft() + iconMargin;
            int iconRight = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth();

            icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

            background.setBounds(itemView.getLeft(), itemView.getTop(),
                    itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
                    itemView.getBottom());
        } else if (dX < 0) { // Swiping to the left
            int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
            int iconRight = itemView.getRight() - iconMargin;
            icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

            background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                    itemView.getTop(), itemView.getRight(), itemView.getBottom());
        } else { // view is unSwiped
            background.setBounds(0, 0, 0, 0);
        }

        background.draw(c);
    }

}


问:
Graphql mutation query : how to access the data elements
```<code> const MUTATION_QUERY = gql`
  mutation MUTATION_QUERY(
    $name: bigint!
  ) {
    insert_name(
      objects: {
        name: $name
      }
    ) {
      returning {
        id
        name
      }
    }
  }
`;

const [onClick, { error, data }] = useMutation<{}, {}>(MUTATION_QUERY, {
        variables: {
          name: 1234,
        },
      });
</code>```

My mutation query is inserting name in my table and autogenerating the id. On console logging the data variable I can view the fields id and name in the data object. But I am not able to access them them individually. How can I console.log "id". Thank you.

the console.log(data) looks like : {insert_name: {...}}

which expands to :

```<code>insert_name:
 returning: Array(1)
   0: {id: 1, name: 1234}
   length: 1
   _proto_: Array(0)
 _typename: "insert_name_mutation_response
</code>```

答: We can also use onCompleted method provided in useMutation if we want to process the result of the query. </p>

Body:
 const MUTATION_QUERY = gql`
  mutation MUTATION_QUERY(
    $name: bigint!
  ) {
    insert_name(
      objects: {
        name: $name
      }
    ) {
      returning {
        id
        name
      }
    }
  }
`;

const [onClick, { error, data }] = useMutation<{}, {}>(MUTATION_QUERY, {
        variables: {
          name: 1234,
        },
      });

My mutation query is inserting name in my table and autogenerating the id. On console logging the data variable I can view the fields id and name in the data object. But I am not able to access them them individually. How can I console.log "id". Thank you.

the console.log(data) looks like : {insert_name: {...}}

which expands to :

insert_name:
 returning: Array(1)
   0: {id: 1, name: 1234}
   length: 1
   _proto_: Array(0)
 _typename: "insert_name_mutation_response


问:
How can i make first letter of all words in a string uppercase recursively?
I wonder how can i make this. I don't want any iteration or isalpha() and toupper() functions. We want to use our own code to read input. We assume that user enters all characters lowercase. This is what i've tried so far:

```<code>define MAX_LENGTH 100

int read_line(char str[],int);
void capitalize(char[]);

int main (void){
    char A[MAX_LENGTH];
printf("Enter a text \n");
read_line(A, MAX_LENGTH);

capitalize(A);
puts(A);

}

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }
</code>```

Output is like this:

Enter a text:

asdf sdf df

Asdf sdf df

What is wrong with my code?

答:
You code is invalid. For example even the function read_line

```<code>int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}
</code>```

is incorrect at least because when i is equal to MAX_LENGTH -1 there is an access memory beyond the character array

```<code>str[i] = '\0';
</code>```

That is the condition of the loop is initially written incorrectly.

As for the recursive function then it can look for example the following way.

```<code>#include <stdio.h>

int is_blank( char c )
{
    return c == ' ' || c == '\t';
}

char * capitalize( char *s )
{
    if ( *s )
    {
        int blank = is_blank( *s );

        if ( !blank )
        {
            *s &= ~' ';
        }

        capitalize( s + 1 );

        if ( !blank && !is_blank( *( s + 1 ) ) && *( s + 1 ) )
        {
            *( s + 1 ) |= ' ';
        }
    }

    return s;
}

int main(void)
{
    char s[] = "hello everybody. how do you do?";

    puts( s );
    puts( capitalize( s ) );

    return 0;
}
</code>```

The program output is

```<code>hello everybody. how do you do?
Hello Everybody. How Do You Do?
</code>```

Here is a similar demonstrative program but with your fixed function read_line.

```<code>#include <stdio.h>

#define MAX_LENGTH  100

int is_blank( char c )
{
    return c == ' ' || c == '\t';
}

char * capitalize( char *s )
{
    if ( *s )
    {
        int blank = is_blank( *s );

        if ( !blank )
        {
            *s &= ~' ';
        }

        capitalize( s + 1 );

        if ( !blank && !is_blank( *( s + 1 ) ) && *( s + 1 ) )
        {
            *( s + 1 ) |= ' ';
        }
    }

    return s;
}

size_t read_line( char *s, size_t n )
{
    int ch;
    size_t i = 0;

    while ( i + 1 < n && ( ch = getchar() ) != EOF && ch != '\n' )
    {
        s[i++] = ch;
    }

    s[i] = '\0';

    return i;
}

int main(void)
{
    char s[MAX_LENGTH];

    read_line( s, MAX_LENGTH );

    puts( s );

    puts( capitalize( s ) );

    return 0;
}
</code>```

If to enter the string

```<code>hello everybody. how do you do?
</code>```

then the program output will be the same as shown above.

```<code>hello everybody. how do you do?
Hello Everybody. How Do You Do?
</code>```

If the bit-wise operations is unclear for you then you can substitute this statement

for this statement

```<code>*s &= ~' ';
</code>```

for this statement

```<code>*s -= 'a' - 'A';
</code>```

and this statement

```<code>*( s + 1 ) |= ' ';
</code>```

for this statement

```<code>*( s + 1 ) += 'a' - 'A';
</code>```

If to use your approach to the implementation of a recursive function with a static variable then it will be interesting to you why your function does not work will not be?

Let's consider it ignoring the first statement with the call of strlen.

```<code>void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }
</code>```

First of all after the first call the function for one string you may not call it a second time for another string because the static variable i will not be already equal to 0.

The condition of the if statement should be written at least like

```<code>    if ( i == 0 || str[i-1]==' ' )
</code>```

that is the order of sub-expressions shall be changed.

The return statement shall not contain an expression

```<code>      return capitalize(&str[i]);
</code>```

you could just write

```<code>      capitalize(&str[i]);
</code>```

Nevertheless the initial value of the pointer str was changed. However within the function you are using the index i relative the initial value of str of the first call of the function.

And I am sure it is interesting to you how correctly to rewrite the function, is not it?

The function can look the following way as it is shown in the demonstrative program below.

```<code>#include <stdio.h>

#define MAX_LENGTH  100

int is_blank( char c )
{
    return c == ' ' || c == '\t';
}

char * capitalize( char *s )
{
    static size_t i = 0;

    if ( *( s + i ) )
    {
        if ( !is_blank( s[i] ) && ( i == 0  || is_blank( s[i-1] ) ) )
        {
            s[i] -= 'a' - 'A';
        }

        ++i;

        capitalize( s );

        --i;
    }

    return s;
}

size_t read_line( char *s, size_t n )
{
    int ch;
    size_t i = 0;

    while ( i + 1 < n && ( ch = getchar() ) != EOF && ch != '\n' )
    {
        s[i++] = ch;
    }

    s[i] = '\0';

    return i;
}

int main(void)
{
    char s[MAX_LENGTH];

    read_line( s, MAX_LENGTH );

    puts( s );

    puts( capitalize( s ) );

    return 0;
}
</code>```

Body:
I wonder how can i make this. I don't want any iteration or isalpha() and toupper() functions. We want to use our own code to read input. We assume that user enters all characters lowercase. This is what i've tried so far:

define MAX_LENGTH 100

int read_line(char str[],int);
void capitalize(char[]);

int main (void){
    char A[MAX_LENGTH];
printf("Enter a text \n");
read_line(A, MAX_LENGTH);

capitalize(A);
puts(A);

}

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }

Output is like this:

Enter a text:

asdf sdf df

Asdf sdf df

What is wrong with my code?

Body:
You code is invalid. For example even the function read_line

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

is incorrect at least because when i is equal to MAX_LENGTH -1 there is an access memory beyond the character array

str[i] = '\0';

That is the condition of the loop is initially written incorrectly.

As for the recursive function then it can look for example the following way.

#include <stdio.h>

int is_blank( char c )
{
    return c == ' ' || c == '\t';
}

char * capitalize( char *s )
{
    if ( *s )
    {
        int blank = is_blank( *s );

        if ( !blank )
        {
            *s &= ~' ';
        }

        capitalize( s + 1 );

        if ( !blank && !is_blank( *( s + 1 ) ) && *( s + 1 ) )
        {
            *( s + 1 ) |= ' ';
        }
    }

    return s;
}

int main(void)
{
    char s[] = "hello everybody. how do you do?";

    puts( s );
    puts( capitalize( s ) );

    return 0;
}

The program output is

hello everybody. how do you do?
Hello Everybody. How Do You Do?

Here is a similar demonstrative program but with your fixed function read_line.

#include <stdio.h>

#define MAX_LENGTH  100

int is_blank( char c )
{
    return c == ' ' || c == '\t';
}

char * capitalize( char *s )
{
    if ( *s )
    {
        int blank = is_blank( *s );

        if ( !blank )
        {
            *s &= ~' ';
        }

        capitalize( s + 1 );

        if ( !blank && !is_blank( *( s + 1 ) ) && *( s + 1 ) )
        {
            *( s + 1 ) |= ' ';
        }
    }

    return s;
}

size_t read_line( char *s, size_t n )
{
    int ch;
    size_t i = 0;

    while ( i + 1 < n && ( ch = getchar() ) != EOF && ch != '\n' )
    {
        s[i++] = ch;
    }

    s[i] = '\0';

    return i;
}

int main(void)
{
    char s[MAX_LENGTH];

    read_line( s, MAX_LENGTH );

    puts( s );

    puts( capitalize( s ) );

    return 0;
}

If to enter the string

hello everybody. how do you do?

then the program output will be the same as shown above.

hello everybody. how do you do?
Hello Everybody. How Do You Do?

If the bit-wise operations is unclear for you then you can substitute this statement

for this statement

*s &= ~' ';

for this statement

*s -= 'a' - 'A';

and this statement

*( s + 1 ) |= ' ';

for this statement

*( s + 1 ) += 'a' - 'A';

If to use your approach to the implementation of a recursive function with a static variable then it will be interesting to you why your function does not work will not be?

Let's consider it ignoring the first statement with the call of strlen.

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }

First of all after the first call the function for one string you may not call it a second time for another string because the static variable i will not be already equal to 0.

The condition of the if statement should be written at least like

    if ( i == 0 || str[i-1]==' ' )

that is the order of sub-expressions shall be changed.

The return statement shall not contain an expression

      return capitalize(&str[i]);

you could just write

      capitalize(&str[i]);

Nevertheless the initial value of the pointer str was changed. However within the function you are using the index i relative the initial value of str of the first call of the function.

And I am sure it is interesting to you how correctly to rewrite the function, is not it?

The function can look the following way as it is shown in the demonstrative program below.

#include <stdio.h>

#define MAX_LENGTH  100

int is_blank( char c )
{
    return c == ' ' || c == '\t';
}

char * capitalize( char *s )
{
    static size_t i = 0;

    if ( *( s + i ) )
    {
        if ( !is_blank( s[i] ) && ( i == 0  || is_blank( s[i-1] ) ) )
        {
            s[i] -= 'a' - 'A';
        }

        ++i;

        capitalize( s );

        --i;
    }

    return s;
}

size_t read_line( char *s, size_t n )
{
    int ch;
    size_t i = 0;

    while ( i + 1 < n && ( ch = getchar() ) != EOF && ch != '\n' )
    {
        s[i++] = ch;
    }

    s[i] = '\0';

    return i;
}

int main(void)
{
    char s[MAX_LENGTH];

    read_line( s, MAX_LENGTH );

    puts( s );

    puts( capitalize( s ) );

    return 0;
}


问:
SQL - Comparing sql ddl programmatically
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.

Lets say we have a table named table1

Steps:

```<code>1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.
</code>```

For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).

Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.

答:
Since you are looking for a Python API you may want to consider using something like
GitPython

For the comparison (your step 2), commit the file and let git determine if there were any changes.
EDIT: Adding to using Git for comparison (git diff) given your comment on white-space, see this answer for guidance.

Body:
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.

Lets say we have a table named table1

Steps:

1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.

For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).

Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.


问:
Windows 10 docker-compose takes 100% disk usage
Docker is very slow on windows 10. I followed a lot of the tasks to make the index not run on the folder and tried to speed things up. The process appears to take up 100% of the CPU, which is fine, but also 100%+ of the disk IO and that is a huge bottleneck. Tasks that take less than 10 seconds to run on linux or mac are taking upwards of 40 minutes to complete on windows.

This is simply not usable in any meaningful way. Is there a reason why docker-compose insists on writing 150MB/s to disk rather than using ram? I have tons of ram. I could actually store the entire docker-container system in ram and have about 10GB left over.

BTW, while it is feasible to insist that docker only run on Linux for servers, development has to support windows, linux, and mac. I cannot believe that testing did not reveal windows 10 support dearly lacking and no, turning off anti-virus is absolutely not an option. Many docker developers do not have the proper permissions to do so and recommending that docker users disable anti-virus is an incredible request. Also, disabling anti-virus or the like still does not answer why docker takes up 100% of disk IO.

答:
So recently I was having the same issue. I was using Docker with DDEV for a Drupal development environment. Running composer require drupal/something took many many hours to complete. I tried some of the trouble shooting items on Why is PHP Composer so slow?. Specifically, running and using composer global require hirak/prestissimo. At least this actually ran. It was promising. It however did not fix the issue. I tried uninstalling an reinstalling DDEV and Docker as suggested by Spiceworks: Docker for windows reach 100% disk usage after win 10 in-place update. This also did not work. I decided to try ddev composer install outside of the container instead of composer install inside the container. Composer gave me the error: This host computer is unable to create real symlinks, please see the docs to enable developer mode: Turned on windows development mode and composer started to work as it should.

Solution:
Turn on windows developer mode so system links can be used.

Hope this helps y'all!


问:
Is there a way to filter the one drop-down based on another drop down using pure javascript?
I have two fields 'Controller Type' and 'Test Type'. What i want is that when controller is 'EBOD' the tests which should be coming in the dropdown are ('BFT','CTO','JBOD Generic'). I tried doing that using javascript but couldn't get an effective solution. Can anyone please help to achieve this?
Any help is much appreciated.
Thanks

```<code><fieldset>
                <label for='Controller Type'><strong>Controller Type </strong></label>
                <select name='controller' id="Controller" onchange="showsecondlist()" required>
                    <option value=""> - Select the Controller - </option>
                    <option data-extra=true value='RAID'>RAID
                    <option data-extra=true value='EBOD'>EBOD
                    <option data-extra=true value='AP'>AP
                </select>
            </fieldset>

            <fieldset>
                <label for='Test Type'><strong>Test Type</strong></label>
                <select name='test' id="Test" required >
                    <option value=""> - Select The Test - </option>
                    <option data-extra=true value='BFT'>BFT
                    <option data-extra=true value='CTO'>CTO
                    <option data-extra=true value='RAID Generic'>RAID Generic
                    <option data-extra=true value='Port Check' >Port Check
                    <option data-extra=true value='FW Generic' >FW Generic
                    <option data-extra=true value='EBOD Generic' >JBOD Generic
                </select>
            </fieldset>
</code>```

I tried something like this, which didn't work.

```<code>function showsecondlist()
{
var uservalue= document.getElementById("Controller").value;
if(uservalue=='EBOD')
document.getElementById("Test").value.innerHTML='<option value="1.1">BFT</option><option value="1.2">CTO</option><option value="1.2">JBOD Generic</option>';
}
</code>```

答:
I would use sth. like the following:

// mapping from values of first select to the ones
// to be shown in second when that value is selected
const mappings = {
  a: ['d','e'],
  b: ['e','f'],
  c: ['d','g']
};
const first = document.getElementById('first');
const second = document.getElementById('second');

// when first select changes, show all options of the second,
// if no mapping exists, otherwise show mapped and hide the others
first.onchange = ({ target: { value: selected }}) => {
  [...second.options].forEach((o) => {
    if (!mappings[selected] || mappings[selected].includes(o.value)) {
      o.style.display = '';
    } else {
      o.style.display = 'none';
    }
  });
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>
  First select:
  <select id="first">
    <option>...</option>
    <option>a</option>
    <option>b</option>
    <option>c</option>
    <option>d</option>
  </select>
</label>

<label>
  Second select:
  <select id="second">
    <option>d</option>
    <option>e</option>
    <option>f</option>
    <option>g</option>
  </select>
</label></code>```

Body:
I have two fields 'Controller Type' and 'Test Type'. What i want is that when controller is 'EBOD' the tests which should be coming in the dropdown are ('BFT','CTO','JBOD Generic'). I tried doing that using javascript but couldn't get an effective solution. Can anyone please help to achieve this?
Any help is much appreciated.
Thanks

<fieldset>
                Controller Type
                <select name='controller' id="Controller" onchange="showsecondlist()" required>
                    <option value=""> - Select the Controller - </option>
                    <option data-extra=true value='RAID'>RAID
                    <option data-extra=true value='EBOD'>EBOD
                    <option data-extra=true value='AP'>AP
                </select>
            </fieldset>

            <fieldset>
                Test Type
                <select name='test' id="Test" required >
                    <option value=""> - Select The Test - </option>
                    <option data-extra=true value='BFT'>BFT
                    <option data-extra=true value='CTO'>CTO
                    <option data-extra=true value='RAID Generic'>RAID Generic
                    <option data-extra=true value='Port Check' >Port Check
                    <option data-extra=true value='FW Generic' >FW Generic
                    <option data-extra=true value='EBOD Generic' >JBOD Generic
                </select>
            </fieldset>

I tried something like this, which didn't work.

function showsecondlist()
{
var uservalue= document.getElementById("Controller").value;
if(uservalue=='EBOD')
document.getElementById("Test").value.innerHTML='<option value="1.1">BFT</option><option value="1.2">CTO</option><option value="1.2">JBOD Generic</option>';
}

Body:
I would use sth. like the following:

// mapping from values of first select to the ones
// to be shown in second when that value is selected
const mappings = {
  a: ['d','e'],
  b: ['e','f'],
  c: ['d','g']
};
const first = document.getElementById('first');
const second = document.getElementById('second');

// when first select changes, show all options of the second,
// if no mapping exists, otherwise show mapped and hide the others
first.onchange = ({ target: { value: selected }}) => {
  [...second.options].forEach((o) => {
    if (!mappings[selected] || mappings[selected].includes(o.value)) {
      o.style.display = '';
    } else {
      o.style.display = 'none';
    }
  });
};

<label>
  First select:
  <select id="first">
    <option>...</option>
    <option>a</option>
    <option>b</option>
    <option>c</option>
    <option>d</option>
  </select>
</label>

<label>
  Second select:
  <select id="second">
    <option>d</option>
    <option>e</option>
    <option>f</option>
    <option>g</option>
  </select>
</label>


问:
Bixby runtime version 3
When using the latest version of Bixby Studio (7.11.0-r20b.14375), I am setting runtime-version (2) for my capsule and getting the following warning:

```<code>INFO A newer version is available: runtime-version(3)
</code>```

But when I go to the Bixby Developers documentation for runtime-version I don't see any documentation on version 3, only on version 1 and 2: https://bixbydevelopers.com/dev/docs/reference/type/capsule.runtime-version

Can anybody clarify what is the difference between runtime version 2 and runtime version 3?

答: The docs have been updated to show the latest runtime-version (3): https://bixbydevelopers.com/dev/docs/reference/type/capsule.runtime-version</p>

Title: Bixby runtime version 3

Body:
When using the latest version of Bixby Studio (7.11.0-r20b.14375), I am setting runtime-version (2) for my capsule and getting the following warning:

INFO A newer version is available: runtime-version(3)

But when I go to the Bixby Developers documentation for runtime-version I don't see any documentation on version 3, only on version 1 and 2: https://bixbydevelopers.com/dev/docs/reference/type/capsule.runtime-version

Can anybody clarify what is the difference between runtime version 2 and runtime version 3?


问:
Rails - how to combine incompatible statements with OR (Rails 5)
There is a Project model and Payment model:

```<code>class Project < ApplicationRecord
  has_many :payments
end

class Payment < ApplicationRecord
  belongs_to :project
end
</code>```

It is quite easy for me to combine queries for colums with either or OR and.

```<code>Project.where(projects[:created_at].gt(6.months.ago).or(projects[:updated_at].gt(1.month.ago)))
</code>```

The reason for using Arel is that the exact columns, operators and values comes from the user and Arel operators match very nicely with what the user can select.

However, if I want to combine this with data from another associated table, then I just cannot figure out what to do. ActiverRecord requires OR to be structurally compatible, so I cannot do:

Project.where(projects[:created_at].gt(6.months.ago)).or(Project.joins(:payments))

Something like this:
Project.where(projects[:created_at].gt(6.months.ago).or(projects.join(payments).on(projects[:id].eq(payments[:project_id]))))

raises exception: ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  subquery must return only one column.

One way I was able to do it was something like:
Project.where(projects[:created_at].gt(6.months.ago)).or(Project.where(id: Project.joins(:payments).select(:id)))

which generated SQL
SELECT "projects".* FROM "projects" WHERE (("projects"."created_at" > '2019-08-19 09:11:22.064298') OR "projects"."id" IN (SELECT "projects"."id" FROM "projects" INNER JOIN "payments" ON "payments"."project_id" = "projects"."id"))

Is this the best way to do it or is there a better way? Please there might be 10+ such clauses combined, involving multiple tables, using include on all the possible tables to make all individual clauses compatible is likely to be too expensive.

答:
Is there any reason why you can't keep your joins consistent across conditions? For example in Rails 5+ you can write:

```<code>Project.where(some_field: '12').joins(:payments)
       .or(
           Project.where(payments: {id: '1'}).joins(:payments)
       )
</code>```

Which would generate SQL like:

```<code>SELECT projects.* FROM projects
INNER JOIN payments ON (payments.project_id = project.id)
WHERE projects.some_field = 12 OR payments.id = 1
</code>```

Note:

Using your structurally incompatible example in the OP, you can simply add a join to the first condition to make it compatible:

```<code>Project.where(projects[:created_at].gt(6.months.ago)).joins(:payments).or(Project.joins(:payments))
</code>```

Body:
There is a Project model and Payment model:

class Project < ApplicationRecord
  has_many :payments
end

class Payment < ApplicationRecord
  belongs_to :project
end

It is quite easy for me to combine queries for colums with either or OR and.

Project.where(projects[:created_at].gt(6.months.ago).or(projects[:updated_at].gt(1.month.ago)))

The reason for using Arel is that the exact columns, operators and values comes from the user and Arel operators match very nicely with what the user can select.

However, if I want to combine this with data from another associated table, then I just cannot figure out what to do. ActiverRecord requires OR to be structurally compatible, so I cannot do:

Project.where(projects[:created_at].gt(6.months.ago)).or(Project.joins(:payments))

Something like this:
Project.where(projects[:created_at].gt(6.months.ago).or(projects.join(payments).on(projects[:id].eq(payments[:project_id]))))

raises exception: ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  subquery must return only one column.

One way I was able to do it was something like:
Project.where(projects[:created_at].gt(6.months.ago)).or(Project.where(id: Project.joins(:payments).select(:id)))

which generated SQL
SELECT "projects".* FROM "projects" WHERE (("projects"."created_at" > '2019-08-19 09:11:22.064298') OR "projects"."id" IN (SELECT "projects"."id" FROM "projects" INNER JOIN "payments" ON "payments"."project_id" = "projects"."id"))

Is this the best way to do it or is there a better way? Please there might be 10+ such clauses combined, involving multiple tables, using include on all the possible tables to make all individual clauses compatible is likely to be too expensive.

Body:
Is there any reason why you can't keep your joins consistent across conditions? For example in Rails 5+ you can write:

Project.where(some_field: '12').joins(:payments)
       .or(
           Project.where(payments: {id: '1'}).joins(:payments)
       )

Which would generate SQL like:

SELECT projects.* FROM projects
INNER JOIN payments ON (payments.project_id = project.id)
WHERE projects.some_field = 12 OR payments.id = 1

Note:

Using your structurally incompatible example in the OP, you can simply add a join to the first condition to make it compatible:

Project.where(projects[:created_at].gt(6.months.ago)).joins(:payments).or(Project.joins(:payments))


问:
Is that possible to be aware that Hotjar is now loaded in JavaScript?
I want to get userId from Hotjar but I need to make sure Hotjar is loaded. How can I dependent a function to Hotjar loaded something like using .then() to wait for promise.

```<code><Hotjar Code>
.
.
.
<End of Hotjar Code>

let x = hj.globals.get('userId').split('-').shift()
</code>```

Now I get the error TypeError: Cannot read property 'get' of undefined

答:
Referencing another SO question which is close to your question: Capturing Hotjar User ID in Google Tag Manager & Google Analytics

Anyway you could check if this property exists and if it's a function. At least this is how I solved it.

One thing might be that you need to wait for the DOM to be available:

```<code>document.addEventListener("DOMContentLoaded", function () {
    hj.globals.get('userId').split('-').shift()
};
</code>```

Another thing might be that you need to check if the script was loaded at all.

```<code>if (window.hj && typeof (window.hj) === "function") {
    hj.globals.get('userId').split('-').shift()
}
</code>```

With both in mind I would perhaps suggest the following code to be very save about it.

```<code>document.addEventListener("DOMContentLoaded", function () {
    if (window.hj && typeof (window.hj) === "function") {
        hj.globals.get('userId').split('-').shift()
    }
};
</code>```

Body:
I want to get userId from Hotjar but I need to make sure Hotjar is loaded. How can I dependent a function to Hotjar loaded something like using .then() to wait for promise.

<Hotjar Code>
.
.
.
<End of Hotjar Code>

let x = hj.globals.get('userId').split('-').shift()

Now I get the error TypeError: Cannot read property 'get' of undefined

Body:
Referencing another SO question which is close to your question: Capturing Hotjar User ID in Google Tag Manager & Google Analytics

Anyway you could check if this property exists and if it's a function. At least this is how I solved it.

One thing might be that you need to wait for the DOM to be available:

document.addEventListener("DOMContentLoaded", function () {
    hj.globals.get('userId').split('-').shift()
};

Another thing might be that you need to check if the script was loaded at all.

if (window.hj && typeof (window.hj) === "function") {
    hj.globals.get('userId').split('-').shift()
}

With both in mind I would perhaps suggest the following code to be very save about it.

document.addEventListener("DOMContentLoaded", function () {
    if (window.hj && typeof (window.hj) === "function") {
        hj.globals.get('userId').split('-').shift()
    }
};


问:
Java regex question
I have a text something like

```<code>ab1ab2ab3ab4cd
</code>```

Can one create a java regular expression to obtain all subtrings that start with "ab" and end with "cd"? e.g:

```<code>ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd
</code>```

Thanks

答:
```<code>/^ab[a-z0-9]+cd$/gm
</code>```

If only a b c and digits 0-9 can appear in the middle as in the examples:

```<code>/^ab[a-c\d]+cd$/gm
</code>```

See it in action: http://regexr.com?2tpdu

Title: Java regex question

Body:
I have a text something like

ab1ab2ab3ab4cd

Can one create a java regular expression to obtain all subtrings that start with "ab" and end with "cd"? e.g:

ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd

Thanks

Body:
/^ab[a-z0-9]+cd$/gm

If only a b c and digits 0-9 can appear in the middle as in the examples:

/^ab[a-c\d]+cd$/gm

See it in action: http://regexr.com?2tpdu


问:
How could avoid these terminal errors for ionic installation?
I formatted my computer because I had accidentally installed ionic with sudo. Now, I installed Catalina from the beginning and installed Node.js again. Although, I still face a problem installing ionic. </p>

答: Seems like youre not running the command with sudo permission, can you try to run with prefix sudo? if this doesn't work, verify if you have the permission granted to access these folders.</p>


问:
Group by of dataframe with average of a column
I am really new to python..just a week ago started learning it. I have a query and hope you guys can help me to solve it. Thanks in advance..!!

I have data in below format.

```<code>Date        Product Price   Discount
1/1/2020    A   17,490  30
1/1/2020    B   34,990  21
1/1/2020    C   20,734  11
1/2/2020    A   16,884  26
1/2/2020    B   26,990  40
1/2/2020    C   17,936  10
1/3/2020    A   16,670  36
1/3/2020    B   12,990  13
1/3/2020    C   30,990  43
</code>```

I want to take the average of discount column for each date and just have 2 columns.. It aint working out.. :(

```<code>Date        AVG_Discount
1/1/2020    x %
1/2/2020    y %
1/3/2020    z %
</code>```

What I have tried doing is below.. As I said, I am novice in Python so approach might be incorrect.. Need guidance guys.. TIA

```<code>mean_col=df.groupby(df['time'])['discount'].mean()
df=df.set_index(['time'])
df['mean_col']=mean_col
df=df.reset_index()
</code>```

答:
Apparently, you have read your DataFrame from a text file,
e.g. CSV, but with separator other than a comma.

Run df.info() and I assume that you got result something like below:

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 4 columns):
Date        9 non-null object
Product     9 non-null object
Price       9 non-null object
Discount    9 non-null int64
dtypes: int64(1), object(3)
</code>```

Note that Date, Product and Price columns are of object type
(actually, a string). This remark is especially importoant in case of
Price column, because to compte mean you should have source column
as a number (not a string).

So first you should convert Date and Price columns to proper types
(datetime and float). To do it run:

```<code>df.Date = pd.to_datetime(df.Date)
df.Price = df.Price.str.replace(',', '.').astype(float)
</code>```

Run df.info() again and now the result should be:

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 4 columns):
Date        9 non-null datetime64[ns]
Product     9 non-null object
Price       9 non-null float64
Discount    9 non-null int64
dtypes: datetime64[ns](1), float64(1), int64(1), object(1)
</code>```

And now you can compute the mean discount, running:

```<code>df.groupby('Date').Discount.mean()
</code>```

For your data I got:

```<code>Date
2020-01-01    20.666667
2020-01-02    25.333333
2020-01-03    30.666667
Name: Discount, dtype: float64
</code>```

Note that your code sample contains the following errors:

Argument of groupby is the column name (or a list of column names), so:

df between parentheses is not needed,

instead of time you should write Date (you have no time column).

Your Discount column is written starting with capital D.

Body:
I am really new to python..just a week ago started learning it. I have a query and hope you guys can help me to solve it. Thanks in advance..!!

I have data in below format.

Date        Product Price   Discount
1/1/2020    A   17,490  30
1/1/2020    B   34,990  21
1/1/2020    C   20,734  11
1/2/2020    A   16,884  26
1/2/2020    B   26,990  40
1/2/2020    C   17,936  10
1/3/2020    A   16,670  36
1/3/2020    B   12,990  13
1/3/2020    C   30,990  43

I want to take the average of discount column for each date and just have 2 columns.. It aint working out.. :(

Date        AVG_Discount
1/1/2020    x %
1/2/2020    y %
1/3/2020    z %

What I have tried doing is below.. As I said, I am novice in Python so approach might be incorrect.. Need guidance guys.. TIA

mean_col=df.groupby(df['time'])['discount'].mean()
df=df.set_index(['time'])
df['mean_col']=mean_col
df=df.reset_index()

Body:
Apparently, you have read your DataFrame from a text file,
e.g. CSV, but with separator other than a comma.

Run df.info() and I assume that you got result something like below:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 4 columns):
Date        9 non-null object
Product     9 non-null object
Price       9 non-null object
Discount    9 non-null int64
dtypes: int64(1), object(3)

Note that Date, Product and Price columns are of object type
(actually, a string). This remark is especially importoant in case of
Price column, because to compte mean you should have source column
as a number (not a string).

So first you should convert Date and Price columns to proper types
(datetime and float). To do it run:

df.Date = pd.to_datetime(df.Date)
df.Price = df.Price.str.replace(',', '.').astype(float)

Run df.info() again and now the result should be:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 4 columns):
Date        9 non-null datetime64[ns]
Product     9 non-null object
Price       9 non-null float64
Discount    9 non-null int64
dtypes: datetime64[ns](1), float64(1), int64(1), object(1)

And now you can compute the mean discount, running:

df.groupby('Date').Discount.mean()

For your data I got:

Date
2020-01-01    20.666667
2020-01-02    25.333333
2020-01-03    30.666667
Name: Discount, dtype: float64

Note that your code sample contains the following errors:

Argument of groupby is the column name (or a list of column names), so:

df between parentheses is not needed,

instead of time you should write Date (you have no time column).

Your Discount column is written starting with capital D.


问:
How do I set the file mask for find in path only for js or jsx in WebStorm?
I want to use Find in Path only for js and jsx files in WebStorm. I tried to set \*.js\* in file mask but it includes other files like js.map.

I really appreciate any advise how to do this.

答: You can specify several file types using commas as separators, see https://www.jetbrains.com/help/webstorm/2019.3/finding-and-replacing-text-in-project.html#exclude_type


问:
Script to copy 4000 rows +
I've been working with a copy script that works fine with minimal rows. I have a form response sheet that will grow up to 4000 rows before i clean it out. I want to copy the response sheet to another google project sheet but my script keeps timing out or doesn't run at all. I need an efficient script to copy large amounts of data to several different spreadsheets. I'm sure this is cake for the Pro's here, I'm still learning.

Here's my script:

function CopyRange() {
  var sss = SpreadsheetApp.openById('myspreadsheet-ID'); //replace with source ID
  var ss = sss.getSheetByName('Sheet4'); //replace with source Sheet tab name
  var range = ss.getRange('A:Q'); //assign the range you want to copy
  var data = range.getValues();
  var tss = SpreadsheetApp.openById('Destination-spreadsheet-ID'); //replace with destination ID
  var ts = tss.getSheetByName('data collect'); //replace with destination Sheet tab name
  var app = SpreadsheetApp;
  ts.clear({contentsOnly: true});
  ts.getRange(ts.getLastRow()+1, 1,4000,15).setValues(data); //you will need to define the size of
  the copied data see getRange()
}
```

答:
```<code> function copyStuffToSeveralSpreadsheets() {
  var ssA=['ssid1','ssid2','ssid3'.....];
  var ss=SpreadsheetApp.openById('mySSID');
  var sh=ss.getSheetByName('Sheet4');
  var rg=sh.getRange(1,1,sh.getLastRow(),17);
  var vA=rg.getValues();
  ssA.forEach(function(r,i){
    var tss=SpreadsheetApp.openById(ssA[i]);
    var tsh=tss.getSheetByName('data collect');
    tsh.clearContents();//remove to append
    tsh.getRange(1,1,vA.length,vA[0].length).setValues(vA);//remove to append
    //tsh.getRange(tsh.getLastRow()+1,1,vA.length,vA[0].length).setValues(vA);//enable this to append to the bottom of last dataset
  });
}
</code>```

Title: Script to copy 4000 rows +


问:
Truth tables in code? How to structure state machine?
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

```<code>u8 newState[] = decisionTable[input1][input2][input3][input4];
</code>```

And then I could access the output values with:

```<code>setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );
</code>```

But in order to get that, it looks like I would have to do a fairly confusing table like so:

```<code>static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};
</code>```

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

```<code>#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))
</code>```

And that will let my truth table array look like this:

```<code>static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};
</code>```

And I can then access my truth table like so:

```<code>decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]
</code>```

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

答:
I'd suggest either (preferred approaches first):

Use a macro to intialize each "row" - this will hide the braces within the macro call.

Use comments to break up the rows.

Use an init function to initialize the context explicitly - perhaps use functions to initialize each section. This is similar to the first option above but has a disadvantage that the init function must be invoked before the state machine can be used.

OwnerDisplayName: HanClinto

ContentLicense: CC BY-SA 2.5

Body:
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

u8 newState[] = decisionTable[input1][input2][input3][input4];

And then I could access the output values with:

setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );

But in order to get that, it looks like I would have to do a fairly confusing table like so:

static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))

And that will let my truth table array look like this:

static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};

And I can then access my truth table like so:

decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

LastEditorDisplayName: Im safe against SQL injection

OwnerDisplayName: Stephen Doyle

LastEditorDisplayName: Stephen Doyle


问:
How to update location in CLLocationManager
I am working on map application and when i run the app it shows my current location and getting the right latitude and longitude , have to send the information to someone through mail, I have implemented all the things and till the mail is send is working fine, i only need help regarding updating CLLocationManager function, after sending the mail, i have tried to call the function [locationmanager startupdatinglocation] however it got get called for the second time, even i have put NSTimer to ask for the location for second time.</p>

答:
Try like this place,

```<code> locationManager = [[CLLocationManager alloc] init];
 locationManager.delegate = self;
 [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(UpdateLocation) userInfo:nil repeats:YES];
</code>```

In viewdidload and call this method from timer,

```<code>-(void)UpdateLocation
{
   [locationManager startUpdatingLocation];
}
</code>```

Body:
Try like this place,

 locationManager = [[CLLocationManager alloc] init];
 locationManager.delegate = self;
 [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(UpdateLocation) userInfo:nil repeats:YES];

In viewdidload and call this method from timer,

-(void)UpdateLocation
{
   [locationManager startUpdatingLocation];
}


问:
JetBrains IDEs - limit the length of argument name tooltips

Is it possible to limit the length of argument tooltips? Either prohibit long tooltips from displaying, or cut them after a certain amount of characters.

I do not want to switch them off completely, it's just sometimes that a monstrosity like this pops up.

答: There is a related issue which should be addressed in 2020.1 EAP builds.</p>