问:
Select all rows but park on specific
I need to show all rows in a table but park on a specific one.

```<code>Select * from t_table
</code>```

will show me all but park on the top.

```<code>select * from t_table where id=1000
</code>```

will only show me id=1000.

what I need is

```<code>select * from t_table locate id=1000
</code>```

is this possible ?

Example :

If the storedprocedure showing this select has a parameter @PartCode.
This can be NULL (show all) of a certain partcode. f.e. 2000443

The select in the stored procedure should park on this partcode but not filter

答:
You could achieve this with a case statement in an order by. It would always return your specific record as row 1 but would still order by other IDs below.

Something like the following should work:

```<code>ORDER BY
   CASE Partcode
      WHEN 2000443 THEN 1 --2000443 being the ID to return first.
      ELSE 2
   END, id
</code>```

Title: Select all rows but park on specific

Body:
I need to show all rows in a table but park on a specific one.

Select * from t_table

will show me all but park on the top.

select * from t_table where id=1000

will only show me id=1000.

what I need is

select * from t_table locate id=1000

is this possible ?

Example :

If the storedprocedure showing this select has a parameter @PartCode.
This can be NULL (show all) of a certain partcode. f.e. 2000443

The select in the stored procedure should park on this partcode but not filter

Body:
You could achieve this with a case statement in an order by. It would always return your specific record as row 1 but would still order by other IDs below.

Something like the following should work:

ORDER BY
   CASE Partcode
      WHEN 2000443 THEN 1 --2000443 being the ID to return first.
      ELSE 2
   END, id


来源: stackexchange

问:
Hi am a new R learner.. wrote below two identical code on editior, 2nd one runs fine, while first one has error.. what is wrong with 1st one
1st One

Not run  there is an error

```<code>repeat{
sc=scan(nmax=1)
if (sc>9) {break} else{
b=switch(sc,"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE")
cat(“\n The Number Entered is “, sc ,” In Alpha it is  “, b,”\n”) } }
</code>```

