问:
How to mock system call in C++ Unit Testing during runtime using GoogleMock?
I have a module written in C. In which I have API defined as follow.

```<code>int ReadData(void* data, int data_size, char* filename, int offset)
</code>```

When performing unit test in order to cover full coverage I need to hit at error condition for fseek and fread system call.
Can somebody explain me How can I override fseek/fread during particular test case so instead of system call it will call mock fseek/fread for that test case ?

```<code>ReadAPI.c
</code>```
```<code>#include<stdio.h>
#include<stdlib.h>

int readdata(void* data,int size, int offset, char* filename)
{
    if(data == NULL || size == 0 || filename == NULL)
    {
        return -1;
    }

    FILE* fp = fopen(filename,"rb");
    if(fp == NULL)
    {
        return -1;
    }

    if(fseek(fp,offset,SEEK_SET) != 0)
    {
        fclose(fp);
        return -1;
    }

    fread(data,size,1,fp);

    if(ferror(fp))
    {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    return 1;
}

</code>```
```<code>readapi.h
</code>```
```<code>#include<stdio.h>
#include<stdlib.h>

int readdata(void* data,int size, int offset, char* filename)
</code>```
```<code>Test.cpp
</code>```
```<code>#include<gtest/gtest.h>
#include"readapi.h"

TEST(test, Test1fseek)
{
    // When fseek called in readdata API call mock fseek to hit fseek fail
    // fseek(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

TEST(test, Test2fread)
{
    //When fread called in readdata API call mock fread to hit read fail
    // fread(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

int main()
{
    return RUN_ALL_TEST();
}

</code>```

答:
If you are using gcc/g++ or clang/clang++ you can use the linker option --wrap=symbol to redirect calls to your own versions of these functions.

Your wrapper functions will have the name __wrap_symbol and the real functions will be named __real_symbol.

Example:

int __wrap_fseek(FILE *stream, long offset, int whence) {
    printf("__wrap_fseek: %ld %d\n", offset, whence);
    return __real_fseek(stream, offset, whence);
}

size_t __wrap_fread(void *restrict ptr, size_t size, size_t nmemb,
                    FILE *restrict stream)
{
    return __real_fread(ptr, size, nmemb, stream);
}
```

Compile with g++ ... -Wl,--wrap=fseek,--wrap=fread

Body:
I have a module written in C. In which I have API defined as follow.

int ReadData(void* data, int data_size, char* filename, int offset)

When performing unit test in order to cover full coverage I need to hit at error condition for fseek and fread system call.
Can somebody explain me How can I override fseek/fread during particular test case so instead of system call it will call mock fseek/fread for that test case ?

ReadAPI.c

#include<stdio.h>
#include<stdlib.h>

int readdata(void* data,int size, int offset, char* filename)
{
    if(data == NULL || size == 0 || filename == NULL)
    {
        return -1;
    }

    FILE* fp = fopen(filename,"rb");
    if(fp == NULL)
    {
        return -1;
    }

    if(fseek(fp,offset,SEEK_SET) != 0)
    {
        fclose(fp);
        return -1;
    }

    fread(data,size,1,fp);

    if(ferror(fp))
    {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    return 1;
}

readapi.h

#include<stdio.h>
#include<stdlib.h>

int readdata(void* data,int size, int offset, char* filename)

Test.cpp

#include<gtest/gtest.h>
#include"readapi.h"

TEST(test, Test1fseek)
{
    // When fseek called in readdata API call mock fseek to hit fseek fail
    // fseek(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

TEST(test, Test2fread)
{
    //When fread called in readdata API call mock fread to hit read fail
    // fread(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

int main()
{
    return RUN_ALL_TEST();
}

Body:
If you are using gcc/g++ or clang/clang++ you can use the linker option --wrap=symbol to redirect calls to your own versions of these functions.

Your wrapper functions will have the name __wrap_symbol and the real functions will be named __real_symbol.

Example:

int __wrap_fseek(FILE *stream, long offset, int whence) {
    printf("__wrap_fseek: %ld %d\n", offset, whence);
    return __real_fseek(stream, offset, whence);
}

size_t __wrap_fread(void *restrict ptr, size_t size, size_t nmemb,
                    FILE *restrict stream)
{
    return __real_fread(ptr, size, nmemb, stream);
}

Compile with g++ ... -Wl,--wrap=fseek,--wrap=fread


来源: stackexchange

问:
android start activity with animation
Is it possible to ad an animation to an activity at runtime so when I start the activity, it starts with my animation? I want to specify some parameters to animation at runtime depending on some view's position. I've managed to ad an animation, but the animation was defined in a xml file so I was not able to edit the numbers from animation. Is it possible to do this?</p>

答: You could define your animation in code instead of the XML file. For example here it is explained how to do that. THen you can change things at runtime by using variables.</p>

ContentLicense: CC BY-SA 3.0

Title: android start activity with animation

OwnerDisplayName: anon


问:
Determine whether a data element in a Pandas Dataframe is present in another Dataframe
I have two Pandas Dataframes (df1 and df2), both of which have identical structures, and both of which have several hundred thousand rows.

I'd like to update a field for each row indicating whether the ID for the row is found anywhere in a field in the other dataframe.

```<code>df1 = pd.DataFrame([['AAA',''],['BBB',''],['CCC','']], columns=['ID','Match'])
df2 = pd.DataFrame([['FFF',''],['BBB',''],['AAA',''],['BBB','']], columns=['ID','Match'])
</code>```

And I'd like to end up with a result that looks like:

```<code>ID  Match
FFF N
BBB Y
AAA Y
BBB Y
</code>```

答:
You could join the IDs in df1 and use str.contains to identify the IDs that contains any ID from df1; then use np.where to assign "Y" if there is a match, "N" otherwise:

```<code>df2['Match'] = np.where(df2['ID'].str.contains('|'.join(df1['ID'])), 'Y', 'N')
</code>```

Output:

```<code>    ID Match
0  FFF     N
1  BBB     Y
2  AAA     Y
3  BBB     Y
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two Pandas Dataframes (df1 and df2), both of which have identical structures, and both of which have several hundred thousand rows.

I'd like to update a field for each row indicating whether the ID for the row is found anywhere in a field in the other dataframe.

df1 = pd.DataFrame([['AAA',''],['BBB',''],['CCC','']], columns=['ID','Match'])
df2 = pd.DataFrame([['FFF',''],['BBB',''],['AAA',''],['BBB','']], columns=['ID','Match'])

And I'd like to end up with a result that looks like:

ID  Match
FFF N
BBB Y
AAA Y
BBB Y

Body:
You could join the IDs in df1 and use str.contains to identify the IDs that contains any ID from df1; then use np.where to assign "Y" if there is a match, "N" otherwise:

df2['Match'] = np.where(df2['ID'].str.contains('|'.join(df1['ID'])), 'Y', 'N')

Output:

    ID Match
0  FFF     N
1  BBB     Y
2  AAA     Y
3  BBB     Y


问:
how to resize windows ec2 root volume (c)
is there an automated way to resize a windows ec2 instance root volume (c)?

expand the root volume by 10GB

extend the disk within the OS

答:
There is no ideal way to do that without cloud watch metrics irrespective of ec2 or windows.

Yes, a crude way can be to utilize the windows command line du tool and run a cron job with it. and store the disk info in a file.
Run grep on the file, if low disk space message is there, run your script


问:
SQL Server stored procedure
I want it to count then if @intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?

```<code>@FiscalYear int,
@SchoolID int,
@Status int

AS
BEGIN

SET NOCOUNT ON;

declare @sqlstr varchar(2000)
declare @intCount int
set @intCount = 0

set @sqlstr = 'Select @intCount = Count(*)
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

 If (@intCount > 0)
 BEGIN
 set @sqlstr=   'Select SchoolName as School,
 (Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
  ELSE ''Not Uploaded'' END) AS Status,
  COUNT(Attachment.PrivateSchoolID) AS [Count]
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

    SET @sqlstr = @sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
    SET @sqlstr = @sqlstr + ' Order By SchoolName'
EXEC(@sqlstr)
 END
 ELSE
 Select 'No Data Found' as 'FileUpload'
 END
</code>```

答:
You need:

```<code>EXEC sp_executesql @sqlstr, N'@intCount INT OUTPUT', @intCount = @intCount OUTPUT;

IF (@intCount > 0)
BEGIN
    ....
END
</code>```

You'll also need to make @sqlstr NVARCHAR(2000) and add set it to N'SELECT ...' as opposed to 'SELECT ...' - that leading N can be important.

Title: SQL Server stored procedure

Body:
I want it to count then if @intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?

@FiscalYear int,
@SchoolID int,
@Status int

AS
BEGIN

SET NOCOUNT ON;

declare @sqlstr varchar(2000)
declare @intCount int
set @intCount = 0

set @sqlstr = 'Select @intCount = Count(*)
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

 If (@intCount > 0)
 BEGIN
 set @sqlstr=   'Select SchoolName as School,
 (Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
  ELSE ''Not Uploaded'' END) AS Status,
  COUNT(Attachment.PrivateSchoolID) AS [Count]
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

    SET @sqlstr = @sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
    SET @sqlstr = @sqlstr + ' Order By SchoolName'
EXEC(@sqlstr)
 END
 ELSE
 Select 'No Data Found' as 'FileUpload'
 END

Body:
You need:

EXEC sp_executesql @sqlstr, N'@intCount INT OUTPUT', @intCount = @intCount OUTPUT;

IF (@intCount > 0)
BEGIN
    ....
END

You'll also need to make @sqlstr NVARCHAR(2000) and add set it to N'SELECT ...' as opposed to 'SELECT ...' - that leading N can be important.


问:
Can't save macro-enabled workbook on remote server after a macro has run
My macro-enabled workbook has been working fine until recently. It runs fine on my local drive, but no longer saves itself when run from a remote folder. I suspect some recent updates on the server are to blame.

If I open the workbook and press the save button, a pop-up appears with a progress bar for a second or two. This has not happened before, but the pop-up does close and allow me to continue.

When I run the macro in the workbook, the last line is ThisWorkbook.Save. The same pop-up appears and hangs. If I close the pop-up and press the save button, it also hangs now. If I choose File> SaveAs, all I get is a blank page with no folders to choose from.

I have a workaround to copy the workbook to a local folder, run the macro, then copy it back to the remote drive, but this may be difficult for my users to handle.

I made a new workbook with a macro that only calls ThisWorkbook.Save from a single button, and this works fine. The problematic workbook gets data from csv files and copies it into itself. Maybe this is causing a problem? Maybe the macros are too large for the anti-malware software to handle?

Does anyone know what recent changes have been made to Server that would cause my old macro to hang on saving?

答:
I got the macro working, but not sure why.

The problem arose with an inefficient way to merge data from two sheets together. I had been using Find, and changed it to march through the data row by row instead. The saving window still pops up, but only for a second.

I don't know exactly why the old method prevented the workbook from being saved. The main difference is that the Find method uses objects, while the method I changed it to use integers and compare cell contents with an if statement. Maybe the memory was being filled with orphaned objects? I don't see what difference that should make when saving the file. The data in the sheets being saved is the same.

If anyone knows what difference this would make in saving a workbook, please add and answer or comment for posterity. It might help someone with a similar problem.


问:
Possible for input/useState not to be set on button click?
Do I need to worry that fetchClassesSearchedByName(searchName); will not have a searchName value? Is it possible my button click is faster than searchName being set?

```<code>// On input
const [searchName, setSearchName] = useState('');

// Text input
<input
    type='text'
    value={searchName}
    onChange={(e) => setSearchName(e.target.value)}
/>

// On button click
const searchNameBtn = (e) => {
        fetchClassesSearchedByName(searchName);
}
</code>```

Thank you

答:
Do I need to worry that fetchClassesSearchedByName(searchName); will
not have a searchName value?

You have defined initial searchName state and all the setSearchName calls pass valid defined values. And so long as all state updates are valid defined values, there's no chance for fetchClassesSearchedByName to be called without a defined searchName value.

Is it possible my button click is faster than searchName being set?

Yes, this is entirely possible, BUT also entirely unrealistic. It's possible because React state updates are not immediate, but are enqueued and asynchronously processed.

Consider the follow example. There are two inputs with onChange handlers.

Input and handler #1: The first input attempts to simulate clicking the button immediately after enqueueing a state update, but due to the way Javascript enclosures and the event loop work, the button's onClick event is processed before React processes the state update because it's synchronous within the onChange handler function's scope. The fetchClassesSearchedByName appears to be a "render cycle behind" because it's logging the unupdated state.

Input and handler #2: The second input attempts to simulate clicking the button immediately after enqueueing a state update, but uses a setTimeout of 0. This places the click event callback at the end of the event queue. Note that this is the earliest possible the button can even be clicked after the state update was enqueued. React's state update is processed, then the click event is processed. Note here that the fetchClassesSearchedByName now always sees the updated React state.

const fetchClassesSearchedByName = (value) => console.log(value);