the Error is
Error: unexpected input in:
"b=switch(sc,"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE")
cat(“"

2nd One
This one runs ok

```<code>repeat{
sc=scan(nmax=1)
if (sc>9) {break} else{
b=switch(sc,"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE")
cat("\n The Entered Number is ", sc ," In Alpha it is ", b,"\n") } }
</code>```

1: 4
Read 1 item
The Entered Number is  4  In Alpha it is  FOUR

答:
“ is not allowed in R as a parentheses.

In the first piece of code you are using “ instead of ".

“ may appear if you copy your code into MS Word first and then into .R file.
To securely copy the code pls use Notepad (Notepad++ or IDE) so it preserves " symbol as is and does not transform it into “.

ContentLicense: CC BY-SA 4.0

Body:
1st One

Not run  there is an error

repeat{
sc=scan(nmax=1)
if (sc>9) {break} else{
b=switch(sc,"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE")
cat(“\n The Number Entered is “, sc ,” In Alpha it is  “, b,”\n”) } }

the Error is
Error: unexpected input in:
"b=switch(sc,"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE")
cat(“"

2nd One
This one runs ok

repeat{
sc=scan(nmax=1)
if (sc>9) {break} else{
b=switch(sc,"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE")
cat("\n The Entered Number is ", sc ," In Alpha it is ", b,"\n") } }

1: 4
Read 1 item
The Entered Number is  4  In Alpha it is  FOUR


问:
Why doesn't the total number of features from data.shape agree with those that are shown during recursive feature elimination?
Forgive me if I'm missing something obvious, I'm a relative newby to both Python and ML (and a new poster here, the trifecta of ignorance). Anyway, data.shape is telling me that me dataset is (150,177), however there are only 175 "False" or "True"  selected features, and also 175 feature rankings produced by this RFE code (see below). I understand that 1 of the 177 is my output, but the 176 input features still doesn't match up with 175 from the Selected Features or Feature Ranking output. What am I missing??

```<code>#load Discovery Metabolomics dataset
from numpy import set_printoptions
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from pandas import read_csv
#load data
filename="DiscoveryMetabolomics_data.csv"
data=read_csv(filename)
array=data.values
Y=array[:, 0]
X=array[:, 1:-1]
#feature selection
model=LogisticRegression(solver='liblinear')
rfe=RFE(model, 5)
fit=rfe.fit(X,Y)
#Summarize Scores
set_printoptions(precision=3)
print(data.shape)
print("Num Features: %d" %fit.n_features_)
print("Selected Features: %s" %fit.support_)
print("Feature Ranking %s" %fit.ranking_)
</code>```

(150, 177)
Num Features: 5

Selected Features:
[False False False False False False False False False False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False  True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False False False False False False]

Feature Ranking
[157 171  40 167 114 143  35 168   7 142  29 162 158 100  95  91 159 160 45  69 118 116  36 151 132 163   1  74  12 127  10  16  58 128 122  79 59   9   1  72 149  42   5  60 119  27  41 138  25 101 156   2  88  43 44  55   6  11 153  17 104   3 166 146  32 141  94 155 145  93  19 130 13  78 139  68   8 123  64 102  67  30  52   1 137  38  61  49 109 140 57  90  26 148 103  63 144 105  21  53 136  31  47  37  86  65 110  28 85 111  14  80 147  98 161  82  22  48  89  96  92 133  76 170  71  33 99  34 112  46 115  18  50 107 126 150 129  51  66  56   1  97  20  84 131  87  73  83 125  39 108  24  62 121  70  75 120 106   1 134  54 165 15 152 169 154  77 135  81 117 124   4  23 164 113]

答:
array = np.zeros((150, 177))

print(array.shape, array[:, 1:-1].shape)
# output (150, 177) (150, 175)
```
<p>Using <code>[1:-1]</code> takes all values starting with the first and up to (exluding)  the last (index -1). So, your input has 175 dimensions, and thus, your output too.</p>
<p>This is simply the way indexing works in Python. If you want all elements until the end, use <code>[1:]</code>:</p>
<pre class="lang-py prettyprint-override"><code>print([1, 2, 3][1:-1])
# output [2]

print([1, 2, 3][1:])
# output [2, 3]
</code>```

Body:
Forgive me if I'm missing something obvious, I'm a relative newby to both Python and ML (and a new poster here, the trifecta of ignorance). Anyway, data.shape is telling me that me dataset is (150,177), however there are only 175 "False" or "True"  selected features, and also 175 feature rankings produced by this RFE code (see below). I understand that 1 of the 177 is my output, but the 176 input features still doesn't match up with 175 from the Selected Features or Feature Ranking output. What am I missing??

#load Discovery Metabolomics dataset
from numpy import set_printoptions
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from pandas import read_csv
#load data
filename="DiscoveryMetabolomics_data.csv"
data=read_csv(filename)
array=data.values
Y=array[:, 0]
X=array[:, 1:-1]
#feature selection
model=LogisticRegression(solver='liblinear')
rfe=RFE(model, 5)
fit=rfe.fit(X,Y)
#Summarize Scores
set_printoptions(precision=3)
print(data.shape)
print("Num Features: %d" %fit.n_features_)
print("Selected Features: %s" %fit.support_)
print("Feature Ranking %s" %fit.ranking_)

(150, 177)
Num Features: 5

Selected Features:
[False False False False False False False False False False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False  True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False False False False False False False  True False False False False False False False False False False False False False False False False]

Feature Ranking
[157 171  40 167 114 143  35 168   7 142  29 162 158 100  95  91 159 160 45  69 118 116  36 151 132 163   1  74  12 127  10  16  58 128 122  79 59   9   1  72 149  42   5  60 119  27  41 138  25 101 156   2  88  43 44  55   6  11 153  17 104   3 166 146  32 141  94 155 145  93  19 130 13  78 139  68   8 123  64 102  67  30  52   1 137  38  61  49 109 140 57  90  26 148 103  63 144 105  21  53 136  31  47  37  86  65 110  28 85 111  14  80 147  98 161  82  22  48  89  96  92 133  76 170  71  33 99  34 112  46 115  18  50 107 126 150 129  51  66  56   1  97  20  84 131  87  73  83 125  39 108  24  62 121  70  75 120 106   1 134  54 165 15 152 169 154  77 135  81 117 124   4  23 164 113]

Body:
array = np.zeros((150, 177))

print(array.shape, array[:, 1:-1].shape)
# output (150, 177) (150, 175)

Using [1:-1] takes all values starting with the first and up to (exluding)  the last (index -1). So, your input has 175 dimensions, and thus, your output too.

This is simply the way indexing works in Python. If you want all elements until the end, use [1:]:

print([1, 2, 3][1:-1])
# output [2]

print([1, 2, 3][1:])
# output [2, 3]


问:
Generate two same random alpha-numeric strings in different java programs
I am looking to see if there is a possibility to generate two same alpha-numeric strings in two different java codes. This is for the purpose of secured communication between client and server.

Or is there an alternative way to do this?

I looked at the usual ways of public private key encryption and related stuff. For my requirement, I do not need such a mechanism as its kind of too much of standard stuff. I am kind of looking for a simple alternative like this.

Thanks,
Abishek

答:
If two different systems are generating the same string then the generator will usually not be cryptographically secure.  Once the attacker knows the inputs she will be able to generate the same string, and the inputs will be things like the current date/time as Alistair suggests.

This is not a new problem, and it has already been solved.  Peter has pointed you at Diffie-Hellman, which is the standard secure solution for establishing a shared secret (i.e. the key) over an insecure line.

ContentLicense: CC BY-SA 3.0


问:
How to get enum order?
If I have enum:

```<code>public enum ImportState : byte
{
     None = 0,
     ImportedWithChanges = 44,
     AwaitingApproval = 45,
     Removing = 66,
     Revalidating = 99,
};
</code>```

How to get enum order?
For example:

```<code>GetOrder(ImportState.None)
</code>```

Should return 1(first in order)

```<code>GetOrder(ImportState.AwaitingApproval )
</code>```

Should return  3 (third in order)

答:
What about this Solution?

```<code>var result = from r in Enum.GetValues<ImportState>()
         let expression =
         r == ImportState.Revalidating
            ? 0
            : r == ImportState.AwaitingApproval
                ? 1
                : r == ImportState.Removing
                    ? 2
                    : r == ImportState.ImportedWithChanges
                        ? 3
                        : 4
         orderby expression ascending
         select r.ToString();
Console.WriteLine(string.Join(", ", result));
</code>```

Output: Revalidating, AwaitingApproval, Removing, ImportedWithChanges, None

Title: How to get enum order?

Body:
If I have enum:

public enum ImportState : byte
{
     None = 0,
     ImportedWithChanges = 44,
     AwaitingApproval = 45,
     Removing = 66,
     Revalidating = 99,
};

How to get enum order?
For example:

GetOrder(ImportState.None)

Should return 1(first in order)

GetOrder(ImportState.AwaitingApproval )

Should return  3 (third in order)

Body:
What about this Solution?

var result = from r in Enum.GetValues<ImportState>()
         let expression =
         r == ImportState.Revalidating
            ? 0
            : r == ImportState.AwaitingApproval
                ? 1
                : r == ImportState.Removing
                    ? 2
                    : r == ImportState.ImportedWithChanges
                        ? 3
                        : 4
         orderby expression ascending
         select r.ToString();
Console.WriteLine(string.Join(", ", result));

Output: Revalidating, AwaitingApproval, Removing, ImportedWithChanges, None


问:
Extract text in quotes after specific preceding text string for whole column
I have a column of data and need to delete the text either side of the Company Name, leaving just the company name in that column.

The company name is always preceded with "Company","value":

Example cell data:

some text to delete,:"Company","value":"Company name to remain", some text to delete

Please help me with Excel VBA to accomplish this. I wouldn't know where to start with this one.

Thank you.

答:
Assuming that the JSON format is fixed and you only wanted just 1 value from it, below solution uses Regex:</p>
```<code>Option Explicit

Private Sub ExtractCompanyName()
    Const regexPattern As String = """value"":""([\s\S]{1,})"",""section"""

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets(1) 'Change to correct worksheet reference

    'Get last row in column B
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row

    'Get the value into an array for faster processing, process cell by cell is a very slow process in general and should be avoided where possible.
    Dim processRng As Range
    Set processRng = ws.Range("B1:B" & lastRow)

    Dim processArr As Variant
    processArr = processRng.Value

    'Create Regex and parse each value in the array to extract the company name
    Dim regex As Object
    Set regex = CreateObject("vbScript.Regexp")
    regex.Pattern = regexPattern

    Dim i As Long
    For i = 1 To UBound(processArr, 1)
        If regex.Test(processArr(i, 1)) Then
            processArr(i, 1) = regex.Execute(processArr(i, 1))(0).SubMatches(0)
        End If
    Next i
    Set regex = Nothing

    'Write the array back into worksheet
    processRng = processArr

    Set processRng = Nothing
    Set ws = Nothing
End Sub
</code>```

Body:
Assuming that the JSON format is fixed and you only wanted just 1 value from it, below solution uses Regex:

Option Explicit

Private Sub ExtractCompanyName()
    Const regexPattern As String = """value"":""([\s\S]{1,})"",""section"""

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets(1) 'Change to correct worksheet reference

    'Get last row in column B
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row

    'Get the value into an array for faster processing, process cell by cell is a very slow process in general and should be avoided where possible.
    Dim processRng As Range
    Set processRng = ws.Range("B1:B" & lastRow)

    Dim processArr As Variant
    processArr = processRng.Value

    'Create Regex and parse each value in the array to extract the company name
    Dim regex As Object
    Set regex = CreateObject("vbScript.Regexp")
    regex.Pattern = regexPattern

    Dim i As Long
    For i = 1 To UBound(processArr, 1)
        If regex.Test(processArr(i, 1)) Then
            processArr(i, 1) = regex.Execute(processArr(i, 1))(0).SubMatches(0)
        End If
    Next i
    Set regex = Nothing

    'Write the array back into worksheet
    processRng = processArr

    Set processRng = Nothing
    Set ws = Nothing
End Sub


问:
Static Comparison of Record Layouts
I have two records, some fields of which need to be in the same positions within each record. Although this has been heavily commented in the code, it is possible that, in 10 years time, a programmer may change one of the records without changing the other and I would like to create a static check that this has not occurred.

I can create an "active" check in a procedure or function as follows:

```<code>
procedure Main is

    type SimpleRecord1 is record
        FirstItem  : Integer;
        SecondItem : Boolean;
        ThirdItem  : Integer;
        DoNotCare  : Float;
    end record;

    type SimpleRecord2 is record
        Foo        : Integer;
        Bar        : Boolean;
        Baz        : Integer;
        Rfc3092    : Boolean;
    end record;

    MyRecord1 : SimpleRecord1;
    MyRecord2 : SimpleRecord2;
begin
    Pragma Assert ((MyRecord1.FirstItem'Position = MyRecord2.Foo'Position) and
                   (MyRecord1.SecondItem'Position = MyRecord2.Bar'Position) and
                   (MyRecord1.ThirdItem'Position = MyRecord2.Baz'Position));

    Put_Line ("The assert didn't fire");

end Main;
</code>```

I am concerned that the first three vairiables have the same offsets within the two records. In the real code there are dozens of other variables within each record which are not the same between the records.

However, I would really like this to be a check, not on instances of the records (MyRecord1, MyRecord2), but on the records themselves (SimpleRecord1, SimpleRecord2). Then it could be placed in the .ads file where the records are defined.

SimpleRecord1.FirstItem'Position

is illegal. Is there a way to create a check without having to make instances and put the code into a function or procedure?

答:
To make the last two comments (by Jere and Jim Rogers) more concrete, indeed the Ada way is to define the types of the list elements so that any kind of element can be placed in the same list, and accessed by the same kind of pointer, without any uncheckable conversions. In the OP's case, IMO the most appropriate method is to make all list elements be tagged records derived from the same abstract parent class where the parent contains the next, prev and priority components. For example like this:

```<code>type List_Element;
type List_Ptr is access List_Element'Class;
type List_Element is abstract tagged record
   Next, Prev : List_Ptr;
   Priority   : Boolean;
end record;

type Simple_Record_1 is new List_Element with record
   DoNotCare : Float;
end record;

type Simple_Record_2 is new List_Element with record
   Rfc3092 : Boolean;
end record;
</code>```

The SW that handles the linked list deals with List_Ptr values that point to List_Element'Class objects but with only the common components Next, Prev and Priority visible. When there is a need to execute some processing that depends on the actual type of the list element, you can use either a dynamically dispatching call, or a membership test followed by a type conversion, to get from a List_Ptr to the underlying Simple_Record_1, for example.

Title: Static Comparison of Record Layouts

Body:
I have two records, some fields of which need to be in the same positions within each record. Although this has been heavily commented in the code, it is possible that, in 10 years time, a programmer may change one of the records without changing the other and I would like to create a static check that this has not occurred.

I can create an "active" check in a procedure or function as follows:

procedure Main is

    type SimpleRecord1 is record
        FirstItem  : Integer;
        SecondItem : Boolean;
        ThirdItem  : Integer;
        DoNotCare  : Float;
    end record;

    type SimpleRecord2 is record
        Foo        : Integer;
        Bar        : Boolean;
        Baz        : Integer;
        Rfc3092    : Boolean;
    end record;

    MyRecord1 : SimpleRecord1;
    MyRecord2 : SimpleRecord2;
begin
    Pragma Assert ((MyRecord1.FirstItem'Position = MyRecord2.Foo'Position) and
                   (MyRecord1.SecondItem'Position = MyRecord2.Bar'Position) and
                   (MyRecord1.ThirdItem'Position = MyRecord2.Baz'Position));

    Put_Line ("The assert didn't fire");

end Main;

I am concerned that the first three vairiables have the same offsets within the two records. In the real code there are dozens of other variables within each record which are not the same between the records.

However, I would really like this to be a check, not on instances of the records (MyRecord1, MyRecord2), but on the records themselves (SimpleRecord1, SimpleRecord2). Then it could be placed in the .ads file where the records are defined.

SimpleRecord1.FirstItem'Position

is illegal. Is there a way to create a check without having to make instances and put the code into a function or procedure?

Body:
To make the last two comments (by Jere and Jim Rogers) more concrete, indeed the Ada way is to define the types of the list elements so that any kind of element can be placed in the same list, and accessed by the same kind of pointer, without any uncheckable conversions. In the OP's case, IMO the most appropriate method is to make all list elements be tagged records derived from the same abstract parent class where the parent contains the next, prev and priority components. For example like this:

type List_Element;
type List_Ptr is access List_Element'Class;
type List_Element is abstract tagged record
   Next, Prev : List_Ptr;
   Priority   : Boolean;
end record;

type Simple_Record_1 is new List_Element with record
   DoNotCare : Float;
end record;

type Simple_Record_2 is new List_Element with record
   Rfc3092 : Boolean;
end record;

The SW that handles the linked list deals with List_Ptr values that point to List_Element'Class objects but with only the common components Next, Prev and Priority visible. When there is a need to execute some processing that depends on the actual type of the list element, you can use either a dynamically dispatching call, or a membership test followed by a type conversion, to get from a List_Ptr to the underlying Simple_Record_1, for example.


问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答:
You never initialise the base nenber variable - your base constructor should be:

```<code>Base(char * aname) : name( aname )
  {
    cout << name << ": Base class cons" << endl;
  }
</code>```

As  well as that, when you say

```<code>Base b = Child( "xxx" );
</code>```

then the Child instance will be sliced down to a Base, which is probably not what you want.

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

Body:
You never initialise the base nenber variable - your base constructor should be:

Base(char * aname) : name( aname )
  {
    cout << name << ": Base class cons" << endl;
  }

As  well as that, when you say

Base b = Child( "xxx" );

then the Child instance will be sliced down to a Base, which is probably not what you want.

OwnerDisplayName: anon


问:
remove query string from url using htaccess
Can anyone help me to remove query string from URL using .htaccess

Current URL

```<code>xyz.com/blog-detail?slug=slugvalue
</code>```

I want this type of url

```<code>xyz.com/blog-detail/slugvalue
</code>```

Basically I want slug value in URL and remove parameter from URL

Here is my code:

```<code><ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</code>```

```<code><ifmodule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</ifmodule>

# BEGIN Expire headers
 <IfModule mod_expires.c>
 #  # Turn on the module.
  ExpiresActive on
  # Set the default expiry times.
  ExpiresDefault "access plus 2 days"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/svg+xml "access 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"
  ExpiresByType image/ico "access plus 1 month"
  ExpiresByType image/x-icon "access plus 1 month"
  ExpiresByType text/html "access plus 600 seconds"
</IfModule>
</code>```

here is my all htaccess file code

```<code># check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]
RewriteRule ^(.*)index\.(php|html?)$ /$1 [R=301,NC,L]
</code>```

please check all above code of my file

please help me to solve my issue

答:
With your shown samples, attempts please try following htaccess rules.
Please make sure to place these rules at the top of your htaccess file.

Also make sure to clear your browser cache before testing your URLs.

```<code>RewriteEngine ON
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ %1/%2? [R=301,L]

##Internal rewrite to php file for frontend request:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]
</code>```

JS/CS rewrite/redirect:
You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.

Body:
Can anyone help me to remove query string from URL using .htaccess

Current URL

xyz.com/blog-detail?slug=slugvalue

I want this type of url

xyz.com/blog-detail/slugvalue

Basically I want slug value in URL and remove parameter from URL

Here is my code:

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

<ifmodule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</ifmodule>

# BEGIN Expire headers
 <IfModule mod_expires.c>
 #  # Turn on the module.
  ExpiresActive on
  # Set the default expiry times.
  ExpiresDefault "access plus 2 days"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/svg+xml "access 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"
  ExpiresByType image/ico "access plus 1 month"
  ExpiresByType image/x-icon "access plus 1 month"
  ExpiresByType text/html "access plus 600 seconds"
</IfModule>

here is my all htaccess file code

# check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]
RewriteRule ^(.*)index\.(php|html?)$ /$1 [R=301,NC,L]

please check all above code of my file

please help me to solve my issue

Body:
With your shown samples, attempts please try following htaccess rules.
Please make sure to place these rules at the top of your htaccess file.

Also make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ %1/%2? [R=301,L]

##Internal rewrite to php file for frontend request:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]

JS/CS rewrite/redirect:
You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.


问:
How does std::find works with std::set
To find an element from a std::set, ofc, we should use std::set::find. However, the function std::find/std::find would work too.

```<code>std::set<int> st;
for (int i = 0; i < 999999; i++) {
    st.insert(i);
}

// method 1
if (st.find(999990) != st.end()) {
    std::cout << "111" << std::endl;
}

// method 2
auto itor = std::find(std::begin(st), std::end(st), 999990);
if (itor != std::end(st)) {
  std::cout << "aaa" << std::endl;
}

// method 3
auto itor2 = std::find(st.begin(), st.end(), 999990);
if (itor2 != st.end()) {
  std::cout << "bbb" << std::endl;
}
</code>```

As you see, all of the the three methods work as exptected (https://godbolt.org/z/fEjzTae81).

But I don't know their difference, especially their complexity.

I just did a simple benchmark here: https://quick-bench.com/q/TjtOBZIWRw0oLg9_TywAlv45kmo

But I don't know why they have totally different complexity.

I know why std::set::find is fast. But I don't know why the two others are slow.

Does std::find totally ignore the order of std::set so that a std::set will be regarded as an sequence container like a std::vector? Or can I say that std::find doesn't know the fact that all of elements have been ordered so it does the search one by one (linear complexity)?

Why is st.begin() faster than std::begin(st)?

答:
The reason for the time complexity difference is that std::find operates with iterators, and it, indeed, does treat std::set as a sequence container, while std::set::find uses container properties.

As for why st.begin() is faster than std::begin(st), they are actually identical. The reason why second is faster is that both of your functions are doing the same thing, and as benchmarks are run consecutively, the execution of the second function is faster because probably cache misses are lower and similar things. I changed the order of these two functions and got exactly opposite result with std::begin(st) being faster. See this modified benchmark here: https://quick-bench.com/q/iM6e3iT1XbqnW_s-v_kyrs6kqrQ

Title: How does std::find works with std::set

Body:
To find an element from a std::set, ofc, we should use std::set::find. However, the function std::find/std::find would work too.

std::set<int> st;
for (int i = 0; i < 999999; i++) {
    st.insert(i);
}

// method 1
if (st.find(999990) != st.end()) {
    std::cout << "111" << std::endl;
}

// method 2
auto itor = std::find(std::begin(st), std::end(st), 999990);
if (itor != std::end(st)) {
  std::cout << "aaa" << std::endl;
}

// method 3
auto itor2 = std::find(st.begin(), st.end(), 999990);
if (itor2 != st.end()) {
  std::cout << "bbb" << std::endl;
}

As you see, all of the the three methods work as exptected (https://godbolt.org/z/fEjzTae81).

But I don't know their difference, especially their complexity.

I just did a simple benchmark here: https://quick-bench.com/q/TjtOBZIWRw0oLg9_TywAlv45kmo

But I don't know why they have totally different complexity.

I know why std::set::find is fast. But I don't know why the two others are slow.

Does std::find totally ignore the order of std::set so that a std::set will be regarded as an sequence container like a std::vector? Or can I say that std::find doesn't know the fact that all of elements have been ordered so it does the search one by one (linear complexity)?

Why is st.begin() faster than std::begin(st)?


问:
Unable to find current origin/master revision in submodule path
In my project (which uses git), I need to use a library, which is still in progress. I decided to create a submodule for that library, because I want to update from time to time its latest version (I don't plan to make my own change there).

I did:

```<code>git submodule add https://github.com/mb21/JSONedit.git
git commit -am 'added JSNedit submodule'
git push -u origin master
git pull origin master
</code>```

Then, I did see the JSONedit folder in my local folder, and a link in my git folder online. But when I did git submodule update --remote JSONedit/, I got the following errors:

```<code>fatal: Needed a single revision
Unable to find current origin/master revision in submodule path 'JSONedit'
</code>```

Does anyone know what's wrong here?

答:
In my case, the problem was that Git submodule assumed there would be a branch origin/master. Instead, the submodule repository only had a branch main.

I added branch=main to the submodule definition in .gitmodules. After running git submodule sync, git submodule update --remote now works fine.

Body:
In my project (which uses git), I need to use a library, which is still in progress. I decided to create a submodule for that library, because I want to update from time to time its latest version (I don't plan to make my own change there).

I did:

git submodule add https://github.com/mb21/JSONedit.git
git commit -am 'added JSNedit submodule'
git push -u origin master
git pull origin master

Then, I did see the JSONedit folder in my local folder, and a link in my git folder online. But when I did git submodule update --remote JSONedit/, I got the following errors:

fatal: Needed a single revision
Unable to find current origin/master revision in submodule path 'JSONedit'

Does anyone know what's wrong here?


问:
WSL 2 is not installed error when opening docker desktop
Whenever I try to open docker desktop on windows 10, I get this.
https://i.stack.imgur.com/AlUCn.png

But I never opted for WSL installation while installing docker desktop.
I tried uninstalling it, restarting my PC and removing the local APPDATA manually, but still I'm getting this error.

答: Try to open powershell and use wsl --install. After that restart your computer and try to open docker again.


问:
How to get the header row thats is (A or B or C) by passing the column name
I'm using exceljs library and I have Workbook with two sheets (masterdata  and sheetB)
In master_data sheet first column status is having values [1 2 3 4 5] and I want to create dropdown in sheetB using masterdata's status column values. Is there a way read column names header value (A) ? In this case the master_dat sheet status column header value that is A. so that I pass that A below in formulae field.

```<code>worksheet.getCell('A1').dataValidation = {
  type: 'list',
  allowBlank: true,
  formulae: ['$A$1:$A$5']
};
</code>```

答:
you need to include the worksheet name:</p>
```<code>worksheet.getCell('A1').dataValidation = {
    type: 'list',
    allowBlank: true,
    formulae: ['masterdata!$A$1:$A$5']
};
</code>```

Body:
I'm using exceljs library and I have Workbook with two sheets (masterdata  and sheetB)
In master_data sheet first column status is having values [1 2 3 4 5] and I want to create dropdown in sheetB using masterdata's status column values. Is there a way read column names header value (A) ? In this case the master_dat sheet status column header value that is A. so that I pass that A below in formulae field.

worksheet.getCell('A1').dataValidation = {
  type: 'list',
  allowBlank: true,
  formulae: ['$A$1:$A$5']
};

Body:
you need to include the worksheet name:

worksheet.getCell('A1').dataValidation = {
    type: 'list',
    allowBlank: true,
    formulae: ['masterdata!$A$1:$A$5']
};


问:
How to use zlib in kernel extension projects for mac os x?
I want to develop a network kernel extension on mac os. I got some data with gzip format in function sf_data_in(). I included the header file named <libkern/zlib.h>, and my mac crashed when it was running the code below after I loading the kext with "kextload".

```<code>z_stream strm;
bzero(&strm, sizeof(z_stream));

if (Z_OK != inflateInit2(&strm))
{
    printf("inflateInit error.\n");

    inflateEnd(&strm);

    return 0;
}
</code>```

who can tell me how to use it in kernel programming. it's much better to give some samples.
Thanks very much.

答:
You are passing the wrong number of parameters to inflateInit2(), it requires both a pointer  to a stream and the window size in bits. if you do not wish to set the latter, use inflateInit() instead.

You may also want to look at some of the kernel code using zlib, ppp_deflate.c, ipcomp_core.c

Body:
I want to develop a network kernel extension on mac os. I got some data with gzip format in function sf_data_in(). I included the header file named <libkern/zlib.h>, and my mac crashed when it was running the code below after I loading the kext with "kextload".

z_stream strm;
bzero(&strm, sizeof(z_stream));

if (Z_OK != inflateInit2(&strm))
{
    printf("inflateInit error.\n");

    inflateEnd(&strm);

    return 0;
}

who can tell me how to use it in kernel programming. it's much better to give some samples.
Thanks very much.


问:
Google Ads API, conversion action. REMOVE, HIDDEN status cannot be set
We started to use Google Ads API V9 instead of Google Adwords API. In Google Adwords API there was status DISABLED for the conversion tracker. Now there is HIDDEN and REMOVED for conversion action. When we try to set HIDDEN or REMOVED there is an error message:

REMOVED-"Enum value 'REMOVED' cannot be used."

HIDDEN-"The field's value is on a deny-list for this field."

Any ideas?

答: Right api to use: ConversionActionOperation::setRemove</p>


问:
Why ord gives big endianness result while my platform is little endianness?
I have been learning how utf16 endianness are represented in C and Python. And from How is unicode represented internally in Python? :

u2049 is then represented as either \x49\x20 or \x20\x49 or \x49\x20\x00\x00 or \x00\x00\x20\x49 depending on the native byte order of your system and if UCS2 or UCS4 was picked.

```<code>ord('⁉') # gives 8265 in decimal
</code>```

Check on https://unicode-table.com/en/2049/ :

8265 is utf16 be in decimall, I expect it to be 18720 in decimal, which is utf16 le .

答:
There is a confusion between the byte representation of number, the byte representation of an unicode character and the value of the unicode code point. The value is a plain integer and does not depend on endiannes. 8265 or 0x2049 is the code point of the unicode character U+2049 EXCLAMATION QUESTION MARK (⁉). Full stop.

That character itself is represented as the byte string b'\x20\x49' in UTF-16BE encoding and b'\x49\x20' in UTF-16LE encoding.

Its internal byte representation is indeed

\x49\x20 or \x20\x49 or \x49\x20\x00\x00 or \x00\x00\x20\x49 depending on the native byte order of your system and if UCS2 or UCS4 was picked.

But you really should not care about it. You have no way to access it from Python language, so it only matters if you write a C module and do not want to use the Unicode library functions. Said differently, unless you want to build a Python interpretor in C language, the internal representation of a unicode character should be seen as an implementation detail.

Body:
I have been learning how utf16 endianness are represented in C and Python. And from How is unicode represented internally in Python? :

u2049 is then represented as either \x49\x20 or \x20\x49 or \x49\x20\x00\x00 or \x00\x00\x20\x49 depending on the native byte order of your system and if UCS2 or UCS4 was picked.

ord('⁉') # gives 8265 in decimal

Check on https://unicode-table.com/en/2049/ :

8265 is utf16 be in decimall, I expect it to be 18720 in decimal, which is utf16 le .


问:
SVG pie chart (donut) slice selection via javascript, html, css
I have my css hover working correctly and I can hard code the css class and get the html to use .active but I cannot get my pie slices to switch to active state upon click.  Additionally, after I get this working, I want to be able to select multiple pie slices and capture the id's.  I'm not that great with javascript so... be gentle with me :)
page header

```<code><!DOCTYPE html>
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/css/style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>

<style>

</style>
<script language="javascript" type="text/javascript">

/* this is for selecting and deselecting svg pie pieces
$('group_path').click(function() {
  $(this).addClass('active').siblings().removeClass('active');
}); */

/* This is the javascript to select pie pieces */
// Get the container element
var group_pathContainer = document.getElementById("4");
var group_paths = group_pathContainer.querySelectorAll(".group_path");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < group_paths.length; i++) {
  group_paths[i].addEventListener("click", function(e) {
    var current = e.currentTarget;
    // toggle active class to the current/clicked button
    current.classList.toggle('active');
    getActive();
  });
}

// list all active pie segemnts
function getActive(){
  let actives = document.querySelectorAll('.active');
  let idArray = [];
  actives.forEach(function(el,i){
    let id = el.id;
    idArray.push(id)
  })
  console.log(idArray)
}

</script>
</code>```

svg

```<code> <svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)';>
                <g id="4" >
                      <g id="4.01" class="active" fill='rgb(84,161,229)' >
                      <path stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
                      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
                      </g>
                       <g id="4.02" class="active" fill='rgb(242,162,84)'>
                      <path  stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
                      </g>
                       <g id="4.03" class="group_path" fill='rgb(237,110,133)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
                    </g>
                       <g id="4.04" class="group_path" fill='rgb(173,205,225)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
                    </g>
                       <g id="4.05" class="group_path" fill='rgb(187,221,147)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.915241 0.402907 A 1 1 0 0 1 -0.946085 0.323917 L 0 0 '></path>
                    </g>
                       <g id="4.06" class="group_path" fill='rgb(238,158,155)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.946085 0.323917 A 1 1 0 0 1 -0.978581 -0.205863 L 0 0 '></path>
                    </g>
                       <g id="4.07" class="group_path active" fill='rgb(84,161,229)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.978581 -0.205863 A 1 1 0 0 1 -0.879316 -0.476238 L 0 0 '></path>
                    </g>
                       <g id="4.08" class="group_path" fill='rgb(108,190,191)'>
                   <path stroke='white' stroke-width='.0125px' d='M -0.879316 -0.476238 A 1 1 0 0 1 -0.527846 -0.849340 L 0 0 '></path>
                   </g>
                       <g id="4.09" class="group_path" fill='rgb(242,162,84)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.527846 -0.849340 A 1 1 0 0 1 0.056518 -0.998402 L 0 0 '></path>
                    </g>
                       <g id="4.10" class="group_path" fill='rgb(237,110,133)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.056518 -0.998402 A 1 1 0 0 1 0.543760 -0.839241 L 0 0 '></path>
                    </g>
                       <g id="4.11" class="group_path" fill='rgb(173,205,225)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.543760 -0.839241 A 1 1 0 0 1 0.711535 -0.702650 L 0 0 '></path>
                    </g>
                       <g id="4.12" class="group_path" fill='rgb(187,221,147)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.711535 -0.702650 A 1 1 0 0 1 0.724653 -0.689114 L 0 0 '></path>
                    </g>
                       <g id="4.13" class="group_path" fill='rgb(42,228,229)'>
                    <path stroke='white' stroke-width='.00625px' d='M 0.724653 -0.689114 A 1 1 0 0 1 1.000000 -0.000000 L 0 0 '></path>
                    </g>
                    <circle fill='#fff' cx='0' cy='0' r='0.80'/>
                </g>
</code>```

css

```<code>.group_path:hover{
 /* fill: purple; */
  transform: scale(.95, .95);
}
.group_path.active {
  fill: purple;
  transform: scale(.92, .92);
}
</code>```

答:
Your active class doesn't have any effect since your path's fill attribute has a higher specificity.

change you css like so:

```<code>.active path{
  fill: purple;
  transform: scale(.92, .92);
}
</code>```

To set a pi segment active or non-active you could use a classList.toggle() approach:

/* This is the javascript to select pie pieces */
// Get the container element
var group_pathContainer = document.getElementById("4");
var group_paths = group_pathContainer.querySelectorAll(".group_path");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < group_paths.length; i++) {
  group_paths[i].addEventListener("click", function(e) {
    var current = e.currentTarget;
    // toggle active class to the current/clicked button
    current.classList.toggle('active');
    getActive();
  });
}

// list all active pie segemnts
function getActive(){
  let actives = document.querySelectorAll('.active');
  let idArray = [];
  actives.forEach(function(el,i){
    let id = el.id;
    idArray.push(id)
  })
  console.log(idArray)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg{
  display:inline-block;
  width:20em;
  border: 1px solid #ccc
}

.active path{
  fill: purple;
  transform: scale(.92, .92);
}</code>```

<svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)' >
  <g id="4">
    <g id="4.01" class="group_path">
      <path fill='rgb(84,161,229)' stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
    </g>
    <g id="4.02" class="group_path">
      <path fill='rgb(242,162,84)' stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
    </g>
    <g id="4.03" class="group_path">
      <path fill='rgb(237,110,133)' stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
    </g>
    <g id="4.04" class="group_path">
      <path fill='rgb(173,205,225)' stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
    </g>
</svg>```
</div>
</div>
</p>
<h2>Example 2: fill defined by group</h2>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* This is the javascript to select pie pieces */
// Get the container element
var group_pathContainer = document.getElementById("4");
var group_paths = group_pathContainer.querySelectorAll(".group_path");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < group_paths.length; i++) {
  group_paths[i].addEventListener("click", function(e) {
    var current = e.currentTarget;
    // toggle active class to the current/clicked button
    current.classList.toggle('active');
    getActive();
  });
}

// list all active pie segemnts
function getActive(){
  let actives = document.querySelectorAll('.active');
  let idArray = [];
  actives.forEach(function(el,i){
    let id = el.id;
    idArray.push(id)
  })
  console.log(idArray)
}</code>```

svg{
  display:inline-block;
  width:20em;
  border: 1px solid #ccc
}

.group_path.active {
  fill: purple;
  transform: scale(.92, .92);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)' >
  <g id="4">
    <g id="4.01" class="group_path" fill='rgb(84,161,229)'>
      <path stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
    </g>
    <g id="4.02" class="group_path" fill='rgb(242,162,84)'>
      <path  stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
    </g>
    <g id="4.03" class="group_path" fill='rgb(237,110,133)'>
      <path  stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
    </g>
    <g id="4.04" class="group_path" fill='rgb(173,205,225)'>
      <path  stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
    </g>
</svg></code>```

Body:
I have my css hover working correctly and I can hard code the css class and get the html to use .active but I cannot get my pie slices to switch to active state upon click.  Additionally, after I get this working, I want to be able to select multiple pie slices and capture the id's.  I'm not that great with javascript so... be gentle with me :)
page header

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/css/style.css" rel="stylesheet" type="text/css" />

svg

 <svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)';>
                <g id="4" >
                      <g id="4.01" class="active" fill='rgb(84,161,229)' >
                      <path stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
                      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
                      </g>
                       <g id="4.02" class="active" fill='rgb(242,162,84)'>
                      <path  stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
                      </g>
                       <g id="4.03" class="group_path" fill='rgb(237,110,133)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
                    </g>
                       <g id="4.04" class="group_path" fill='rgb(173,205,225)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
                    </g>
                       <g id="4.05" class="group_path" fill='rgb(187,221,147)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.915241 0.402907 A 1 1 0 0 1 -0.946085 0.323917 L 0 0 '></path>
                    </g>
                       <g id="4.06" class="group_path" fill='rgb(238,158,155)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.946085 0.323917 A 1 1 0 0 1 -0.978581 -0.205863 L 0 0 '></path>
                    </g>
                       <g id="4.07" class="group_path active" fill='rgb(84,161,229)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.978581 -0.205863 A 1 1 0 0 1 -0.879316 -0.476238 L 0 0 '></path>
                    </g>
                       <g id="4.08" class="group_path" fill='rgb(108,190,191)'>
                   <path stroke='white' stroke-width='.0125px' d='M -0.879316 -0.476238 A 1 1 0 0 1 -0.527846 -0.849340 L 0 0 '></path>
                   </g>
                       <g id="4.09" class="group_path" fill='rgb(242,162,84)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.527846 -0.849340 A 1 1 0 0 1 0.056518 -0.998402 L 0 0 '></path>
                    </g>
                       <g id="4.10" class="group_path" fill='rgb(237,110,133)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.056518 -0.998402 A 1 1 0 0 1 0.543760 -0.839241 L 0 0 '></path>
                    </g>
                       <g id="4.11" class="group_path" fill='rgb(173,205,225)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.543760 -0.839241 A 1 1 0 0 1 0.711535 -0.702650 L 0 0 '></path>
                    </g>
                       <g id="4.12" class="group_path" fill='rgb(187,221,147)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.711535 -0.702650 A 1 1 0 0 1 0.724653 -0.689114 L 0 0 '></path>
                    </g>
                       <g id="4.13" class="group_path" fill='rgb(42,228,229)'>
                    <path stroke='white' stroke-width='.00625px' d='M 0.724653 -0.689114 A 1 1 0 0 1 1.000000 -0.000000 L 0 0 '></path>
                    </g>
                    <circle fill='#fff' cx='0' cy='0' r='0.80'/>
                </g>

css

.group_path:hover{
 /* fill: purple; */
  transform: scale(.95, .95);
}
.group_path.active {
  fill: purple;
  transform: scale(.92, .92);
}

Body:
Your active class doesn't have any effect since your path's fill attribute has a higher specificity.

change you css like so:

.active path{
  fill: purple;
  transform: scale(.92, .92);
}

To set a pi segment active or non-active you could use a classList.toggle() approach:

/* This is the javascript to select pie pieces */
// Get the container element
var group_pathContainer = document.getElementById("4");
var group_paths = group_pathContainer.querySelectorAll(".group_path");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < group_paths.length; i++) {
  group_paths[i].addEventListener("click", function(e) {
    var current = e.currentTarget;
    // toggle active class to the current/clicked button
    current.classList.toggle('active');
    getActive();
  });
}

// list all active pie segemnts
function getActive(){
  let actives = document.querySelectorAll('.active');
  let idArray = [];
  actives.forEach(function(el,i){
    let id = el.id;
    idArray.push(id)
  })
  console.log(idArray)
}

svg{
  display:inline-block;
  width:20em;
  border: 1px solid #ccc
}

.active path{
  fill: purple;
  transform: scale(.92, .92);
}

<svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)' >
  <g id="4">
    <g id="4.01" class="group_path">
      <path fill='rgb(84,161,229)' stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
    </g>
    <g id="4.02" class="group_path">
      <path fill='rgb(242,162,84)' stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
    </g>
    <g id="4.03" class="group_path">
      <path fill='rgb(237,110,133)' stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
    </g>
    <g id="4.04" class="group_path">
      <path fill='rgb(173,205,225)' stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
    </g>
</svg>

Example 2: fill defined by group

/* This is the javascript to select pie pieces */
// Get the container element
var group_pathContainer = document.getElementById("4");
var group_paths = group_pathContainer.querySelectorAll(".group_path");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < group_paths.length; i++) {
  group_paths[i].addEventListener("click", function(e) {
    var current = e.currentTarget;
    // toggle active class to the current/clicked button
    current.classList.toggle('active');
    getActive();
  });
}

// list all active pie segemnts
function getActive(){
  let actives = document.querySelectorAll('.active');
  let idArray = [];
  actives.forEach(function(el,i){
    let id = el.id;
    idArray.push(id)
  })
  console.log(idArray)
}

svg{
  display:inline-block;
  width:20em;
  border: 1px solid #ccc
}

.group_path.active {
  fill: purple;
  transform: scale(.92, .92);
}

<svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)' >
  <g id="4">
    <g id="4.01" class="group_path" fill='rgb(84,161,229)'>
      <path stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
    </g>
    <g id="4.02" class="group_path" fill='rgb(242,162,84)'>
      <path  stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
    </g>
    <g id="4.03" class="group_path" fill='rgb(237,110,133)'>
      <path  stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
    </g>
    <g id="4.04" class="group_path" fill='rgb(173,205,225)'>
      <path  stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
    </g>