function App() {
  const buttonRef = React.useRef();
  const [searchName, setSearchName] = React.useState("");

  const changeHandler1 = (e) => {
    setSearchName(e.target.value);
    buttonRef.current.click();
  };

  const changeHandler2 = (e) => {
    setSearchName(e.target.value);
    setTimeout(() => {
      buttonRef.current.click();
    }, 0);
  };

  const searchNameBtn = (e) => {
    fetchClassesSearchedByName(searchName);
  };

  return (

          Input 1 w/ synchronous button click
          <input type="text" value={searchName} onChange={changeHandler1} />

          Input 2 w/ asynchronous button click
          <input type="text" value={searchName} onChange={changeHandler2} />

        <button ref={buttonRef} type="button" onClick={searchNameBtn}>
          Click me
        </button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <App />,
  rootElement
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" /></code>```

Body:
Do I need to worry that fetchClassesSearchedByName(searchName); will not have a searchName value? Is it possible my button click is faster than searchName being set?

// On input
const [searchName, setSearchName] = useState('');

// Text input
<input
    type='text'
    value={searchName}
    onChange={(e) => setSearchName(e.target.value)}
/>

// On button click
const searchNameBtn = (e) => {
        fetchClassesSearchedByName(searchName);
}

Thank you

Body:
Do I need to worry that fetchClassesSearchedByName(searchName); will
not have a searchName value?

You have defined initial searchName state and all the setSearchName calls pass valid defined values. And so long as all state updates are valid defined values, there's no chance for fetchClassesSearchedByName to be called without a defined searchName value.

Is it possible my button click is faster than searchName being set?

Yes, this is entirely possible, BUT also entirely unrealistic. It's possible because React state updates are not immediate, but are enqueued and asynchronously processed.

Consider the follow example. There are two inputs with onChange handlers.

Input and handler #1: The first input attempts to simulate clicking the button immediately after enqueueing a state update, but due to the way Javascript enclosures and the event loop work, the button's onClick event is processed before React processes the state update because it's synchronous within the onChange handler function's scope. The fetchClassesSearchedByName appears to be a "render cycle behind" because it's logging the unupdated state.

Input and handler #2: The second input attempts to simulate clicking the button immediately after enqueueing a state update, but uses a setTimeout of 0. This places the click event callback at the end of the event queue. Note that this is the earliest possible the button can even be clicked after the state update was enqueued. React's state update is processed, then the click event is processed. Note here that the fetchClassesSearchedByName now always sees the updated React state.

const fetchClassesSearchedByName = (value) => console.log(value);

function App() {
  const buttonRef = React.useRef();
  const [searchName, setSearchName] = React.useState("");

  const changeHandler1 = (e) => {
    setSearchName(e.target.value);
    buttonRef.current.click();
  };

  const changeHandler2 = (e) => {
    setSearchName(e.target.value);
    setTimeout(() => {
      buttonRef.current.click();
    }, 0);
  };

  const searchNameBtn = (e) => {
    fetchClassesSearchedByName(searchName);
  };

  return (
    <div className="App">
      <div>
        <label>
          Input 1 w/ synchronous button click
          <input type="text" value={searchName} onChange={changeHandler1} />
        </label>
      </div>
      <div>
        <label>
          Input 2 w/ asynchronous button click
          <input type="text" value={searchName} onChange={changeHandler2} />
        </label>
      </div>

      <div>
        <button ref={buttonRef} type="button" onClick={searchNameBtn}>
          Click me
        </button>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <App />,
  rootElement
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />


问:
How to create an editable column headers in silverlight 4 datagrid?
So I'm building a silverlight datagrid dynamically (columns and cells) and I need my users to be able to change the column headers.  I used a DataTemplate with a TextBox binded to the Header (I think) on the DataGridColumnHeader.ContentTemplate.

```<code><DataTemplate xmlns='http://schemas.microsoft.com/client/2007'>
    <TextBox Text='{Binding}' />
</DataTemplate>
</code>```

However when I change the textbox's text the actual Header value does not change.  I think I need to use 2 way binding but i'm not sure how that would work.  I've been trying to wrap my head around silverlight/wpf bindings but am struggling a bit.

I suppose I could use a textbox.textchanged event to update them or something like that.  But I think it would be cleaner in xaml.

Any suggestions? I feel like someone must have created a DataGrid with editable column headers.

答:
Alright I fixed it.  So I just created a string wrapper class like so:

```<code>public class SingleString:System.ComponentModel.INotifyPropertyChanged
{
    String _value = "";
    public String Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged("Value");
        }
    }

    public SingleString()
    {
    }
    public SingleString(String val)
    {
        Value = val;
    }

    public override string ToString()
    {
        return Value;
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
}
</code>```

Then I used those object types for my column headers.  So my header style worked out to be:

```<code>    <Style x:Key="TextBoxHeader" TargetType="dataprimitives:DataGridColumnHeader">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBox Text="{Binding Value, Mode=TwoWay}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

This resulted in the Header values (which are SingleString objects) to have there values changed when the textbox text was changed.  Which resulted in correct behavior with my export.  Thanks for the help.

Body:
So I'm building a silverlight datagrid dynamically (columns and cells) and I need my users to be able to change the column headers.  I used a DataTemplate with a TextBox binded to the Header (I think) on the DataGridColumnHeader.ContentTemplate.

<DataTemplate xmlns='http://schemas.microsoft.com/client/2007'>
    <TextBox Text='{Binding}' />
</DataTemplate>

However when I change the textbox's text the actual Header value does not change.  I think I need to use 2 way binding but i'm not sure how that would work.  I've been trying to wrap my head around silverlight/wpf bindings but am struggling a bit.

I suppose I could use a textbox.textchanged event to update them or something like that.  But I think it would be cleaner in xaml.

Any suggestions? I feel like someone must have created a DataGrid with editable column headers.

Body:
Alright I fixed it.  So I just created a string wrapper class like so:

public class SingleString:System.ComponentModel.INotifyPropertyChanged
{
    String _value = "";
    public String Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged("Value");
        }
    }

    public SingleString()
    {
    }
    public SingleString(String val)
    {
        Value = val;
    }

    public override string ToString()
    {
        return Value;
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
}

Then I used those object types for my column headers.  So my header style worked out to be:

    <Style x:Key="TextBoxHeader" TargetType="dataprimitives:DataGridColumnHeader">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBox Text="{Binding Value, Mode=TwoWay}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

This resulted in the Header values (which are SingleString objects) to have there values changed when the textbox text was changed.  Which resulted in correct behavior with my export.  Thanks for the help.


问:
"istanbul ignore next" command seems to be ignored
I'm trying to use Jest to test my code. It was working quite fine until I tried to exclude a class method from the tests.

The querySelector() call is the reason why I want to skip this method from being tested ("document" is obviously null unless I run the script in the browser)

I tried this solution, which seems to be the most suggested one:

```<code>  /* istanbul ignore next */
  appendNewInputFields() {

    const howMany = Number(document.querySelector('#items-to-add').value);

    [...Array(howMany)].forEach( i => {
      const newInputField = this.createNewItemInputField();
      this.inputItemsContainerNode.append(newInputField);
    });
  }
</code>```

But the test keeps failing and the line /* istanbul ignore next */  seems to be ignored.

I've also tried putting the comment between the function signature and its body (as was suggested somewhere here on SO), but no luck:

```<code> FAIL  js/DOMManager.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'value' of null

      135 |   appendNewInputFields() /* istanbul ignore next */ {
      136 |
    > 137 |     const howMany = Number(document.querySelector('#items-to-add').value);
          |                            ^
      138 |
</code>```

I've read around that this might be related to babel-plugin-istanbul. I've tried

npm --save-dev uninstall babel-plugin-istanbul

which in the terminal returned:

```<code>npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

removed 18 packages and audited 521 packages in 2.178s
</code>```

but the folder babel-plugin-istanbul is still present in /node_modules/ inside my working folder and the test keeps failing as if nothing changed.

If I comment out the body of the function, the other test suites work perfectly. If I try to apply the ignore next command to any other part of the code, the tests pass just fine and the line is completely ignored.

If I try to manually delete the /babel-plugin-istanbul/ folder (from the /node_modules/ in my working folder), Jest stops working.

(This is the first time I installed Node.js, and I did it only because I wanted to start unit testing with Jest. I'm pointing this out because these are my first steps venturing out of the vanilla world. I don't know how to deal with Node.js nor npm, I just launched a couple commands to install it, I wrote a few tests for Jest and they all immediately worked fine. I'm not using any other framework, I'm trying to stick to vanilla JS as much as possible.)

----------------------- Edit:

I tried changing the code to this:

```<code>
  appendNewInputFields() {
    // TODO solve the istanbul ignore issue

    let howMany;

    /* istanbul ignore if */
    if(document != null) {
      howMany = Number(document.querySelector('#items-to-add').value);

      [...Array(howMany)].forEach( i => {
        const newInputField = this.createNewItemInputField();
        this.inputItemsContainerNode.append(newInputField);
      });

      console.log("added " + howMany + " input fields");
    }
  }
</code>```

I keep getting

```<code> FAIL  js/DOMManager.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'value' of null

      139 |     /* istanbul ignore if */
      140 |     if(document != null) {
    > 141 |       howMany = Number(document.querySelector('#items-to-add').value);
          |                        ^
      142 |
      143 |       [...Array(howMany)].forEach( i => {
      144 |         const newInputField = this.createNewItemInputField();
</code>```

I'm totally clueless at this point. Given the conditional, "document" should be null and that block entirely skipped, but it keeps failing the test.

The same code works exactly as intended when run in the browser.

答:
I was with the same error with window.alert command with jest:

```<code>ReferenceError: alert is not defined

  4 |
  5 | /* istanbul ignore next */
> 6 | alert(helloWorld());
    | ^
  7 |
</code>```

so I tried to use try-catch and SUCCESS!

before:

```<code>alert(helloWorld());
</code>```

after:

```<code>const alerta = () => {
  try {
    return alert(helloWorld());
  } catch (error) {
      return false;
  }
}
</code>```

testes:

```<code>Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
</code>```

Body:
I'm trying to use Jest to test my code. It was working quite fine until I tried to exclude a class method from the tests.

The querySelector() call is the reason why I want to skip this method from being tested ("document" is obviously null unless I run the script in the browser)

I tried this solution, which seems to be the most suggested one:

  /* istanbul ignore next */
  appendNewInputFields() {

    const howMany = Number(document.querySelector('#items-to-add').value);

    [...Array(howMany)].forEach( i => {
      const newInputField = this.createNewItemInputField();
      this.inputItemsContainerNode.append(newInputField);
    });
  }

But the test keeps failing and the line /* istanbul ignore next */  seems to be ignored.

I've also tried putting the comment between the function signature and its body (as was suggested somewhere here on SO), but no luck:

 FAIL  js/DOMManager.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'value' of null

      135 |   appendNewInputFields() /* istanbul ignore next */ {
      136 |
    > 137 |     const howMany = Number(document.querySelector('#items-to-add').value);
          |                            ^
      138 |

I've read around that this might be related to babel-plugin-istanbul. I've tried

npm --save-dev uninstall babel-plugin-istanbul

which in the terminal returned:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

removed 18 packages and audited 521 packages in 2.178s

but the folder babel-plugin-istanbul is still present in /node_modules/ inside my working folder and the test keeps failing as if nothing changed.

If I comment out the body of the function, the other test suites work perfectly. If I try to apply the ignore next command to any other part of the code, the tests pass just fine and the line is completely ignored.

If I try to manually delete the /babel-plugin-istanbul/ folder (from the /node_modules/ in my working folder), Jest stops working.

(This is the first time I installed Node.js, and I did it only because I wanted to start unit testing with Jest. I'm pointing this out because these are my first steps venturing out of the vanilla world. I don't know how to deal with Node.js nor npm, I just launched a couple commands to install it, I wrote a few tests for Jest and they all immediately worked fine. I'm not using any other framework, I'm trying to stick to vanilla JS as much as possible.)

----------------------- Edit:

I tried changing the code to this:

  appendNewInputFields() {
    // TODO solve the istanbul ignore issue

    let howMany;

    /* istanbul ignore if */
    if(document != null) {
      howMany = Number(document.querySelector('#items-to-add').value);

      [...Array(howMany)].forEach( i => {
        const newInputField = this.createNewItemInputField();
        this.inputItemsContainerNode.append(newInputField);
      });

      console.log("added " + howMany + " input fields");
    }
  }

I keep getting

 FAIL  js/DOMManager.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'value' of null

      139 |     /* istanbul ignore if */
      140 |     if(document != null) {
    > 141 |       howMany = Number(document.querySelector('#items-to-add').value);
          |                        ^
      142 |
      143 |       [...Array(howMany)].forEach( i => {
      144 |         const newInputField = this.createNewItemInputField();

I'm totally clueless at this point. Given the conditional, "document" should be null and that block entirely skipped, but it keeps failing the test.

The same code works exactly as intended when run in the browser.

Body:
I was with the same error with window.alert command with jest:

ReferenceError: alert is not defined

  4 |
  5 | /* istanbul ignore next */
> 6 | alert(helloWorld());
    | ^
  7 |

so I tried to use try-catch and SUCCESS!

before:

alert(helloWorld());

after:

const alerta = () => {
  try {
    return alert(helloWorld());
  } catch (error) {
      return false;
  }
}

testes:

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total


问:
How can I send get or post request to Heroku API using ESP8266?
Currently I have build a simple api using nodejs and deployed it in heroku.
Heroku is a secured website so I have used WiFiClientSecure.h in my nodemcu program to connect to the api . But it is returning errors like this .

```<code>connecting to WIFI
....
WiFi connected
IP address:
xxxxxxxxxxx
connecting to api71.herokuapp.com

 CUT HERE FOR EXCEPTION DECODER ---------------

Exception (9):
epc1=0x40207acc epc2=0x00000000 epc3=0x00000000 excvaddr=0xfeefeffe depc=0x00000000
>>>stack>>>

ctx: cont
sp: 3ffffc80 end: 3fffffc0 offset: 0190
3ffffe10:  3ffe87d5 3fff11bc 3ffffea0 40203b53
3ffffe20:  00000124 3ffee784 00000001 40205b14
3ffffe30:  00000000 00000000 00000000 4020610e
3ffffe40:  00000000 3ffffea0 3ffef52c 4020281c
3ffffe50:  3ffee680 00000d50 3ffe86fc 3ffe862b
3ffffe60:  000001bb 3ffffea0 3ffe87d5 3ffe862b
3ffffe70:  000001bb 3ffffea0 3ffe87d5 40203d29
3ffffe80:  40208078 54cac522 40208078 54cac522
3ffffe90:  3ffe84cc 3ffe84cc 3ffee6a0 40201150
3ffffea0:  40207f18 00000000 00003a98 feefeffe
3ffffeb0:  00000000 3ffef52c 3fff11bc 3ffef66c
3ffffec0:  00000000 00000000 3fff11bc 3fff62c4
3ffffed0:  3ffef75c 00000000 00000000 00000000
3ffffee0:  00000000 3fff1f14 3ffef57c 3fff6064
3ffffef0:  3ffef594 00000000 00000000 00000000
3fffff00:  00004145 00000255 feef0000 00000000
3fffff10:  00000000 00000000 00000000 00000000
3fffff20:  00000000 00000000 feef0000 feefeffe
3fffff30:  feefeffe feefeffe feefeffe fe00effe
3fffff40:  00000000 feefeffe 00000000 00000000
3fffff50:  feefef00 00000000 00000000 feefeffe
3fffff60:  feefeffe feefeffe feefeffe feefeffe
3fffff70:  feefeffe feefeffe feefeffe feefeffe
3fffff80:  feefeffe feefeffe feefeffe feefeffe
3fffff90:  feefeffe feefeffe feefeffe 3ffee728
3fffffa0:  3fffdad0 00000000 3ffee6e8 40205c24
3fffffb0:  feefeffe feefeffe 3ffe84f0 40100b85
<<<stack<<<
</code>```

I have checked my api in localhost and it is working fine. There is a problem with interacting with secured website . Heroku uses sha256RSA Signature Algorithm and sha256 as signature hash .
Here is my code which I have deployed

```<code>#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const char * ssid = "YOURNETWORK";
const char * password = "YOURPASSWORD";
const char * host = "api71.herokuapp.com";
String path = "/api/courses"; // Path of Server
const int httpsPort = 443; // HTTPS PORT (default: 443)
int refreshtime = 15; // Make new HTTPS request after x seconds

String datarx; // Received data as string
long crontimer;

void setup () {
  delay (1000);
  Serial.begin (115200);
  WiFi.mode (WIFI_OFF);
  delay (1000);
  WiFi.mode (WIFI_STA);
  WiFi.begin (ssid, password);
  Serial.print ("Connecting");
  while (WiFi.status ()! = WL_CONNECTED) {
    delay (500);
    Serial.print (".");
  }
  Serial.print ("Connected:");
  Serial.println (ssid);
}

void loop () {
  if (crontimer <millis () / 1000) {
    crontimer = (millis () / 1000) + refreshtime;
    callhttps (); //
  }
}

void callhttps () {
  WiFiClientSecure httpsClient;
  httpsClient.setTimeout (15000);
  delay (1000);
  int retry = 0;
  while ((! httpsClient.connect (host, httpsPort)) && (retry <15)) {
    delay (100);
    Serial.print (".");
    retry ++;
  }
  if (retry == 15) {
    Serial.println ("Connection failed");
  }
  else {
    Serial.println ("Connected to Server");
  }
  httpsClient.print (String ("GET") + path +
                    "HTTP / 1.1 \ r \ n" +
                    "Host:" + host +
                    "\ r \ n" + "Connection: close \ r \ n \ r \ n");
  while (httpsClient.connected ()) {
    String line = httpsClient.readStringUntil ('\ n');
    if (line == "\ r") {
      break;
    }
  }
  while (httpsClient.available ()) {
    datarx + = httpsClient.readStringUntil ('\ n');
  }
  Serial.println (datarx);
  datarx = "";
}
</code>```

Is there any why to connect to this website ? Please help me .

答: Sometimes is just a buffer overflow of Serial.print, if it's the case,  use a JSON lib for ESP to turn over this issue, or just remove Serial.print if isn't needed, or maybe to test if this is not the case.</p>

Body:
Currently I have build a simple api using nodejs and deployed it in heroku.
Heroku is a secured website so I have used WiFiClientSecure.h in my nodemcu program to connect to the api . But it is returning errors like this .

connecting to WIFI
....
WiFi connected
IP address:
xxxxxxxxxxx
connecting to api71.herokuapp.com

 CUT HERE FOR EXCEPTION DECODER ---------------

Exception (9):
epc1=0x40207acc epc2=0x00000000 epc3=0x00000000 excvaddr=0xfeefeffe depc=0x00000000
>>>stack>>>

ctx: cont
sp: 3ffffc80 end: 3fffffc0 offset: 0190
3ffffe10:  3ffe87d5 3fff11bc 3ffffea0 40203b53
3ffffe20:  00000124 3ffee784 00000001 40205b14
3ffffe30:  00000000 00000000 00000000 4020610e
3ffffe40:  00000000 3ffffea0 3ffef52c 4020281c
3ffffe50:  3ffee680 00000d50 3ffe86fc 3ffe862b
3ffffe60:  000001bb 3ffffea0 3ffe87d5 3ffe862b
3ffffe70:  000001bb 3ffffea0 3ffe87d5 40203d29
3ffffe80:  40208078 54cac522 40208078 54cac522
3ffffe90:  3ffe84cc 3ffe84cc 3ffee6a0 40201150
3ffffea0:  40207f18 00000000 00003a98 feefeffe
3ffffeb0:  00000000 3ffef52c 3fff11bc 3ffef66c
3ffffec0:  00000000 00000000 3fff11bc 3fff62c4
3ffffed0:  3ffef75c 00000000 00000000 00000000
3ffffee0:  00000000 3fff1f14 3ffef57c 3fff6064
3ffffef0:  3ffef594 00000000 00000000 00000000
3fffff00:  00004145 00000255 feef0000 00000000
3fffff10:  00000000 00000000 00000000 00000000
3fffff20:  00000000 00000000 feef0000 feefeffe
3fffff30:  feefeffe feefeffe feefeffe fe00effe
3fffff40:  00000000 feefeffe 00000000 00000000
3fffff50:  feefef00 00000000 00000000 feefeffe
3fffff60:  feefeffe feefeffe feefeffe feefeffe
3fffff70:  feefeffe feefeffe feefeffe feefeffe
3fffff80:  feefeffe feefeffe feefeffe feefeffe
3fffff90:  feefeffe feefeffe feefeffe 3ffee728
3fffffa0:  3fffdad0 00000000 3ffee6e8 40205c24
3fffffb0:  feefeffe feefeffe 3ffe84f0 40100b85
<<<stack<<<

I have checked my api in localhost and it is working fine. There is a problem with interacting with secured website . Heroku uses sha256RSA Signature Algorithm and sha256 as signature hash .
Here is my code which I have deployed

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const char * ssid = "YOURNETWORK";
const char * password = "YOURPASSWORD";
const char * host = "api71.herokuapp.com";
String path = "/api/courses"; // Path of Server
const int httpsPort = 443; // HTTPS PORT (default: 443)
int refreshtime = 15; // Make new HTTPS request after x seconds

String datarx; // Received data as string
long crontimer;

void setup () {
  delay (1000);
  Serial.begin (115200);
  WiFi.mode (WIFI_OFF);
  delay (1000);
  WiFi.mode (WIFI_STA);
  WiFi.begin (ssid, password);
  Serial.print ("Connecting");
  while (WiFi.status ()! = WL_CONNECTED) {
    delay (500);
    Serial.print (".");
  }
  Serial.print ("Connected:");
  Serial.println (ssid);
}

void loop () {
  if (crontimer <millis () / 1000) {
    crontimer = (millis () / 1000) + refreshtime;
    callhttps (); //
  }
}

void callhttps () {
  WiFiClientSecure httpsClient;
  httpsClient.setTimeout (15000);
  delay (1000);
  int retry = 0;
  while ((! httpsClient.connect (host, httpsPort)) && (retry <15)) {
    delay (100);
    Serial.print (".");
    retry ++;
  }
  if (retry == 15) {
    Serial.println ("Connection failed");
  }
  else {
    Serial.println ("Connected to Server");
  }
  httpsClient.print (String ("GET") + path +
                    "HTTP / 1.1 \ r \ n" +
                    "Host:" + host +
                    "\ r \ n" + "Connection: close \ r \ n \ r \ n");
  while (httpsClient.connected ()) {
    String line = httpsClient.readStringUntil ('\ n');
    if (line == "\ r") {
      break;
    }
  }
  while (httpsClient.available ()) {
    datarx + = httpsClient.readStringUntil ('\ n');
  }
  Serial.println (datarx);
  datarx = "";
}

Is there any why to connect to this website ? Please help me .


问:
Clicking component inside renderHeader prop for MUI Data Grid Pro changes the sortModel
I'm using Material UI DataGridPro component to build a React Js app.

I want to create a custom filtering.

The red box in the image below is an IconButton for the filtering view and the blue box is for the column showing/hiding view.

I want to change the behavior of the custom filtering view.

If the filter icon is clicked, then the DataGridPro header will show some Select and TextField components as the filter fields like this image below.

If we click one of the Select and TextField components, the Data Grid Pro component will trigger the onSortModelChange prop to change the sortModel value like this image below.

So now the Data Grid Pro component is sorted based on the column.

Here is the conditions I want:
if we click one of the Select and TextField components inside the Data Grid Pro header, the Data Grid Pro will not trigger the onSortModelChange prop which means that the sortModel value is not changed

Here is the playground: https://codesandbox.io/s/stackoverflow-mui-data-grid-render-header-xmwf0?file=/src/App.js

I have tried to add sortable: false for every column but it will not show the arrow icon inside the Data Grid Pro header and prevent the column to be sorted. That's not what I want.

I also have added sortModel and onSortModelChange props for the Data Grid Pro component to control the sortModel value but it hasn't worked.

So, what's the solution for this case?

答:
The MUI X team told me from the Github issue here https://github.com/mui/mui-x/issues/3655#issuecomment-1015263995 that the solution is very simple.

Just add event.stopPropagation() for the onClick prop of each TextField and Select component.

onClick={(event) => event.stopPropagation()}
```


问:
Django REST framework - sumbit only fields?
I use a model serializer in my code and need to get extra field value in the PUT request. This is to identify the user intention on certain operations. I see there are read_only and write_only option in serialize fields. But I can't use those since I'm not going to store this additional field to the model (it don't have such field).

How can I achieve this in the serializer correct way?

```<code>djangorestframework version 3.13.1
</code>```

答:
Found the solution based on the @loki's comment.

Included the serializer field as follows since I use it for PUT method only.

```<code>delete_now = serializers.BooleanField(default=False, write_only=True)
</code>```

Body:
I use a model serializer in my code and need to get extra field value in the PUT request. This is to identify the user intention on certain operations. I see there are read_only and write_only option in serialize fields. But I can't use those since I'm not going to store this additional field to the model (it don't have such field).

How can I achieve this in the serializer correct way?

djangorestframework version 3.13.1

Body:
Found the solution based on the @loki's comment.

Included the serializer field as follows since I use it for PUT method only.

delete_now = serializers.BooleanField(default=False, write_only=True)


问:
How do I send request to server from a dynamic form using jquery
I am working on an inventory management system that involves sales of products

The form is dynamic

when a user click on add new product it sends to the server and get the price of the product

My HTML Code

```<code><form role="form" action="{{ url('admin/sales/store') }}" method="get">
    @csrf
    <div class="card-body">
        <div class="row">
            <div class="col-md-12">
            </div>
            <div class="col-md-12 right my-3">
                <a href="#" class="btn btn-danger" id="add-product">Add New Product</a>
            </div>
            <div id="wrapper" class="col-md-12">
                <div id="new-field" class="col-md-12">
                    <div class="row">

                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Product Name</label>
                                <select name="product[]" id="product" class="form-control">
                                    <option value="">Select Product Name</option>
                                    @foreach ($products as $product)
                                        <option value="{{ $product->id }}" name="product[]">
                                            {{ $product->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Quantity</label>
                                <input type="text" name="quantity[]" class="form-control"
                                    value="{{ old('quantity') }}"
                                    placeholder="Enter Quantity">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Unit Price</label>
                                <input type="text" name="price[]" disabled
                                    id="price"
                                    class="form-control"
                                    placeholder="Enter Quantity">
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <div class="card-footer">
        <button type="submit" class="btn btn-primary float-md-right">Add Sales</button>
    </div>
</form>
</code>```

JQUERY

```<code><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        $("#add-product").click(function(e) {
            e.preventDefault();
            $("#new-field").clone().appendTo("#wrapper");
        });
        $("#product").change(function(e) {
            e.preventDefault();
            axios.get("/ims/api/get-price/" + $(this).val())
                .then(function(response) {
                    $("#price").val(response.data.price);
                });
        })
</script>
</code>```

JSON

```<code>{
   price: 34000.42
}
</code>```

but it is only the first row that works

How can I make other rows to work?

答:
The issue is that you're using the id attribute to select your elements.

Initially, your product rows (simplified) look like this:

        ...
        <select name="product[]" id="product"></select>
        ...
        <input type="text" name="quantity[]" value="{{ old('quantity') }}" >
        ...
        <input type="text" name="price[]" disabled id="price">
        ...

```
<p>After the <code>#add-product</code> element is clicked, you clone the whole <code>#new-field</code> element, and append it to the <code>#wrapper</code> element with this code:</p>
<pre class="lang-js prettyprint-override"><code>$("#add-product").click(function(e) {
    e.preventDefault();
    $("#new-field").clone().appendTo("#wrapper");
});
</code>```

Then the simplified view of your product rows looks like this:

        ...
        <select name="product[]" id="product"></select>
        ...
        <input type="text" name="quantity[]" value="{{ old('quantity') }}" >
        ...
        <input type="text" name="price[]" disabled id="price">
        ...

        ...
        <select name="product[]" id="product"></select>
        ...
        <input type="text" name="quantity[]" value="{{ old('quantity') }}" >
        ...
        <input type="text" name="price[]" disabled id="price">
        ...

```
<p>Note particularly that you have doubled-up <code>id</code> attributes for <code>new-field</code>, <code>product</code> and <code>price</code>.</p>
<p><code>id</code> is supposed to be unique in HTML.</p>
<p>Then, when your price update code runs, it's always going to cause an issue. The HTML engine in your browser is ignoring all the duplicate <code>id</code> attributes:</p>
<pre class="lang-js prettyprint-override"><code>// This line tries to get the unique element with the id "product"
// after it's found it (i.e. the first element in the DOM), it stops
// so this line only selects the first element with an id of "product"
$("#product").change(function(e) {
    e.preventDefault();
    axios.get("/ims/api/get-price/" + $(this).val())
        .then(function(response) {

            // This line tries to get the unique element with the id
            // "price", after it finds the first one, it stops looking
            // so this will never select the duplicated elements.
            $("#price").val(response.data.price);

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

To fix it, you need to stop using id to select the product. Do something like this:

Change your id attributes on the #new-field, #product and #price elements to class:

    <select name="product[]" class="product"></select>
    ...
    <input type="text" name="price[]" disabled class="price">

```
<p>And modify your JS to select based on class:</p>
<pre class="lang-js prettyprint-override"><code>$(".wrapper").on('change', '.product', function(e) {
    e.preventDefault();
    axios.get("/ims/api/get-price/" + $(this).val())
        .then(function(response) {

            $(this).parent('.new-field').find('.price').val(response.data.price);

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

You'll also need to update your JavaScript to correctly add new products.

Body:
I am working on an inventory management system that involves sales of products

The form is dynamic

when a user click on add new product it sends to the server and get the price of the product

My HTML Code

<form role="form" action="{{ url('admin/sales/store') }}" method="get">
    @csrf

                Add New Product

                                Product Name
                                <select name="product[]" id="product" class="form-control">
                                    <option value="">Select Product Name</option>
                                    @foreach ($products as $product)
                                        <option value="{{ $product->id }}" name="product[]">
                                            {{ $product->name }}</option>
                                    @endforeach
                                </select>

                                Quantity
                                <input type="text" name="quantity[]" class="form-control"
                                    value="{{ old('quantity') }}"
                                    placeholder="Enter Quantity">

                                Unit Price
                                <input type="text" name="price[]" disabled
                                    id="price"
                                    class="form-control"
                                    placeholder="Enter Quantity">

        <button type="submit" class="btn btn-primary float-md-right">Add Sales</button>

</form>

JQUERY

JSON

{
   price: 34000.42
}

but it is only the first row that works

How can I make other rows to work?

Body:
The issue is that you're using the id attribute to select your elements.

Initially, your product rows (simplified) look like this:

<div id="wrapper">
    <div id="new-field">
        ...
        <select name="product[]" id="product"></select>
        ...
        <input type="text" name="quantity[]" value="{{ old('quantity') }}" >
        ...
        <input type="text" name="price[]" disabled id="price">
        ...
    </div>
</div>

After the #add-product element is clicked, you clone the whole #new-field element, and append it to the #wrapper element with this code:

$("#add-product").click(function(e) {
    e.preventDefault();
    $("#new-field").clone().appendTo("#wrapper");
});

Then the simplified view of your product rows looks like this:

<div id="wrapper">
    <div id="new-field">
        ...
        <select name="product[]" id="product"></select>
        ...
        <input type="text" name="quantity[]" value="{{ old('quantity') }}" >
        ...
        <input type="text" name="price[]" disabled id="price">
        ...
    </div>
    <div id="new-field">
        ...
        <select name="product[]" id="product"></select>
        ...
        <input type="text" name="quantity[]" value="{{ old('quantity') }}" >
        ...
        <input type="text" name="price[]" disabled id="price">
        ...
    </div>
</div>

Note particularly that you have doubled-up id attributes for new-field, product and price.

id is supposed to be unique in HTML.

Then, when your price update code runs, it's always going to cause an issue. The HTML engine in your browser is ignoring all the duplicate id attributes:

// This line tries to get the unique element with the id "product"
// after it's found it (i.e. the first element in the DOM), it stops
// so this line only selects the first element with an id of "product"
$("#product").change(function(e) {
    e.preventDefault();
    axios.get("/ims/api/get-price/" + $(this).val())
        .then(function(response) {

            // This line tries to get the unique element with the id
            // "price", after it finds the first one, it stops looking
            // so this will never select the duplicated elements.
            $("#price").val(response.data.price);

        });
})

To fix it, you need to stop using id to select the product. Do something like this:

Change your id attributes on the #new-field, #product and #price elements to class:

<div class="new-field">
    <select name="product[]" class="product"></select>
    ...
    <input type="text" name="price[]" disabled class="price">
</div>

And modify your JS to select based on class:

$(".wrapper").on('change', '.product', function(e) {
    e.preventDefault();
    axios.get("/ims/api/get-price/" + $(this).val())
        .then(function(response) {

            $(this).parent('.new-field').find('.price').val(response.data.price);

        });
})

You'll also need to update your JavaScript to correctly add new products.


问:
(SQL) Select rows only where a column's values are found in another column?
Is it possible to filter rows where one column only has values that match ones found in another column, but without using subselect?

Ex:

All rows

Selected rows

Filtered to only rows with column values that were referenced in the pointer column.

答:
Here You Go, using selg join:</p>
```<code>Create table #temp( name varchar(200), ColumnA int, PointerColumnB int)

Insert into #temp values('NAMEA',1,null),('NAMEB',2,3),
('NAMEC',3,3),('NAMED',4,null),('NAMEE',5,4),('NAMEF',6,7),('NAMEG',7,null)

Select distinct x.Name
from #temp x
join #temp y on x.ColumnA = y.PointerColumnB
</code>```

Body:
Here You Go, using selg join:

Create table #temp( name varchar(200), ColumnA int, PointerColumnB int)

Insert into #temp values('NAMEA',1,null),('NAMEB',2,3),
('NAMEC',3,3),('NAMED',4,null),('NAMEE',5,4),('NAMEF',6,7),('NAMEG',7,null)

Select distinct x.Name
from #temp x
join #temp y on x.ColumnA = y.PointerColumnB


问:
Using Google Fonts with SVG <object>
I'm embedding SVGs in my page with the <object> tag, and they're supposed to utilize Google Fonts (e.g. Roboto). However, the SVGs aren't picking these fonts up and instead default to system fonts.

What am I doing wrong? Does every SVG require that the font itself be embedded in

答:
Kyle's answer is awesome, but didn't quite work for me, but it lead me to the right answer:

You can define the font as local if you already have it on the page

@font-face {
  font-family: 'Bitter';
  src: local('Bitter');
}
```

I'm making a website where I'm already using certain fonts and couldn't get them to load, but ideally I wouldn't even have to anyway since they're already loaded. This solution worked perfectly for me.

Title: Using Google Fonts with SVG <object>

Body:
Kyle's answer is awesome, but didn't quite work for me, but it lead me to the right answer:

You can define the font as local if you already have it on the page

@font-face {
  font-family: 'Bitter';
  src: local('Bitter');
}

I'm making a website where I'm already using certain fonts and couldn't get them to load, but ideally I wouldn't even have to anyway since they're already loaded. This solution worked perfectly for me.


问:
Angular 6 HostBinding with multiple values?
I have successfully used @HostBinding in my Angular 6 app to apply properties to the host component, as in applying a class when a variable is true:

@HostBinding('class.compact-ui') isCompact;

Now, however, I need to assign one of 4 possible classes based on the model of a select menu. For example, user can red, blue, or green.

I suppose I can use multiple host bindings for when any of the colors are true:

@HostBinding('class.green-ui') uiColor === 'green';

But that seems wrong. What's the proper way to do this?

答:
You can do it with style too:</p>
```<code>@HostBinding('style')
get style_binding()
{
    return {
        display: 'grid',
        gap: this.config.internalGap,
        margin: this.config.margin,
        gridArea: this.config.area
    };
}
</code>```

Body:
You can do it with style too:

@HostBinding('style')
get style_binding()
{
    return {
        display: 'grid',
        gap: this.config.internalGap,
        margin: this.config.margin,
        gridArea: this.config.area
    };
}


问:
docker postgres pgadmin local connection
I have created an ubuntu image with nginx, php and postgres.

I want to connect the postgres database in my current image with pgadmin located on my local machine.

I have tried using docker inspector to try to use the image ip to make a connection with my local pgadmin but without much success. I've also tried configuring some ports on local to make connection work.

答:
I ran this, It worked for me</p>
```<code>docker pull dpage/pgadmin4
docker run -p 9000:80 -e 'PGADMIN_DEFAULT_EMAIL=test@gmail.com' -e 'PGADMIN_DEFAULT_PASSWORD=root' -d dpage/pgadmin4
</code>```

Body:
I ran this, It worked for me

docker pull dpage/pgadmin4
docker run -p 9000:80 -e 'PGADMIN_DEFAULT_EMAIL=test@gmail.com' -e 'PGADMIN_DEFAULT_PASSWORD=root' -d dpage/pgadmin4


问:
Uncaught Type error while using C on Atom IDE
So I have only used atom for Python until now but I tried running C code on it and its showing at RHS of the screen with a red message
Uncaught TypeError: Cannot read property 'replace' of undefined
I have my editor set at C language so there is no problem with that.Is it the problem with the script package?

答:
If you are having problem in Atom editor for "C language" as- "uncaught type error"
then try these things-

Save the atom file with .c extension else it won't work for c program.

Check whether you have installed "gpp-compiler".

Though if the program doesn't work then, check whether your program is correct.


问:
npm not working on windows - Error: Cannot find module 'emoji-regex'
I was trying to update the version of npm and I don't know what went wrong but since then no command of npm is working (globally as well as inside any folder). I can't do npm install, or even npm -v I have tried uninstalling and installing node, updating node versions, using previous versions but nothing works. It gives me the following error:

```<code> node:internal/modules/cjs/loader:933
  const err = new Error(message);
              ^

Error: Cannot find module 'emoji-regex'
Require stack:
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\node_modules\string-width\index.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\wide-truncate.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\render-template.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\plumbing.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\index.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\npmlog\lib\log.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\lib\utils\log-shim.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\lib\utils\exit-handler.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\lib\cli.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js
←[90m    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:778:27)←[39m
←[90m    at Module.require (node:internal/modules/cjs/loader:1005:19)←[39m
←[90m    at require (node:internal/modules/cjs/helpers:102:18)←[39m
    at Object.<anonymous> (C:\Users\nihal\AppData\Roaming\npm\node_modules\←[4mnpm←[24m\node_modules\←[4mgauge←[24m\node_modules\←[4mstring-width←[24m\index.js:4:20)
←[90m    at Module._compile (node:internal/modules/cjs/loader:1103:14)←[39m
←[90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m    at Module.require (node:internal/modules/cjs/loader:1005:19)←[39m {
  code: ←[32m'MODULE_NOT_FOUND'←[39m,
  requireStack: [
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\node_modules\\string-width\\index.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\wide-truncate.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\render-template.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\plumbing.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\index.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\npmlog\\lib\\log.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\lib\\utils\\log-shim.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\lib\\utils\\exit-handler.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\lib\\cli.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js'←[39m
  ]
}
</code>```

I tried where node and where npm and they give these results respectively:

```<code>C:\Program Files\nodejs\node.exe

C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd
C:\Users\nihal\AppData\Roaming\npm\npm
C:\Users\nihal\AppData\Roaming\npm\npm.cmd
</code>```

Any help is appreciated. Thanks!

答:
So after several trial and errors, I was finally able to solve this. These where the steps I followed:

Use where node and where npm to know their locations.

Uninstall Nodejs

Manually delete all the folders which I found in step 1 (If they are still there. For me, they were).

Install latest Nodejs

Now everything works.
Thanks!

Body:
I was trying to update the version of npm and I don't know what went wrong but since then no command of npm is working (globally as well as inside any folder). I can't do npm install, or even npm -v I have tried uninstalling and installing node, updating node versions, using previous versions but nothing works. It gives me the following error:

 node:internal/modules/cjs/loader:933
  const err = new Error(message);
              ^

Error: Cannot find module 'emoji-regex'
Require stack:
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\node_modules\string-width\index.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\wide-truncate.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\render-template.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\plumbing.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\gauge\lib\index.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\node_modules\npmlog\lib\log.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\lib\utils\log-shim.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\lib\utils\exit-handler.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\lib\cli.js
- C:\Users\nihal\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js
←[90m    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:778:27)←[39m
←[90m    at Module.require (node:internal/modules/cjs/loader:1005:19)←[39m
←[90m    at require (node:internal/modules/cjs/helpers:102:18)←[39m
    at Object.<anonymous> (C:\Users\nihal\AppData\Roaming\npm\node_modules\←[4mnpm←[24m\node_modules\←[4mgauge←[24m\node_modules\←[4mstring-width←[24m\index.js:4:20)
←[90m    at Module._compile (node:internal/modules/cjs/loader:1103:14)←[39m
←[90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m    at Module.require (node:internal/modules/cjs/loader:1005:19)←[39m {
  code: ←[32m'MODULE_NOT_FOUND'←[39m,
  requireStack: [
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\node_modules\\string-width\\index.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\wide-truncate.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\render-template.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\plumbing.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\gauge\\lib\\index.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\npmlog\\lib\\log.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\lib\\utils\\log-shim.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\lib\\utils\\exit-handler.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\lib\\cli.js'←[39m,
    ←[32m'C:\\Users\\nihal\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js'←[39m
  ]
}

I tried where node and where npm and they give these results respectively:

C:\Program Files\nodejs\node.exe

C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd
C:\Users\nihal\AppData\Roaming\npm\npm
C:\Users\nihal\AppData\Roaming\npm\npm.cmd

Any help is appreciated. Thanks!


问:
How to use Azure App Services domain for Static Web Apps?
I have an Azure App Services instance, which by default goes to https://myappservice.azurewebsites.net (not actually mine, but it's the same format). It's not a bad domain and a lot better than the sporadic randomized domains from Static Web Apps (https://lively-tree-randomletters.azurestaticapps.net).

Is there any way to switch the serverless website running on static web apps to also use the https://myappservice.azurewebsites.net domain?

Or is the only possible solution for hosting (1) react and (2) spring boot on the same domain, to buy one? Or this isn't possible at all?

(I want them to be on the same domain so I don't need to worry about CORS)

答:
I think you could pull this off by using an Application Gateway. With the Application Gateway you can set up path-based rules so that you've got both your app service and your static website, but say yoursite.com/sprintBoot will be routed to your App Service and everything else on yoursite.com, to your static website.

See this article as an example: Create an application gateway with path-based routing rules using the Azure portal

Though it is up for debate if this is easier than worrying about CORS.


问:
Where am I missing a key prop here? I'm generating uuids for TableCell keys and I'm using row.id for the row keys
I have this bit of code where I'm getting the warning:

Each child in a list should have a unique "key" prop. Check the render
method of AllPersonnel... at TableRow

And the table cells are not rendering. Any help would be appreciated. Thanks!

```<code>       <TableContainer component={Paper}>
            <Table>
              <TableHead>
                <TableRow key={uuidv4()}>
                  {cols.map((col) => {
                    return <TableCell key={col.path}>{col.name}</TableCell>
                  })}
                </TableRow>
              </TableHead>

              <TableBody>

                {personnel.map((row, i) => {
                  return (

                    <TableRow key={row.id}>
                      <TableCell key={uuidv4()}>{row.first_name}</TableCell>
                      <TableCell key={uuidv4()}>{row.last_name}</TableCell>
                      <TableCell key={uuidv4()}>{row.section}</TableCell>
                      <TableCell key={uuidv4()}>{row.role}</TableCell>
                      <TableCell key={uuidv4()}>{row.employee_type}</TableCell>
                    </TableRow>

                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
</code>```

答:
You don't need a key on your TableRow, only on the first child in the return of an iterator.
Try :

```<code>{personnel.map((row, i) => {
    const key = uuidv4()
              return (
                <TableRow key={key}>
                  <TableCell>{row.first_name}</TableCell>
                ...
</code>```

Normaly...

Body:
I have this bit of code where I'm getting the warning:

Each child in a list should have a unique "key" prop. Check the render
method of AllPersonnel... at TableRow

And the table cells are not rendering. Any help would be appreciated. Thanks!

       <TableContainer component={Paper}>

              <TableHead>
                <TableRow key={uuidv4()}>
                  {cols.map((col) => {
                    return <TableCell key={col.path}>{col.name}</TableCell>
                  })}
                </TableRow>
              </TableHead>

              <TableBody>

                {personnel.map((row, i) => {
                  return (

                    <TableRow key={row.id}>
                      <TableCell key={uuidv4()}>{row.first_name}</TableCell>
                      <TableCell key={uuidv4()}>{row.last_name}</TableCell>
                      <TableCell key={uuidv4()}>{row.section}</TableCell>
                      <TableCell key={uuidv4()}>{row.role}</TableCell>
                      <TableCell key={uuidv4()}>{row.employee_type}</TableCell>
                    </TableRow>

                  );
                })}
              </TableBody>

          </TableContainer>

Body:
You don't need a key on your TableRow, only on the first child in the return of an iterator.
Try :

{personnel.map((row, i) => {
    const key = uuidv4()
              return (
                <TableRow key={key}>
                  <TableCell>{row.first_name}</TableCell>
                ...

Normaly...


问:
What PHP function(s) should I use to cut off the end of a string?
I have a filename stored with the directory as a value.

Ex. /var/www/remove_this.php

In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.

There are so many string editing functions, I don't know a good approach. Thanks!

答: dirname() will return you the directory part of the path</p>


问:
How do I fix a npm WARN lifecycle error from Namecheap?
This is the error I'm getting when I run NPM install in Namecheap Cpanel:

```<code>Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.
</code>```

I tried adding a file at the root folder of the app, called .npmrc, place this line into it:

scripts-prepend-node-path=true

but that didn't work.
Any ideas on how to resolve this?

答: I had to install my modules manually through Namecheaps terminal/ssh.</p>

Body:
This is the error I'm getting when I run NPM install in Namecheap Cpanel:

Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

I tried adding a file at the root folder of the app, called .npmrc, place this line into it:

scripts-prepend-node-path=true

but that didn't work.
Any ideas on how to resolve this?


问:
Regex to select all spaces between a special enclosure
I am trying to write a regex for Javascript that can select all whitespaces in between AMPScript brackets, the syntax for the Lang is something like this

%%[

set @truth = 'this is amp'

IF @truth == 'this is amp' THEN
set @response = 'amp rocks'
ELSE
set @response = '...'
ENDIF

]%%```
</div>
</div>
</p>
<p>So far, I am able to select all the characters inside the given brackets using this expression:</p>
```%%\[(\s|.)*?\]%%
```

But this selects all the characters inside the enclosure, is there a method I can use to only select spaces/new lines/tabindents only?

Thanks in advance!

答:
I believe this is what you want:

```<code>(?<=%%\[(\s|.)*)\s*(?=(\s|.)*\]%%)
</code>```

https://regex101.com/r/EWhbuX/1

Edit

Here's a breakdown of the regular expression:

1.

First we start with a Positive Lookbehind (?<=   )

This will make sure that the pattern that's following this, will be preceded by the pattern inside, but will not be include it in the matches.

In this case we want our matching pattern to be preceded by %%[ and any other character %%\[(\s|.)*

So, our resulting code for the Positive Lookbehind is

```<code>(?<=%%\[(\s|.)*)
</code>```

2.

Next comes the pattern that we actually want to match after our Lookabehind, and (spoiler alert), before a Lookahead that we'll define later.

In this case, that's just any whitespace character, so our pattern will be

```<code>\s
</code>```

(Yes, I just noticed that we don't even need the * in my original answer)

3.

Similarly to what we did at the beginning of the expression with the Lookbehind, we now need a Positive Lookahead (?=   )

This is to make sure that our whitespaces will be  followed by any character and ]%% (\s|.)*\]%%.

So this is our resulting Lookahead:

```<code>(?=(\s|.)*\]%%)
</code>```

4.

Put everything together and you have your regular expression!

```<code>(?<=%%\[(\s|.)*)\s(?=(\s|.)*\]%%)
</code>```

Body:
I am trying to write a regex for Javascript that can select all whitespaces in between AMPScript brackets, the syntax for the Lang is something like this

%%[

set @truth = 'this is amp'

IF @truth == 'this is amp' THEN
set @response = 'amp rocks'
ELSE
set @response = '...'
ENDIF

]%%

So far, I am able to select all the characters inside the given brackets using this expression:

%%\[(\s|.)*?\]%%

But this selects all the characters inside the enclosure, is there a method I can use to only select spaces/new lines/tabindents only?

Thanks in advance!

Body:
I believe this is what you want:

(?<=%%\[(\s|.)*)\s*(?=(\s|.)*\]%%)

https://regex101.com/r/EWhbuX/1

Edit

Here's a breakdown of the regular expression:

1.

First we start with a Positive Lookbehind (?<=   )

This will make sure that the pattern that's following this, will be preceded by the pattern inside, but will not be include it in the matches.

In this case we want our matching pattern to be preceded by %%[ and any other character %%\[(\s|.)*

So, our resulting code for the Positive Lookbehind is

(?<=%%\[(\s|.)*)

2.

Next comes the pattern that we actually want to match after our Lookabehind, and (spoiler alert), before a Lookahead that we'll define later.

In this case, that's just any whitespace character, so our pattern will be

\s

(Yes, I just noticed that we don't even need the * in my original answer)

3.

Similarly to what we did at the beginning of the expression with the Lookbehind, we now need a Positive Lookahead (?=   )

This is to make sure that our whitespaces will be  followed by any character and ]%% (\s|.)*\]%%.

So this is our resulting Lookahead:

(?=(\s|.)*\]%%)

4.

Put everything together and you have your regular expression!

(?<=%%\[(\s|.)*)\s(?=(\s|.)*\]%%)


问:
c++ heuristic for estimating function inlining benefits
In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may be ultimately beyond my control, I am still curious.</p>

答:
All inlining saves you is the entry/exit cost of the function, so it's only worth considering if the function does almost nothing.
Certainly if the function itself contains a function call, it's probably not worth considering.

Even if the function does very little, it has to be called so much that it owns the program counter a significant percent of the time, before any speedup of the function would be noticeable.


问:
Screenshotting the windows desktop when working through WSL
I'm primarily using Windows, where I run WSL2. So from a python script running in the subsystem, I would like to screenshot whatever is on windows monitor, as simple as such:

v1

```<code>import mss
import os

os.environ['DISPLAY'] = ':0'

with mss.mss() as sct:
    sct.shot()

</code>```

This gives only gives "Segmentation fault" error and no image. So I tried to setup vcxsrv in Windows and I'm able to open stuff from my subsystem in Windows through the server, however I cant get it the other way around..

I just want access to the windows screen so I can screenshot it. Any help about how to access the monitor through wsl would be greatly appreciated, I can't find much on google..

答:
The problem with your attempted solution is that the WSL/Linux Python's mss, as you've found, isn't able to capture the Windows desktop.  Being the Linux version of MSS, it will only be able to communicate with Linux processes and protocols like X.  Starting up VcXsrv might get you part of the way there, in that you might be able to capture X output, but you may need to be running the Python app from inside a terminal that is running in a X window.

Regardless, you've said that your goal is to capture the entire Windows desktop, not just the X output in VcXsrv.  To do that, you'll need to use a Windows process of some sort.

But don't worry; using WSL's interop, you can still do that from inside WSL/Linux Python.  We just need to call out to a Windows .exe of some sort.

There are literally dozens of third-party apps that you could use in Windows to create a screenshot.  But I prefer to use a solution that doesn't require any additional installation.

So I resorted to PowerShell for this, since you can easily call powershell.exe and pass in a script from WSL.  There are a number of examples here on Stack Overflow, but I ended up going slightly "lower tech" to try to simplify a bit.  The code here is most similar to this solution, so refer to that if you want to expand on this.

From WSL/Linux Python:

```<code>import os
os.system("""
    powershell.exe \"
        Add-Type -AssemblyName System.Windows.Forms
        [Windows.Forms.Sendkeys]::SendWait('+{Prtsc}')
        \$img = [Windows.Forms.Clipboard]::GetImage()
        \$img.Save(\\\"\$env:USERPROFILE\\Pictures\\Screenshots\\screenshot.jpg\\\", [Drawing.Imaging.ImageFormat]::Jpeg)\"
""")
</code>```

That essentially sends the ShiftPrintScreen key chord to capture the current desktop to the clipboard, then saves the clipboard.  It can get slightly hairy with the quoting, since you are essentially wrapping PowerShell inside a /bin/sh inside a Python script.

Note that, even though you are in Linux Python, since it's the Windows PowerShell that we are calling, it takes the Windows path format (C:\Users\Username\Pictures...) rather than the Linux version (/mnt/c/Users/...).

While I didn't have any timing issues with this, you may need to insert small delays.  Again, refer to the existing answer for that.  This solution is primarily to explain how to do it through WSL's Python using PowerShell.

Body:
I'm primarily using Windows, where I run WSL2. So from a python script running in the subsystem, I would like to screenshot whatever is on windows monitor, as simple as such:

v1

import mss
import os

os.environ['DISPLAY'] = ':0'

with mss.mss() as sct:
    sct.shot()

This gives only gives "Segmentation fault" error and no image. So I tried to setup vcxsrv in Windows and I'm able to open stuff from my subsystem in Windows through the server, however I cant get it the other way around..

I just want access to the windows screen so I can screenshot it. Any help about how to access the monitor through wsl would be greatly appreciated, I can't find much on google..

Body:
The problem with your attempted solution is that the WSL/Linux Python's mss, as you've found, isn't able to capture the Windows desktop.  Being the Linux version of MSS, it will only be able to communicate with Linux processes and protocols like X.  Starting up VcXsrv might get you part of the way there, in that you might be able to capture X output, but you may need to be running the Python app from inside a terminal that is running in a X window.

Regardless, you've said that your goal is to capture the entire Windows desktop, not just the X output in VcXsrv.  To do that, you'll need to use a Windows process of some sort.

But don't worry; using WSL's interop, you can still do that from inside WSL/Linux Python.  We just need to call out to a Windows .exe of some sort.

There are literally dozens of third-party apps that you could use in Windows to create a screenshot.  But I prefer to use a solution that doesn't require any additional installation.

So I resorted to PowerShell for this, since you can easily call powershell.exe and pass in a script from WSL.  There are a number of examples here on Stack Overflow, but I ended up going slightly "lower tech" to try to simplify a bit.  The code here is most similar to this solution, so refer to that if you want to expand on this.

From WSL/Linux Python:

import os
os.system("""
    powershell.exe \"
        Add-Type -AssemblyName System.Windows.Forms
        [Windows.Forms.Sendkeys]::SendWait('+{Prtsc}')
        \$img = [Windows.Forms.Clipboard]::GetImage()
        \$img.Save(\\\"\$env:USERPROFILE\\Pictures\\Screenshots\\screenshot.jpg\\\", [Drawing.Imaging.ImageFormat]::Jpeg)\"
""")

That essentially sends the ShiftPrintScreen key chord to capture the current desktop to the clipboard, then saves the clipboard.  It can get slightly hairy with the quoting, since you are essentially wrapping PowerShell inside a /bin/sh inside a Python script.

Note that, even though you are in Linux Python, since it's the Windows PowerShell that we are calling, it takes the Windows path format (C:\Users\Username\Pictures...) rather than the Linux version (/mnt/c/Users/...).

While I didn't have any timing issues with this, you may need to insert small delays.  Again, refer to the existing answer for that.  This solution is primarily to explain how to do it through WSL's Python using PowerShell.


问:
Formatting Large Text File with Python
I am looking for a way to read a data from a text file with various headers and reformat the data. The each line of data consists of XYZ coordinates with an associated value for that particular coordinate as shown below:

```<code>    Header 1...
    Header 2...
         X1 Y1 Z1 Value1
         X2 Y2 Z2 Value2
         etc...
</code>```

what I am wanting to do is reformat the data in a manner that can be read by another program such as:

```<code>    Header 1...
    Header 2...
         X1 Y1 Z1
         X2 Y2 Z2
         etc...
    essentially a comment/header...
         Value1
         Value2
         etc...**
</code>```

I am just looking for some direction on how to start tackling this problem. The text files I am looking to edit range in size from several thousand lines to very large files with 100,000,000+ lines of data. So it would not matter to me if the script takes a while to run because you can imagine the time it would take to edit a file that size by hand!

答:
Here's my idea:

You can use a variable to store the current header. And for each line within that header, use string.split() function to seperate (X, Y, Z) and the value after the coordinates. Use a list of tuples to store that XYZ and the values after the XYZ can be stored in a seperated list.

Then you can loop through the data you've collected, write the headers first, and then join the X, Y, Z together using string.join() and add a tab to the beginning.

Title: Formatting Large Text File with Python

Body:
I am looking for a way to read a data from a text file with various headers and reformat the data. The each line of data consists of XYZ coordinates with an associated value for that particular coordinate as shown below:

    Header 1...
    Header 2...
         X1 Y1 Z1 Value1
         X2 Y2 Z2 Value2
         etc...

what I am wanting to do is reformat the data in a manner that can be read by another program such as:

    Header 1...
    Header 2...
         X1 Y1 Z1
         X2 Y2 Z2
         etc...
    essentially a comment/header...
         Value1
         Value2
         etc...**

I am just looking for some direction on how to start tackling this problem. The text files I am looking to edit range in size from several thousand lines to very large files with 100,000,000+ lines of data. So it would not matter to me if the script takes a while to run because you can imagine the time it would take to edit a file that size by hand!


问:
Cant use proxy on python request
I have three versions that i tested: 3.10.2, 3.9.9 and 3.8.10 on different machines and even one online compiler. In all of them i did the following:

```<code>import requests
requests.get(url, proxies=proxies, headers=headers)
</code>```

Testing in each parameter:
url:

```<code>"https://www.icanhazip.com"
"http://www.icanhazip.com"
</code>```

proxies:

```<code>{"https": "223.241.0.250:3000", "http": "223.241.0.250:3000"}
{"https": "223.241.0.250:3000", "http": "223.241.0.250:3000"}
</code>```

headers:

```<code>{'User-Agent': 'Chrome'}
{"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}
</code>```

In all of them but the 3.10.2 I got this error:

```<code>ProxyError: HTTPSConnectionPool(host='www.icanhazip.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConn
ectionError('<urllib3.connection.HTTPSConnection object at 0x05694F40>: Failed to establish a new connection: [WinError 10060] A connection attempt failed beca
use the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond')))
</code>```

On the 3.10.2 i got:

```<code>InvalidURL: Proxy URL had no scheme, should start with http:// or https://
</code>```

But when i tried to put the proxies like this:
{"https": "223.241.0.250:3000", "http": "223.241.0.250:3000"}
It didnt work and it just showed my normal ip.

What am I missing? A normal requests works just fine but when I add the proxies it just doesnt work. This code was working fine a while back and now outputs this error I cant figure out why.

Title: Cant use proxy on python request

Body:
I have three versions that i tested: 3.10.2, 3.9.9 and 3.8.10 on different machines and even one online compiler. In all of them i did the following:

import requests
requests.get(url, proxies=proxies, headers=headers)

Testing in each parameter:
url:

"https://www.icanhazip.com"
"http://www.icanhazip.com"

proxies:

{"https": "223.241.0.250:3000", "http": "223.241.0.250:3000"}
{"https": "223.241.0.250:3000", "http": "223.241.0.250:3000"}

headers:

{'User-Agent': 'Chrome'}
{"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}

In all of them but the 3.10.2 I got this error:

ProxyError: HTTPSConnectionPool(host='www.icanhazip.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConn
ectionError('<urllib3.connection.HTTPSConnection object at 0x05694F40>: Failed to establish a new connection: [WinError 10060] A connection attempt failed beca
use the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond')))

On the 3.10.2 i got:

InvalidURL: Proxy URL had no scheme, should start with http:// or https://

But when i tried to put the proxies like this:
{"https": "223.241.0.250:3000", "http": "223.241.0.250:3000"}
It didnt work and it just showed my normal ip.

What am I missing? A normal requests works just fine but when I add the proxies it just doesnt work. This code was working fine a while back and now outputs this error I cant figure out why.

Body:
Try adding a scheme in the proxy address

{"https": "http://223.241.0.250:3000", "http": "http://223.241.0.250:3000"}
{"https": "http://223.241.0.250:3000", "http": "http://223.241.0.250:3000"}