</svg>


问:
React Router Url displays blank page after running npm serve
I have an issue with running npm serve for a static react SPA. I believe it has to do with the react-router-dom from react-router.

Below is the package json

```<code> {
  "name": "eureka-customer-ui",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.7.1",
    "@webstudio/buttons": "^5.3.2",
    "@webstudio/checkbox": "^2.1.6",
    "@webstudio/icons": "^5.0.4",
    "@webstudio/inputs": "^4.11.0",
    "@webstudio/theme-dbs": "^2.0.1",
    "@webstudio/tooltip": "^2.3.1",
    "@webstudio/typography": "^1.0.3",
    "axios": "^0.24.0",
    "formik": "^2.2.9",
    "html-react-parser": "^1.4.5",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-helmet": "^6.1.0",
    "react-redux": "^7.2.6",
    "react-router-dom": "^6.2.1",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.3",
    "web-vitals": "^2.1.3",
    "yup": "^0.32.11"
  },
  "scripts": {
    "clean": "rm -rf build && rm -rf node_modules",
    "lint": "eslint './src/**/*.{js,ts,tsx}' --max-warnings 5",
    "start": "react-scripts start ",
    "build:clean": "rm -rf build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "setup": "npm ci",
    "preinstall": "npx npm-force-resolutions",
    "package": "cd build && zip -r ../$BUILD_ENV.zip *",
    "copy:static": "cp Staticfile build",
    "serve": "npx serve -s build -l 5000"
  },
  "eslintConfig": {
    "extends": [
      "react-app"
    ],
    "rules": {
      "import/no-anonymous-default-export": "off"
    }
  },
  "eslintIgnore": [
    "src/components/DBSDefault/*.tsx"
  ],
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^13.1.5",
    "@types/jest": "^24.9.1",
    "@types/node": "^16.11.19",
    "@types/react": "^16.9.53",
    "@types/react-dom": "^16.9.9",
    "@types/react-helmet": "^6.1.5",
    "@types/styled-components": "^5.1.19",
    "@types/uuid": "^8.3.4",
    "@typescript-eslint/eslint-plugin": "^4.17.0",
    "@typescript-eslint/parser": "^4.17.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-cypress": "^2.11.2",
    "eslint-plugin-jest": "^24.2.1",
    "eslint-plugin-prettier": "^3.3.1",
    "local-web-server": "^5.1.1",
    "serve": "^13.0.2",
    "typescript": "^4.4.4",
    "ws": "^8.5.0"
  }
}

</code>```

After running npm run build and npm run serve, i am unable to hit a PATH defined in my routes such as localhost:5000/personal/cards/subscription/signup. I get a blank page instead.

Below is a snippet of my routes components

```<code>import ConfirmationPage from "pages/ConfirmationPage";
import SignUpForm from "pages/SignUpForm";
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";

export default () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/personal/cards/subscription/signup"
          element={<SignUpForm />}
        />
        <Route
          path="/personal/cards/subscription/confirm"
          element={<ConfirmationPage />}
        />
      </Routes>
    </BrowserRouter>
  );
};
</code>```

Any ideas? Thank you!

答: Solved it by replace BrowserRouter with HashRouter.</p>

Body:
I have an issue with running npm serve for a static react SPA. I believe it has to do with the react-router-dom from react-router.

Below is the package json

 {
  "name": "eureka-customer-ui",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.7.1",
    "@webstudio/buttons": "^5.3.2",
    "@webstudio/checkbox": "^2.1.6",
    "@webstudio/icons": "^5.0.4",
    "@webstudio/inputs": "^4.11.0",
    "@webstudio/theme-dbs": "^2.0.1",
    "@webstudio/tooltip": "^2.3.1",
    "@webstudio/typography": "^1.0.3",
    "axios": "^0.24.0",
    "formik": "^2.2.9",
    "html-react-parser": "^1.4.5",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-helmet": "^6.1.0",
    "react-redux": "^7.2.6",
    "react-router-dom": "^6.2.1",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.3",
    "web-vitals": "^2.1.3",
    "yup": "^0.32.11"
  },
  "scripts": {
    "clean": "rm -rf build && rm -rf node_modules",
    "lint": "eslint './src/**/*.{js,ts,tsx}' --max-warnings 5",
    "start": "react-scripts start ",
    "build:clean": "rm -rf build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "setup": "npm ci",
    "preinstall": "npx npm-force-resolutions",
    "package": "cd build && zip -r ../$BUILD_ENV.zip *",
    "copy:static": "cp Staticfile build",
    "serve": "npx serve -s build -l 5000"
  },
  "eslintConfig": {
    "extends": [
      "react-app"
    ],
    "rules": {
      "import/no-anonymous-default-export": "off"
    }
  },
  "eslintIgnore": [
    "src/components/DBSDefault/*.tsx"
  ],
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^13.1.5",
    "@types/jest": "^24.9.1",
    "@types/node": "^16.11.19",
    "@types/react": "^16.9.53",
    "@types/react-dom": "^16.9.9",
    "@types/react-helmet": "^6.1.5",
    "@types/styled-components": "^5.1.19",
    "@types/uuid": "^8.3.4",
    "@typescript-eslint/eslint-plugin": "^4.17.0",
    "@typescript-eslint/parser": "^4.17.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-cypress": "^2.11.2",
    "eslint-plugin-jest": "^24.2.1",
    "eslint-plugin-prettier": "^3.3.1",
    "local-web-server": "^5.1.1",
    "serve": "^13.0.2",
    "typescript": "^4.4.4",
    "ws": "^8.5.0"
  }
}

After running npm run build and npm run serve, i am unable to hit a PATH defined in my routes such as localhost:5000/personal/cards/subscription/signup. I get a blank page instead.

Below is a snippet of my routes components

import ConfirmationPage from "pages/ConfirmationPage";
import SignUpForm from "pages/SignUpForm";
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";

export default () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/personal/cards/subscription/signup"
          element={<SignUpForm />}
        />
        <Route
          path="/personal/cards/subscription/confirm"
          element={<ConfirmationPage />}
        />
      </Routes>
    </BrowserRouter>
  );
};

Any ideas? Thank you!


问:
Phantom NA's in dataframe when regression in R
I have pretty large dataframe -- about 235K rows and I want to do multivariate regression:

```<code>model <- lm(var~., data=data)
</code>```

but I get an error:

```<code>Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
  NA/NaN/Inf в 'y'
In addition: Warning message:
In storage.mode(v) <- "double" : NAs introduced by coercion
</code>```

Neither na.omit, nor other methods of getting rid of NA's didn't help.

So I've tried to find NA by myself. I've split dataframe into two parts:

Second UPD

```<code>data1 <- data[1:(dim(data)[1]/2), ]
data2 <- data[(dim(data)[1]/2):(dim(data)[1]), ]
</code>```

and I again get result for both lm and no errors from previous UPD section! NB: I've restarted RStudio.

First UPD

```<code>data1 <- data[1:(dim(data)[1]/2),]
</code>```

and when I call lm instead of previous error I get next:

```<code>Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels
</code>```

To reach this error I reduced data from 235K to 14.5K. So, what is the problem now? Some of offcasted slices don't throw any errors.

Origin version

```<code>data1 <- data[1:(dim(data)[1]/2)]
data2 <- data[(dim(data)[1]/2):(dim(data)[1])]
</code>```

and call lm for each of them:

```<code>model1 <- lm(var~., data=data1)
model2 <- lm(var~., data=data2)
</code>```

and I reciece no errors! So, I suppose problem is in big size of dataframe. Is there any way to fix it?

答:
From the outputs of str(data) it looks like some of your numeric predictors are coded as "characters".

Re-code them to numeric using as.numeric and see if that fixes the issue.

If it does you might want to check why they're coded as characters. Are there rogue punctuation or spaces in your data?

Body:
I have pretty large dataframe -- about 235K rows and I want to do multivariate regression:

model <- lm(var~., data=data)

but I get an error:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
  NA/NaN/Inf в 'y'
In addition: Warning message:
In storage.mode(v) <- "double" : NAs introduced by coercion

Neither na.omit, nor other methods of getting rid of NA's didn't help.

So I've tried to find NA by myself. I've split dataframe into two parts:

Second UPD

data1 <- data[1:(dim(data)[1]/2), ]
data2 <- data[(dim(data)[1]/2):(dim(data)[1]), ]

and I again get result for both lm and no errors from previous UPD section! NB: I've restarted RStudio.

First UPD

data1 <- data[1:(dim(data)[1]/2),]

and when I call lm instead of previous error I get next:

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels

To reach this error I reduced data from 235K to 14.5K. So, what is the problem now? Some of offcasted slices don't throw any errors.

Origin version

data1 <- data[1:(dim(data)[1]/2)]
data2 <- data[(dim(data)[1]/2):(dim(data)[1])]

and call lm for each of them:

model1 <- lm(var~., data=data1)
model2 <- lm(var~., data=data2)

and I reciece no errors! So, I suppose problem is in big size of dataframe. Is there any way to fix it?


问:
Matching two data frames of longitudes and latitudes in python
I have a list of longitudes and latitudes that are stores located in a city.

```<code>ID   Latitude Longitude
1    28.2828  48.8392
2    28.3829  48.2947
3    27.9274  48.9274
4    28.9284  48.1937
5    27.2749  48.2804
…
1000 27.9292  48.9284
</code>```

I have another list of longitudes and latitudes that have stores located in the state.

```<code>ID   Latitude Longitude
8392 28.73948 48.9284
7274 19.82744 27.2837
7293 28.72847 48.92847
8384 18.28474 83.29374
2848 28.92745 48.8293
…
</code>```

Using python, how can I find which data points in the second data frame are located in the area made up by the first data frame?

In other words, this is my desired result because these ID’s in the second data frame are located in the city made up by the first data frame. All of the other ID’s are filtered out because they span other areas.

```<code>ID    Latitude Longitude
8392 28.73948 48.9284
7293 28.72847 48.92847
2848 28.92745 48.8293
</code>```

答:
your sample data does not have any points that intersect between state and convex hull of city

to find an intersection you need a polygon that represents your city. This can be achieved with https://shapely.readthedocs.io/en/latest/manual.html#object.convex_hull

once your have a polygon that represents the city you can sjoin() to other points.  I have simulated this to get some points

also provided visualisation to demonstrate

```<code>import pandas as pd
import geopandas as gpd
import io
import shapely

df_city = pd.read_csv(
    io.StringIO(
        """ID   Latitude Longitude
1    28.2828  48.8392
2    28.3829  48.2947
3    27.9274  48.9274
4    28.9284  48.1937
5    27.2749  48.2804
1000 27.9292  48.9284"""
    ),
    sep="\s+",
)

df_state = pd.read_csv(
    io.StringIO(
        """ID   Latitude Longitude
8392 28.73948 48.9284
7274 19.82744 27.2837
7293 28.72847 48.92847
8384 18.28474 83.29374
2848 28.92745 48.8293"""
    ),
    sep="\s+",
)

city_geom = shapely.geometry.MultiPoint(
    gpd.points_from_xy(df_city["Longitude"], df_city["Latitude"])
).convex_hull

# have some overlapping points...
df_state2 = pd.concat([df_state, df_city.sample(2)])
gpd.GeoDataFrame(
    df_state2, geometry=gpd.points_from_xy(df_state2["Longitude"], df_state2["Latitude"], crs="epsg:4326")
).sjoin(gpd.GeoDataFrame(geometry=[city_geom], crs="epsg:4326"))
</code>```

ID
Latitude
Longitude
geometry
index_right

1
28.2828
48.8392
POINT (48.8392 28.2828)
0

3
27.9274
48.9274
POINT (48.9274 27.9274)
0

visualisation

```<code>m = gpd.GeoDataFrame(
    df_state, geometry=gpd.points_from_xy(df_state["Longitude"], df_state["Latitude"], crs="epsg:4326")
).explore()
gpd.GeoDataFrame(geometry=[city_geom], crs="epsg:4326").explore(m=m)

</code>```

Body:
I have a list of longitudes and latitudes that are stores located in a city.

ID   Latitude Longitude
1    28.2828  48.8392
2    28.3829  48.2947
3    27.9274  48.9274
4    28.9284  48.1937
5    27.2749  48.2804
…
1000 27.9292  48.9284

I have another list of longitudes and latitudes that have stores located in the state.

ID   Latitude Longitude
8392 28.73948 48.9284
7274 19.82744 27.2837
7293 28.72847 48.92847
8384 18.28474 83.29374
2848 28.92745 48.8293
…

Using python, how can I find which data points in the second data frame are located in the area made up by the first data frame?

In other words, this is my desired result because these ID’s in the second data frame are located in the city made up by the first data frame. All of the other ID’s are filtered out because they span other areas.

ID    Latitude Longitude
8392 28.73948 48.9284
7293 28.72847 48.92847
2848 28.92745 48.8293

Body:
your sample data does not have any points that intersect between state and convex hull of city

to find an intersection you need a polygon that represents your city. This can be achieved with https://shapely.readthedocs.io/en/latest/manual.html#object.convex_hull

once your have a polygon that represents the city you can sjoin() to other points.  I have simulated this to get some points

also provided visualisation to demonstrate

import pandas as pd
import geopandas as gpd
import io
import shapely

df_city = pd.read_csv(
    io.StringIO(
        """ID   Latitude Longitude
1    28.2828  48.8392
2    28.3829  48.2947
3    27.9274  48.9274
4    28.9284  48.1937
5    27.2749  48.2804
1000 27.9292  48.9284"""
    ),
    sep="\s+",
)

df_state = pd.read_csv(
    io.StringIO(
        """ID   Latitude Longitude
8392 28.73948 48.9284
7274 19.82744 27.2837
7293 28.72847 48.92847
8384 18.28474 83.29374
2848 28.92745 48.8293"""
    ),
    sep="\s+",
)

city_geom = shapely.geometry.MultiPoint(
    gpd.points_from_xy(df_city["Longitude"], df_city["Latitude"])
).convex_hull

# have some overlapping points...
df_state2 = pd.concat([df_state, df_city.sample(2)])
gpd.GeoDataFrame(
    df_state2, geometry=gpd.points_from_xy(df_state2["Longitude"], df_state2["Latitude"], crs="epsg:4326")
).sjoin(gpd.GeoDataFrame(geometry=[city_geom], crs="epsg:4326"))

ID
Latitude
Longitude
geometry
index_right

1
28.2828
48.8392
POINT (48.8392 28.2828)
0

3
27.9274
48.9274
POINT (48.9274 27.9274)
0

visualisation

m = gpd.GeoDataFrame(
    df_state, geometry=gpd.points_from_xy(df_state["Longitude"], df_state["Latitude"], crs="epsg:4326")
).explore()
gpd.GeoDataFrame(geometry=[city_geom], crs="epsg:4326").explore(m=m)


问:
Web address of .url files in Sharepoint Online document library
When we add "Link" files to the Sharepoint document library, how can we edit/display the original web address of these .URL files?

Currently, I can only see it when I click on the URL.

答: Per my test and knowledge, URL files created in the document library cannot be edited. You could click Copy link to check the link of URL file.</p>


问:
How do I rename all folders and files to lowercase on Linux?
I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter).

Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box.

There were some valid arguments about details of the file renaming.

I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too.

I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code).

The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.

答:
I believe the one-liners can be simplified:

for f in **/*; do mv "$f" "${f:l}"; done

OwnerDisplayName: vividos

LastEditorDisplayName: dsm


问:
Select all rows but park on specific
I need to show all rows in a table but park on a specific one.

```<code>Select * from t_table
</code>```

will show me all but park on the top.

```<code>select * from t_table where id=1000
</code>```

will only show me id=1000.

what I need is

```<code>select * from t_table locate id=1000
</code>```

is this possible ?

Example :

If the storedprocedure showing this select has a parameter @PartCode.
This can be NULL (show all) of a certain partcode. f.e. 2000443

The select in the stored procedure should park on this partcode but not filter

答:
To have your required "partcode" appear at the top of the result set you will need to pass its value as a parameter to your procedure, so assuming this is @PartCode

```<code><your select query>
order by
  case when t.Partcode = @PartCode then 0 else 1 end, <other criteria>
</code>```

Title: Select all rows but park on specific

Body:
I need to show all rows in a table but park on a specific one.

Select * from t_table

will show me all but park on the top.

select * from t_table where id=1000

will only show me id=1000.

what I need is

select * from t_table locate id=1000

is this possible ?

Example :

If the storedprocedure showing this select has a parameter @PartCode.
This can be NULL (show all) of a certain partcode. f.e. 2000443

The select in the stored procedure should park on this partcode but not filter

Body:
To have your required "partcode" appear at the top of the result set you will need to pass its value as a parameter to your procedure, so assuming this is @PartCode

<your select query>
order by
  case when t.Partcode = @PartCode then 0 else 1 end, <other criteria>


问:
http vs web socket memory usage per connection in spite of request body
I need to benchmark how much memory used per connection in HTTP(request/response) vs web socket connection in the same condition(ex. request body).

How can I  theoretically or practically benchmark this scenario?

If any work already has done for this, please refer to me.

答:
The exact use of memory for websocket(not socket.io ) is: for 1 TCP connection it take 40MB, for 1000(1k) TCP connections it take 80 MB, for 10,000(10k) TCP connections it takes 210 MB.

Now if you use Socket.io then for 1000 TCP connections it will take 200MB, for 10,000(10k) TCP connection it take almost 2 GB. And most Importantly socket.io is around 3 times slower than pure websocket.

Conclusion:   So when you use pure websocket it becomes really efficient for both memory uses and data flowing speed.


问:
How to make setting scrollTop scroll to the point instantly?
I'm trying to scroll to a certain block on page load like this (needs to work in IE 11):

```<code>getScrollbaleContainer().scrollTop =
         block.getBoundingClientRect().top +
         (window.pageYOffset || document.documentElement.scrollTop);
</code>```

But Chromium browsers and Firefox scroll to that point with a duration. Is there a way to make it scroll instantly?

答:
You can do this by setting and unsetting the scroll-behavior css property:</p>
```<code>const container = getPageScrollContainer();
container.style.scrollBehavior = 'auto';
container.scrollTop =
              block.getBoundingClientRect().top +
              (window.pageYOffset || document.documentElement.scrollTop);
container.style.scrollBehavior = '';
</code>```

Body:
I'm trying to scroll to a certain block on page load like this (needs to work in IE 11):

getScrollbaleContainer().scrollTop =
         block.getBoundingClientRect().top +
         (window.pageYOffset || document.documentElement.scrollTop);

But Chromium browsers and Firefox scroll to that point with a duration. Is there a way to make it scroll instantly?

Body:
You can do this by setting and unsetting the scroll-behavior css property:

const container = getPageScrollContainer();
container.style.scrollBehavior = 'auto';
container.scrollTop =
              block.getBoundingClientRect().top +
              (window.pageYOffset || document.documentElement.scrollTop);
container.style.scrollBehavior = '';


问:
Python - Pip Install - Proxy Error - 'Cannot connect to proxy.', OSError'
I want to install some modules in a Enterprise VM in order to create some Python Scripts. I'm trying to use PIP with Proxy to do it. I'm using this command lines:

```<code>C:\Users\user>SET HTTPS_PROXY=https://user:pass@199.00.11.11:8080

C:\Users\user>SET PROXY=http://user:pass@199.00.11.11:8080

C:\Users\user>pip install datetime
</code>```

To have access to my virtual machine I've this credentials:

USER: NAN/user

PASS: pass

But I am getting this error:

```<code>Collecting datetime
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Could not find a version that satisfies the requirement datetime (from versions: )
No matching distribution found for datetime
</code>```

What I need to do in order to get the python module?

答: Try like: Go to *control panel --> Internet options --> Connections -->LAN Settings ->mark 'use proxy server for local address' options.</p>

Body:
I want to install some modules in a Enterprise VM in order to create some Python Scripts. I'm trying to use PIP with Proxy to do it. I'm using this command lines:

C:\Users\user>SET HTTPS_PROXY=https://user:pass@199.00.11.11:8080

C:\Users\user>SET PROXY=http://user:pass@199.00.11.11:8080

C:\Users\user>pip install datetime

To have access to my virtual machine I've this credentials:

USER: NAN/user

PASS: pass

But I am getting this error:

Collecting datetime
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )',))': /simple/datetime/
  Could not find a version that satisfies the requirement datetime (from versions: )
No matching distribution found for datetime

What I need to do in order to get the python module?


问:
Divide number into digits and save them in list (array) using python
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

```<code>dig = [0 for i in range(10)]
</code>```

and then

```<code>i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num
</code>```

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

```<code>i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1
</code>```

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

答:
Assuming num is a positive integer, the number of digits is equal to int(math.log10(num) + 1).

But better than that is to just use the append method of list -- then you won't have to know the length beforehand.

Even easier (though the list will be in reverse order):

```<code>dig = [int(x) for x in str(num)]
</code>```

or

```<code>dig = map(int, str(num))
</code>```

Body:
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

dig = [0 for i in range(10)]

and then

i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

Body:
Assuming num is a positive integer, the number of digits is equal to int(math.log10(num) + 1).

But better than that is to just use the append method of list -- then you won't have to know the length beforehand.

Even easier (though the list will be in reverse order):

dig = [int(x) for x in str(num)]

or

dig = map(int, str(num))


问:
Vite.js (Vue): Unwanted Page Reload Happens Only On Samsung Internet
I have a weird problem with Vite.js and it only happens on Samsung Internet when I'm on development server...

Problem: page reloads automatically 3 seconds in a loop and I don't set nor write any intervals... the page reload happens at browser level.

These are unwanted reloads and I want to get rid of them.

Any Idea why it happens?

答:
Edited asnwer:

Ok so, I looked closer to this problem and I found some possible solutions.

Samsung Internet (same as Chrome) doesn't allow unsecure websocket (ws) connections to localhost (only wss, so you should setup a TLS certificate for your local web/websocket server). However the same should work fine with Firefox.

Another reason for this error could be "overloading" the same port. Maybe other app, which you are running, uses port 3000. The solution would be to stop that process or again change the port.

Testing solution: Does the code works if you do this?

// Original line
new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')

// Replace with exact url with port that you are running the app
new WebSocket("ws://localhost:3000")
```


问:
How do I factor out a unit conversion in python
If there is an answer somewhere else, please just link it. I looked for hours.

Problem

Write a function so that the main program below can be replaced by the simpler code that calls function mph_and_minutes_to_miles(). Original main program:

```<code>miles_per_hour = float(input())
minutes_traveled = float(input())
hours_traveled = minutes_traveled / 60.0
miles_traveled = hours_traveled * miles_per_hour

print('Miles: {:f}'.format(miles_traveled))
</code>```

Sample output with inputs: 70.0 100.0
Miles: 116.666667

MY CODE

```<code>def mph_and_minutes_to_miles(miles_per_hour, minutes_traveled):
    miles_per_hour = float(input())
    hours_traveled = minutes_traveled / 60
    miles_traveled = hours_traveled * miles_per_hour
    return hours_traveled

miles_per_hour = float(input())
minutes_traveled = float(input())

print('Miles: {:f}'.format(mph_and_minutes_to_miles(miles_per_hour, minutes_traveled)))
</code>```

OUTPUTS

Testing with inputs: 70.0 100.0

Output differs. See highlights below.

Your output
Miles: 1.666667

Expected output
Miles: 116.666667

答:
here it works correctly

# python program to convert mph and minutes to miles

def main():
    print("This program converts mph and minutes to miles\n")

    mph = input("Enter the speed in mph: ")
    minutes = input("Enter the time in minutes: ")

    miles = mph * minutes / 60

    print("The distance is", miles, "miles")

main()
```

Body:
If there is an answer somewhere else, please just link it. I looked for hours.

Problem

Write a function so that the main program below can be replaced by the simpler code that calls function mph_and_minutes_to_miles(). Original main program:

miles_per_hour = float(input())
minutes_traveled = float(input())
hours_traveled = minutes_traveled / 60.0
miles_traveled = hours_traveled * miles_per_hour

print('Miles: {:f}'.format(miles_traveled))

Sample output with inputs: 70.0 100.0
Miles: 116.666667

MY CODE

def mph_and_minutes_to_miles(miles_per_hour, minutes_traveled):
    miles_per_hour = float(input())
    hours_traveled = minutes_traveled / 60
    miles_traveled = hours_traveled * miles_per_hour
    return hours_traveled

miles_per_hour = float(input())
minutes_traveled = float(input())

print('Miles: {:f}'.format(mph_and_minutes_to_miles(miles_per_hour, minutes_traveled)))

OUTPUTS

Testing with inputs: 70.0 100.0

Output differs. See highlights below.

Your output
Miles: 1.666667

Expected output
Miles: 116.666667


问:
Removing the "box" of a checkbox in css
I am trying to remove the actual box of a checkbox field, and just make the text clickable.   How can I do this with JS and css?  I started using buttons, but I switched to checkboxes because the "state" of the box is easier to find out than a button. But now that I am polishing up the page with css for better formatting and layout, The boxes are getting in the way, and I would prefer just for the text to be clickable without a box present.</p>

答:
Use appearance: none;

Note: Not compatible or consistent with all browsers, see the MDN docs

Title: Removing the "box" of a checkbox in css


问:
Python cleaning up / refactoring redundant code
This is probably quite a newbie question. I started learning python by programming webscrapers. In each module I have a default set of imports and profile sets that I need for it. They are always the same, initializing the selenium webdrivers, setting it into headless mode, etc.

```<code>from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import FirefoxProfile
import openpyxl
...
profile = FirefoxProfile()
profile.set_preference("browser.download.panel.shown", False)
...
</code>```

They take up a lot of lines in each file and I wanted to clean this up a bit by having them all in a seperate .py module but I don't understand how I can accomplish that. Simply putting all that into a function and importing that .py file doesn't work.

答:
You're halfway there - put all the imports into a separate .py file in the same directory, let's call it selenium_imports.py. To get all the modules into your namespaces, you'll have to run the following:

from selenium_imports import *
```

Then all your modules will be loaded correctly.

Body:
This is probably quite a newbie question. I started learning python by programming webscrapers. In each module I have a default set of imports and profile sets that I need for it. They are always the same, initializing the selenium webdrivers, setting it into headless mode, etc.

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import FirefoxProfile
import openpyxl
...
profile = FirefoxProfile()
profile.set_preference("browser.download.panel.shown", False)
...

They take up a lot of lines in each file and I wanted to clean this up a bit by having them all in a seperate .py module but I don't understand how I can accomplish that. Simply putting all that into a function and importing that .py file doesn't work.

Body:
You're halfway there - put all the imports into a separate .py file in the same directory, let's call it selenium_imports.py. To get all the modules into your namespaces, you'll have to run the following:

from selenium_imports import *

Then all your modules will be loaded correctly.