问:
How to edit string in .ini file with user input VBScript
I have .ini file and I need to edit one line of that with user input

```<code>##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%
</code>```

In this .ini file I need to change the

```<code>PlayerName = SoulFlyers
</code>```

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

```<code>    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************
</code>```

but it adds lines to .ini files.

How can I solve it?

Thanks.

答:
This function WriteReadIni can be used easily for reading and writing from an INI file :

Here is the English Version :

```<code>Option Explicit
Dim Title,fso,oFile,PlayerName,NewPlayerName
Title = "Read and Write from INI file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("Settings.ini")

PlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) 'For reading only
MsgBox "The content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title
Do
    PlayerName = inputbox("Please enter your name")
Loop Until PlayerName <> ""

NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName",PlayerName) ' Writing the new variable to ini file
NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) ' Reading the new variable

MsgBox "The New content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & NewPlayerName, vbInformation,Title

'-----------------------------------------------------------------------------------------------------------------------
Function WriteReadIni(oFile,section,key,value)
'-----------------------------------------------------------------------------------------------------------------------
' omen999 - mars 2018 v 1.1 - http://omen999.developpez.com/
' writes / reads the <key> of the <section> section of the oFile file object with the value <value> if read: value = Null
' In writing if the section and / or the key do not exist, they will be created
' In writing returns false if the key / value pair already existed if not true
' In read returns either: the key value, an empty string in the case of an empty key or False if the key does not exist
'-----------------------------------------------------------------------------------------------------------------------
Dim oText,iniText,sectText,newSectText,keyText,reg,regSub
  ' Initialization of regex objects
  ' Can be moved in the main code in case of successive calls
  Set reg = New RegExp
  Set regSub = New RegExp
  reg.MultiLine=True 'simplifie le pattern
  reg.IgnoreCase = True
  regSub.IgnoreCase = True
  Set oText = oFile.OpenAsTextStream(1,0)
  iniText = oText.ReadAll
  oText.Close
  reg.Pattern = "^\[" & section & "\]((.|\n[^\[])+)"
  regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
  On Error Resume Next
  If IsNull(value) Then   ' key reading
    WriteReadIni = regSub.Execute(reg.Execute(iniText).Item(0).SubMatches(0)).Item(0).SubMatches(0)
    If Err.Number = 5 then WriteReadIni = False
  Else                                              ' key writing
    sectText = reg.Execute(iniText).Item(0).SubMatches(0)
    If Err.Number = 5 Then ' Unknown section
      iniText = iniText & vbCrLf & "[" & section & "]" & vbCrLf & key & "=" & value
    Else
      newSectText = regSub.Replace(sectText,key & "=" & value)
      If newSectText = sectText Then ' No replacement noted. either the key / value already exists or it is a new key
        If regSub.Test(sectText) Then ' The key / value pair already exists -> Exit Function
          WriteReadIni = False
          Exit Function
        End If
        If Right(sectText,1) = vbCr Then keyText = key & "=" & value Else keyText = vbCrLf & key & "=" & value
        newSectText = sectText & keyText
      End If
      iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
    End If
    Set oText = oFile.OpenAsTextStream(2,0)
    oText.Write iniText
    oText.Close
    WriteReadIni = True
  End If
End Function
'-----------------------------------------------------------------------------------------------------------------------
</code>```

Body:
I have .ini file and I need to edit one line of that with user input

##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%

In this .ini file I need to change the

PlayerName = SoulFlyers

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************

but it adds lines to .ini files.

How can I solve it?

Thanks.

Body:
This function WriteReadIni can be used easily for reading and writing from an INI file :

Here is the English Version :

Option Explicit
Dim Title,fso,oFile,PlayerName,NewPlayerName
Title = "Read and Write from INI file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("Settings.ini")

PlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) 'For reading only
MsgBox "The content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title
Do
    PlayerName = inputbox("Please enter your name")
Loop Until PlayerName <> ""

NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName",PlayerName) ' Writing the new variable to ini file
NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) ' Reading the new variable

MsgBox "The New content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & NewPlayerName, vbInformation,Title

'-----------------------------------------------------------------------------------------------------------------------
Function WriteReadIni(oFile,section,key,value)
'-----------------------------------------------------------------------------------------------------------------------
' omen999 - mars 2018 v 1.1 - http://omen999.developpez.com/
' writes / reads the <key> of the <section> section of the oFile file object with the value <value> if read: value = Null
' In writing if the section and / or the key do not exist, they will be created
' In writing returns false if the key / value pair already existed if not true
' In read returns either: the key value, an empty string in the case of an empty key or False if the key does not exist
'-----------------------------------------------------------------------------------------------------------------------
Dim oText,iniText,sectText,newSectText,keyText,reg,regSub
  ' Initialization of regex objects
  ' Can be moved in the main code in case of successive calls
  Set reg = New RegExp
  Set regSub = New RegExp
  reg.MultiLine=True 'simplifie le pattern
  reg.IgnoreCase = True
  regSub.IgnoreCase = True
  Set oText = oFile.OpenAsTextStream(1,0)
  iniText = oText.ReadAll
  oText.Close
  reg.Pattern = "^\[" & section & "\]((.|\n[^\[])+)"
  regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
  On Error Resume Next
  If IsNull(value) Then   ' key reading
    WriteReadIni = regSub.Execute(reg.Execute(iniText).Item(0).SubMatches(0)).Item(0).SubMatches(0)
    If Err.Number = 5 then WriteReadIni = False
  Else                                              ' key writing
    sectText = reg.Execute(iniText).Item(0).SubMatches(0)
    If Err.Number = 5 Then ' Unknown section
      iniText = iniText & vbCrLf & "[" & section & "]" & vbCrLf & key & "=" & value
    Else
      newSectText = regSub.Replace(sectText,key & "=" & value)
      If newSectText = sectText Then ' No replacement noted. either the key / value already exists or it is a new key
        If regSub.Test(sectText) Then ' The key / value pair already exists -> Exit Function
          WriteReadIni = False
          Exit Function
        End If
        If Right(sectText,1) = vbCr Then keyText = key & "=" & value Else keyText = vbCrLf & key & "=" & value
        newSectText = sectText & keyText
      End If
      iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
    End If
    Set oText = oFile.OpenAsTextStream(2,0)
    oText.Write iniText
    oText.Close
    WriteReadIni = True
  End If
End Function
'-----------------------------------------------------------------------------------------------------------------------


来源: stackexchange

问:
Compiling C++ program on Windows XP
I have a problem running a simple Hello-world program in C++ on my Windows XP. I have written a post here:

Using the g++ C++ compiler from cygwin

where I stated the problem and I received many helpful replies, which solved some things. However, I still cannot run my hello-world program. Please, have a look at the post, I have included the program there. A friend of mine is able to run this program on his machine without problems. So, the problem should be in my system or libraries or something else, but I cannot figure what. In the "Edited" section of my post, I have included what error messages exactly I get.

Here is what I receive when I try to compile the program like this:

g++ hello.cpp

From the cygwin shell:

When I try g++ hello.cpp, I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

And here is what I get when I try to compile the program (again with g++ hello.cpp) from the DOS command prompt:

When I try g++ hello.cpp, I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

答: It looks like you have somehow got an illegal character in your code. Did you type the code in yourself or copy & paste it? If the latter, the source you copied from may be suspect in some way - type the code into the editor yourself, save it and recompile.</p>

ContentLicense: CC BY-SA 2.5

Title: Compiling C++ program on Windows XP

Body:
I have a problem running a simple Hello-world program in C++ on my Windows XP. I have written a post here:

Using the g++ C++ compiler from cygwin

where I stated the problem and I received many helpful replies, which solved some things. However, I still cannot run my hello-world program. Please, have a look at the post, I have included the program there. A friend of mine is able to run this program on his machine without problems. So, the problem should be in my system or libraries or something else, but I cannot figure what. In the "Edited" section of my post, I have included what error messages exactly I get.

Here is what I receive when I try to compile the program like this:

g++ hello.cpp

From the cygwin shell:

When I try g++ hello.cpp, I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

And here is what I get when I try to compile the program (again with g++ hello.cpp) from the DOS command prompt:

When I try g++ hello.cpp, I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

LastEditorDisplayName: Rich B

OwnerDisplayName: anon


问:
How do I force a 24 hour format on all time values?
Is there a locale (or any other code) that will force all my formating and my uiDatePicker to always be in English and 24 hour format?
I need this regardless of what the device settings are.
many thanks...</p>

答:
For the UIDatePicker, there isn't a way within the SDK to make the component 24 hour (aside from the user selecting a locale in Settings.app which uses 24 hour times). What you'll need to do is roll your own using a UIPickerView and a custom data source, which is really quite simple, and then convert the values there into an NSDate using simple arithmetic.

For the time formatting, you can always choose what format you want to display NSDate objects by using a NSDateFormatter like the following:

```<code>NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSLog(@"the current 24hr date and time is %@", [formatter stringFromDate:[NSDate date]]);
[formatter release];
</code>```

You can then wrap this into Utils class or what have you, and use it globally to format your dates into strings.

ContentLicense: CC BY-SA 3.0

Body:
For the UIDatePicker, there isn't a way within the SDK to make the component 24 hour (aside from the user selecting a locale in Settings.app which uses 24 hour times). What you'll need to do is roll your own using a UIPickerView and a custom data source, which is really quite simple, and then convert the values there into an NSDate using simple arithmetic.

For the time formatting, you can always choose what format you want to display NSDate objects by using a NSDateFormatter like the following:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSLog(@"the current 24hr date and time is %@", [formatter stringFromDate:[NSDate date]]);
[formatter release];

You can then wrap this into Utils class or what have you, and use it globally to format your dates into strings.


问:
How do I efficiently construct a block matrix of the following form in JULIA?
So I am working on a code that requires me to construct a large Matrix M
using smaller 'square' matrices J AND M of sizes n x n each, repeated such that:

i.e with the dimensions of M such that M is repeated 'L' times along the diagonal, J' is repeated along the upper second diagonal and J on the lower second diagonal.

Note that I am working on Julia v 1.0.0 and as far as I understand there are no direct ways of assigning Block Matrices in Julia, unlike Mathematica.

I tried to use Kronecker products to solve my problem:

```<code> =Diagonal(ones(L)) #IDENTITY matrix of L x L size
 =kron(,M)
</code>```

Doing so, I can make a Block diagonal matrix M with small matrix M repeated along its diagonal. But now how do I place matrices J and J' along its second diagonals as required?

答:
You can also do this without any external packages like this:

```<code># assign stand-in values
L = 4;
n = 2;
M = reshape(1:n^2, (n, n));
J = -M;

# put together the larger matrix
μ = [zeros(Int64, n, n) for i in 1:L, j in 1:L];
μ[diagind(μ)] .= [M];
μ[diagind(μ, -1)] .= [J];
μ[diagind(μ, 1)] .= [J'];
bM = reduce(vcat, [reduce(hcat, μ[i, :]) for i in 1:L]);
</code>```

The final matrix bM is then:

```<code>8×8 Array{Int64,2}:
  1   3  -1  -2   0   0   0   0
  2   4  -3  -4   0   0   0   0
 -1  -3   1   3  -1  -2   0   0
 -2  -4   2   4  -3  -4   0   0
  0   0  -1  -3   1   3  -1  -2
  0   0  -2  -4   2   4  -3  -4
  0   0   0   0  -1  -3   1   3
  0   0   0   0  -2  -4   2   4
</code>```

Not sure how the effiency compares to other answers, but it may at least be nice to know it can be done without too much complication.

ContentLicense: CC BY-SA 4.0

Body:
So I am working on a code that requires me to construct a large Matrix M
using smaller 'square' matrices J AND M of sizes n x n each, repeated such that:

i.e with the dimensions of M such that M is repeated 'L' times along the diagonal, J' is repeated along the upper second diagonal and J on the lower second diagonal.

Note that I am working on Julia v 1.0.0 and as far as I understand there are no direct ways of assigning Block Matrices in Julia, unlike Mathematica.

I tried to use Kronecker products to solve my problem:

 =Diagonal(ones(L)) #IDENTITY matrix of L x L size
 =kron(,M)

Doing so, I can make a Block diagonal matrix M with small matrix M repeated along its diagonal. But now how do I place matrices J and J' along its second diagonals as required?

Body:
You can also do this without any external packages like this:

# assign stand-in values
L = 4;
n = 2;
M = reshape(1:n^2, (n, n));
J = -M;

# put together the larger matrix
μ = [zeros(Int64, n, n) for i in 1:L, j in 1:L];
μ[diagind(μ)] .= [M];
μ[diagind(μ, -1)] .= [J];
μ[diagind(μ, 1)] .= [J'];
bM = reduce(vcat, [reduce(hcat, μ[i, :]) for i in 1:L]);

The final matrix bM is then:

8×8 Array{Int64,2}:
  1   3  -1  -2   0   0   0   0
  2   4  -3  -4   0   0   0   0
 -1  -3   1   3  -1  -2   0   0
 -2  -4   2   4  -3  -4   0   0
  0   0  -1  -3   1   3  -1  -2
  0   0  -2  -4   2   4  -3  -4
  0   0   0   0  -1  -3   1   3
  0   0   0   0  -2  -4   2   4

Not sure how the effiency compares to other answers, but it may at least be nice to know it can be done without too much complication.


问:
What is the use of get(0) in OnResult() method of SpeechRecognizer?
I am working on speech to text recognition. In OnResults() method of speechRecognizer, what is the use of result.get(0) as specified in the below code snippet. I found out that it is used to get the first result but what does that actually mean?

```<code>@Override
public void onResults(Bundle results)  {
    ArrayList<String> result = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    if(result != null){
        edittext.setText(result.get(0));
    }
}
</code>```

答:
"ArrayList from the Bundle [...] are the possible recognition results, where the first element is the most likely candidate." [https://developer.android.com/reference/android/speech/SpeechRecognizer#RESULTS_RECOGNITION]

You could also look at the results and determine by your own heuristic which is the most likely candidate, but index:0 is what the Recognizer deemed most likely.

Body:
I am working on speech to text recognition. In OnResults() method of speechRecognizer, what is the use of result.get(0) as specified in the below code snippet. I found out that it is used to get the first result but what does that actually mean?

@Override
public void onResults(Bundle results)  {
    ArrayList<String> result = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    if(result != null){
        edittext.setText(result.get(0));
    }
}


问:
How to make 32-bit applications in Python in a 64-bit PC
I use pyinstaller or cx_Freeze whenever I want my Python file to convert it into a .exe package, but the problem is, my PC is 64-bit, and if I make that application, it only runs on a 64-bit PC, that's why I want to know, is there a way to develop 32-bit applications on a 64-bit PC using any module or anything? Please I really need an answer!</p>

答: Download, install a 32-bit version of python and use that instead of the 64 bit python that you are using.</p>


问:
Rendering the content asynchronously in reactJS
Basically I have a set of dynamic tables that are being displayed based on the values passed. If there is an empty array passed, it should show No data found. In my case when I send data to the table, all the tables will show "No data found" first then followed by the actual table content. I am not sure what is causing this.

The data is loaded asynchronously , it shows no data found and then the actual content. I have added setInterval to show this asynchronous nature

Sandbox:https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js:0-1322

Can someone help me?

Parent

```<code>import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";

const d1 = [{ name: "test", age: "20" }, { name: "test1", age: "15" }];
const d2 = [{ area: "area", pin: "123" }, { area: "area1", pin: "1245" }];
const c1 = [
  { Header: "Name", accessor: "name" },
  { Header: "Age", accessor: "age" }
];
const c2 = [
  { Header: "Area", accessor: "area" },
  { Header: "Pin", accessor: "pin" }
];
const d3 = [];
const c3 = [];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data1: [],
      column1: [],
      data2: [],
      column2: [],
      data3: [],
      column3: []
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        data1: d1,
        column1: c1
      });
    }, 2000);
    setTimeout(() => {
      this.setState({
        data2: d2,
        column2: c2
      });
    }, 2500);
    this.setState({
      data3: d3,
      column3: c3
    });
  }

  render() {
    return (
      <>
        <DataGrid data={this.state.data1} columns={this.state.column1} />
        <DataGrid data={this.state.data2} columns={this.state.column2} />
        <DataGrid data={this.state.data3} columns={this.state.column3} />
      </>
    );
  }
}
</code>```

Child

```<code>import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  };

  formatData = () => {
    let arr = [];
    if (this.props.data && this.props.data.length > 0)
      arr = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    return arr;
  };

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = this.formatData();
    return (
      <>
        {showLink && (
          <button onClick={this.toggleState}>
            Show {showMore ? "Less" : "More"}
          </button>
        )}
        {data && data.length > 0 ? (
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
            minRows={0}
            NoDataComponent={() => null}
            loading={false}
          />
        ) : (
          "No data found"
        )}
      </>
    );
  }
}

</code>```

答:
Initialize the App state's data with null instead of an empty array (sandbox):

```<code>this.state = {
  data1: null,
  column1: [],
  data2: null,
  column2: [],
  data3: null,
  column3: []
};
</code>```

In the DataGrid method check if the value is falsy (null counts, but empty array is truthy), and return null (nothing to render) if it is:

```<code>render() {
  const { data, columns } = this.props;

  if (!data) return null;
</code>```

Body:
Basically I have a set of dynamic tables that are being displayed based on the values passed. If there is an empty array passed, it should show No data found. In my case when I send data to the table, all the tables will show "No data found" first then followed by the actual table content. I am not sure what is causing this.

The data is loaded asynchronously , it shows no data found and then the actual content. I have added setInterval to show this asynchronous nature

Sandbox:https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js:0-1322

Can someone help me?

Parent

import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";

const d1 = [{ name: "test", age: "20" }, { name: "test1", age: "15" }];
const d2 = [{ area: "area", pin: "123" }, { area: "area1", pin: "1245" }];
const c1 = [
  { Header: "Name", accessor: "name" },
  { Header: "Age", accessor: "age" }
];
const c2 = [
  { Header: "Area", accessor: "area" },
  { Header: "Pin", accessor: "pin" }
];
const d3 = [];
const c3 = [];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data1: [],
      column1: [],
      data2: [],
      column2: [],
      data3: [],
      column3: []
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        data1: d1,
        column1: c1
      });
    }, 2000);
    setTimeout(() => {
      this.setState({
        data2: d2,
        column2: c2
      });
    }, 2500);
    this.setState({
      data3: d3,
      column3: c3
    });
  }

  render() {
    return (
      <>
        <DataGrid data={this.state.data1} columns={this.state.column1} />
        <DataGrid data={this.state.data2} columns={this.state.column2} />
        <DataGrid data={this.state.data3} columns={this.state.column3} />
      </>
    );
  }
}

Child

import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  };

  formatData = () => {
    let arr = [];
    if (this.props.data && this.props.data.length > 0)
      arr = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    return arr;
  };

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = this.formatData();
    return (
      <>
        {showLink && (
          <button onClick={this.toggleState}>
            Show {showMore ? "Less" : "More"}
          </button>
        )}
        {data && data.length > 0 ? (
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
            minRows={0}
            NoDataComponent={() => null}
            loading={false}
          />
        ) : (
          "No data found"
        )}
      </>
    );
  }
}

Body:
Initialize the App state's data with null instead of an empty array (sandbox):

this.state = {
  data1: null,
  column1: [],
  data2: null,
  column2: [],
  data3: null,
  column3: []
};

In the DataGrid method check if the value is falsy (null counts, but empty array is truthy), and return null (nothing to render) if it is:

render() {
  const { data, columns } = this.props;

  if (!data) return null;


问:
Implementing my own low-pass filter in Java using fft
I'm using: http://introcs.cs.princeton.edu/java/97data/FFT.java.html to implement my own low-pass filter.

How do I rearrange the output from FFT.fft() to zero out the correct values for a correct low-pass filter?

答:
When given a waveform of N samples, this FFT implementation returns an array of size N, that you have to consider as two consecutive array of size N/2:

the first goes from index 0 to index N/2-1,

the second goes from index N/2 to the end of the array.

Each of them contain the complex energy for each integer frequency between 0 and N/2 (except that one is the opposite of the other).

So if you want to silence all signals equal or above frequency F, you have to zero out:

all the values from F to N/2-1 inclusive, and

all the values from N/2-1+F to N/2-1 inclusive.

Then you can run the inverse FFT to get your filtered signal.


问:
.NET Core 3.1 - EntityFrameworkCore - DBContext.Query obsolete
I find many examples and tutorials where functions are obsolete, but it's hard to find replacements for them

here is an examble, the Query function is obsolete, yet I cannot find what to use in it's place

```<code>SqlParameter usernameParam = new SqlParameter("@username", usernameVal ?? (object)DBNull.Value);
SqlParameter passwordParam = new SqlParameter("@password", passwordVal ?? (object)DBNull.Value);

string sqlQuery = "EXEC [dbo].[LoginByUsernamePassword] @username, @password";

lst = await context.Query<Authenticate>().FromSql(sqlQuery, usernameParam,passwordParam).ToListAsync();
</code>```

in this case, this line does not compile :

```<code>lst = await context.Query<Authenticate>().FromSql(sqlQuery, usernameParam, passwordParam).ToListAsync();
</code>```

context beeing a DbContext instance

anyone knows how to fix this ?

I have checked the microsoft doc, it says it's obsolete but does not point to it's replacement

答:
The replacement for Query<T>() is Set<T>().

So following your example it'd be something like this:

```<code>lst = await context.Set<Authenticate>().FromSqlRaw(sqlQuery, usernameParam,passwordParam).ToListAsync();
</code>```

Body:
I find many examples and tutorials where functions are obsolete, but it's hard to find replacements for them

here is an examble, the Query function is obsolete, yet I cannot find what to use in it's place

SqlParameter usernameParam = new SqlParameter("@username", usernameVal ?? (object)DBNull.Value);
SqlParameter passwordParam = new SqlParameter("@password", passwordVal ?? (object)DBNull.Value);

string sqlQuery = "EXEC [dbo].[LoginByUsernamePassword] @username, @password";

lst = await context.Query<Authenticate>().FromSql(sqlQuery, usernameParam,passwordParam).ToListAsync();

in this case, this line does not compile :

lst = await context.Query<Authenticate>().FromSql(sqlQuery, usernameParam, passwordParam).ToListAsync();

context beeing a DbContext instance

anyone knows how to fix this ?

I have checked the microsoft doc, it says it's obsolete but does not point to it's replacement

Body:
The replacement for Query<T>() is Set<T>().

So following your example it'd be something like this:

lst = await context.Set<Authenticate>().FromSqlRaw(sqlQuery, usernameParam,passwordParam).ToListAsync();


问:
how to map array of strings while assigning priorities
I want to map some strings to numbers which are used to priorities each one of them, the following way works fine but I don't think its the best way to do it.

any suggestions on how to write this piece of code in a better way ?

  private readonly PRIORITY: Map<string, number> = new Map<string, number>([
        ['XDR', 1],
        ['PT1M', 2],
        ['PT1M_', 2],
        ['PT5M', 3],
        ['PT5M_', 3],
        ['PT15M', 4],
        ['PT15M_', 4],
        ['PT1H', 5],
        ['PT1H_', 5],
        ['P1D', 6],
        ['P1D_', 6],
        ['P7D', 7],
        ['P1W', 7],
        ['P1M', 8]
    ]);
    private  getsAsPriorityMap(): Map<string, number> {
        const result: Map<string, number> = new Map<string, number>();
        const Widgets = ViewManager.getView().getWidgets();
        Widgets.forEach(graphWidget => {
            const gran = QueryProcessorService.getWidgetApplied(Widget);
            if (gran) {
                result.set(gran, this.PRIORITY.get(gran));
            }
        });
        return result;
    }```

the way the array looks is confusing I want to write in a way in which it would be easily readable by anyone reading my code

答:
If you use an enum it should look like this:

```<code>enum PRIORITY {
  XDR = 1,
  PT1M = 2,
  PT1M_ = 2,
  PT5M = 3,
  PT5M_ = 3,
  PT15M = 4,
  PT15M_ = 4,
  PT1H = 5,
  PT1H_ = 5,
  P1D = 6,
  P1D_ = 6,
  P7D = 7,
  P1W = 7,
  P1M = 8,
}
</code>```

And your getter would look something similar to the following:

```<code> private getsAsPriorityMap(): string[][] {
    const widgets = ViewManager.getView().getWidgets();
    return widgets.reduce((acc, curWidget) => {
      const gran = QueryProcessorService.getWidgetApplied(curWidget);
      acc.push([gran.toString(), PRIORITY[gran].toString()]);
      return acc;
    }, []);
  }
</code>```

Body:
I want to map some strings to numbers which are used to priorities each one of them, the following way works fine but I don't think its the best way to do it.

any suggestions on how to write this piece of code in a better way ?

  private readonly PRIORITY: Map<string, number> = new Map<string, number>([
        ['XDR', 1],
        ['PT1M', 2],
        ['PT1M_', 2],
        ['PT5M', 3],
        ['PT5M_', 3],
        ['PT15M', 4],
        ['PT15M_', 4],
        ['PT1H', 5],
        ['PT1H_', 5],
        ['P1D', 6],
        ['P1D_', 6],
        ['P7D', 7],
        ['P1W', 7],
        ['P1M', 8]
    ]);
    private  getsAsPriorityMap(): Map<string, number> {
        const result: Map<string, number> = new Map<string, number>();
        const Widgets = ViewManager.getView().getWidgets();
        Widgets.forEach(graphWidget => {
            const gran = QueryProcessorService.getWidgetApplied(Widget);
            if (gran) {
                result.set(gran, this.PRIORITY.get(gran));
            }
        });
        return result;
    }

the way the array looks is confusing I want to write in a way in which it would be easily readable by anyone reading my code

Body:
If you use an enum it should look like this:

enum PRIORITY {
  XDR = 1,
  PT1M = 2,
  PT1M_ = 2,
  PT5M = 3,
  PT5M_ = 3,
  PT15M = 4,
  PT15M_ = 4,
  PT1H = 5,
  PT1H_ = 5,
  P1D = 6,
  P1D_ = 6,
  P7D = 7,
  P1W = 7,
  P1M = 8,
}

And your getter would look something similar to the following:

 private getsAsPriorityMap(): string[][] {
    const widgets = ViewManager.getView().getWidgets();
    return widgets.reduce((acc, curWidget) => {
      const gran = QueryProcessorService.getWidgetApplied(curWidget);
      acc.push([gran.toString(), PRIORITY[gran].toString()]);
      return acc;
    }, []);
  }


问:
How to set subprotocol with boost weboscket
I want to use the subprotocol with boost websocket.

For example, I have s websocket server address , ws://127.0.0.1:5005.
Now I want to replace it with ws://127.0.0.1:5005/order.
"order" is the subprotocol in websocket, which could be used in libwebsocket.
I find no resource about subprotocol with boost.

答:
handshake method takes a target (the subprotocol as you describe it) as an options parameter.

Per documentation:

```<code>// Do the websocket handshake in the client role, on the connected stream.
// The implementation only uses the Host parameter to set the HTTP "Host" field,
// it does not perform any DNS lookup. That must be done first, as shown above.

ws.handshake(
    "www.example.com",  // The Host field
    "/order"            // The request-target
);
</code>```

Body:
handshake method takes a target (the subprotocol as you describe it) as an options parameter.

Per documentation:

// Do the websocket handshake in the client role, on the connected stream.
// The implementation only uses the Host parameter to set the HTTP "Host" field,
// it does not perform any DNS lookup. That must be done first, as shown above.

ws.handshake(
    "www.example.com",  // The Host field
    "/order"            // The request-target
);


问:
Do Firebase Cloud Functions require Billing to be enabled by April 20, 2020 because of the Cloud Build API?

Firebase: Enable the Google Cloud Build API for your Cloud Functions project? & understanding "action required" email from GCP, re: enable Cloud Build API ask for something different and I understand what Cloud Build means for Firebase Functions as described in the following. I am asking about the billing requirement - if that is a thing. This is not clear from the notice.

Cloud Functions & Cloud Build

I have received notice via email that I need to do the following for my Firebase project:

[Action Required] Enable the Google Cloud Build API for your Cloud Functions project(s) before April 20, 2020

The message further explains that Cloud Functions will use Cloud Build, Container Registry, and Cloud Storage in the future in order to deploy code.

Billing

Having received the notice, I followed the described steps:

Access the Cloud Build API link in the Cloud Console.

Select your project from the drop-down menu.

Click Continue to enable the Cloud Build API for the project. A box will appear in the lower-left corner to confirm the API is enabled.

I visited the link and followed the steps and it fails: This API cannot be enabled at the moment. You may lack appropriate permissions.
Using the "Enable" button at Cloud Build in the Google Cloud Console for my Firebase project shows me:

Billing required

Does this mean that Cloud Functions for Firebase now require billing to be enabled, i.e. the Blaze plan?

答:
Yes! You can never trust google to be good for long.

Now they want to move you to paid plans to write cloud functions.

If would have been ok, but when you consider that even simple things like knowing the count of a collection in firebase/firestore will also require a paid billing plan as probably you want to use increment/decrement counter on database triggers, it's really messed up to see how such a database can be useful.

I think its time for developer to find some other avenues which are more honest.


问:
Why are template divs showing as ":hidden" in afterRender?
Why are template divs showing as ":hidden" in afterRender?

Here's the code:

```

答:
When afterRender is called for the template binding in foreach mode, the elements have not been added to the DOM yet.  Some additional processing is done to make sure that nodes are efficiently added/removed.

However, you can instead use the afterAdd callback when using the foreach option to execute code after the elements are in the DOM.


问:
Flutter convert JSON string to multi-level list
I want to convert a string to multi-level list, but I cannot find a efficient way to do.

From String:
[[1,2,3],[1,2]]

To List:
List< List < int>>

答:
Try this as a funtion

```<code>List<List<int>> convert(String val){
    List<List<int>> list = [];
  jsonDecode(val).forEach((mainList) {
    List<int> subList = [];
    mainList.forEach((sList) {
      subList.add(sList);
    });
    list.add(subList);
  });
  return list;
}
</code>```

Also import dart:convert;

Body:
Try this as a funtion

List<List<int>> convert(String val){
    List<List<int>> list = [];
  jsonDecode(val).forEach((mainList) {
    List<int> subList = [];
    mainList.forEach((sList) {
      subList.add(sList);
    });
    list.add(subList);
  });
  return list;
}

Also import dart:convert;


问:
Check in file the data match the syntax
i have a scenario where i want to check the below details in files match the syntax

Syntax : NAME/SURNAME/COUNTRY

Note : every record in file should match the syntax. if one records does not match then should display
failed or success

File data

```<code>Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/
</code>```

As you can see the file data the last record does not match according to the syntax
then should display failed

My code

```<code> for i in `cat /demo/Student.txt`
      do
      check=`echo $i | cut -d '/' -f3`
      if [[ -z $check ]];
      then
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1
      fi
    done
</code>```

答:
Syntax : NAME/SURNAME/COUNTRY

Is very much underspecified. First write a regex to match your line - then just use a utility to check if each line matches the regex.

With grep:

```<code>if grep -v -q '^[[:alpha:]]\+/[[:alpha:]]\+/[[:alpha:]]\+$' "$file"; then
    echo "failed synax grep"
fi
</code>```

grep matches a regex:

-v invert match

^ match beginning of the line

[[:alpha:]]\+ one or more consecutive characters sed character classes. You could use [^/]* or [^/]+ instead for the same behavior as your current code wanted to do.

/ a slash

etc.

$ match ending of the line

With gnu sed:

```<code>if ! sed -n '\@^[[:alpha:]]\+/[[:alpha:]]\+/[[:alpha:]]\+$@!q1' "$file"; then
    echo "failed syntax"
fi
</code>```

Sed does:

\@....@ - match the regex inside

! - if the regex was not matched

q1 - quit with exit status 1

You could also remove all characters except newline and a slash and check if each line has 3 characters.

Notes:

for i in cat is a common antipattern in bash - you shouldn't use this form. How to read a file line by line in bash bashfaq

`...` Do not use backticks, they are discouraged. Use $(...) instead. bash hackers wiki obsolete and deprecated

Title: Check in file the data match the syntax

Body:
i have a scenario where i want to check the below details in files match the syntax

Syntax : NAME/SURNAME/COUNTRY

Note : every record in file should match the syntax. if one records does not match then should display
failed or success

File data

Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/

As you can see the file data the last record does not match according to the syntax
then should display failed

My code

 for i in `cat /demo/Student.txt`
      do
      check=`echo $i | cut -d '/' -f3`
      if [[ -z $check ]];
      then
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1
      fi
    done

Body:
Syntax : NAME/SURNAME/COUNTRY

Is very much underspecified. First write a regex to match your line - then just use a utility to check if each line matches the regex.

With grep:

if grep -v -q '^[[:alpha:]]\+/[[:alpha:]]\+/[[:alpha:]]\+$' "$file"; then
    echo "failed synax grep"
fi

grep matches a regex:

-v invert match

^ match beginning of the line

[[:alpha:]]\+ one or more consecutive characters sed character classes. You could use [^/]* or [^/]+ instead for the same behavior as your current code wanted to do.

/ a slash

etc.

$ match ending of the line

With gnu sed:

if ! sed -n '\@^[[:alpha:]]\+/[[:alpha:]]\+/[[:alpha:]]\+$@!q1' "$file"; then
    echo "failed syntax"
fi

Sed does:

\@....@ - match the regex inside

! - if the regex was not matched

q1 - quit with exit status 1

You could also remove all characters except newline and a slash and check if each line has 3 characters.

Notes:

for i in cat is a common antipattern in bash - you shouldn't use this form. How to read a file line by line in bash bashfaq

`...` Do not use backticks, they are discouraged. Use $(...) instead. bash hackers wiki obsolete and deprecated


问:
Sorting high-scores in JavaScript?
Hello I am writing a game using javascript that takes the user's name as well as the "round" they made it to and stores it in two different arrays, and I would like to display the names coupled with the scores, highest to lowest but I'm stumped on how to do it, I can sort the rounds from highest to lowest but I can't figure out how to sort the names along with them. Please help!

my current code:

```<code>        nameScore.push(username);
        highScore.push(round);
        highScore.reverse();

        for (var i = 0; i < highScore.length; i++) {
            $("#highScore").append(nameScore[i] + "  " + highScore[i] + "<br>");
        }
</code>```

答:
There are many suggestions in Stackoverflow on handling the synchronous sorting of several arrays. One idea that came to my mind is the creation of a sorted index array for stepping through the concerned arrays, that are left unsorted. Here is a short example with array nam, containing names and array num with the associated scores. The function mkidx(arr) expects the array to be sorted after as an argument (I chose num) and returns a sorted (in descending order) index array that can then be used to step through all unsorted arrays:

var nam=['eins','zwei','drei'];
var num=[10,200,30];

// create an index array:
const mkidx=arr=>arr.map((v,i)=>
({v,i})).sort((a,b)=> typeof a.v=="string"? a.v.localeCompare(b.v) : b.v-a.v).map(v=>v.i);

mkidx(num).forEach(k=>
console.log(k,nam[k]+': '+num[k])
)```

I created the index-creation function such that it checks for the type of elements and then sorts either alphabetically (.localeCompare()) or numerically (descending).

Title: Sorting high-scores in JavaScript?

Body:
Hello I am writing a game using javascript that takes the user's name as well as the "round" they made it to and stores it in two different arrays, and I would like to display the names coupled with the scores, highest to lowest but I'm stumped on how to do it, I can sort the rounds from highest to lowest but I can't figure out how to sort the names along with them. Please help!

my current code:

        nameScore.push(username);
        highScore.push(round);
        highScore.reverse();

        for (var i = 0; i < highScore.length; i++) {
            $("#highScore").append(nameScore[i] + "  " + highScore[i] + "
");
        }

Body:
There are many suggestions in Stackoverflow on handling the synchronous sorting of several arrays. One idea that came to my mind is the creation of a sorted index array for stepping through the concerned arrays, that are left unsorted. Here is a short example with array nam, containing names and array num with the associated scores. The function mkidx(arr) expects the array to be sorted after as an argument (I chose num) and returns a sorted (in descending order) index array that can then be used to step through all unsorted arrays:

var nam=['eins','zwei','drei'];
var num=[10,200,30];

// create an index array:
const mkidx=arr=>arr.map((v,i)=>
({v,i})).sort((a,b)=> typeof a.v=="string"? a.v.localeCompare(b.v) : b.v-a.v).map(v=>v.i);

mkidx(num).forEach(k=>
console.log(k,nam[k]+': '+num[k])
)

I created the index-creation function such that it checks for the type of elements and then sorts either alphabetically (.localeCompare()) or numerically (descending).


问:
Azure and NX, error while running a pipeline : npm : Another process, with id 4224, is currently running ngcc
I'm trying to run a pipeline with Azure, when it comes to build, it fails with this error :

When I run the nx affected --target=build --base=origin/master --prod --parallel command locally, I also have the Another process... message but it doesn't show as an error which lets the build continues. But on Azure it just fails :(

Any idea how I can solve this? Thanks

答:
After further investigation, I found out the problem was with powershell.

Here is the yaml code I was using :

```<code>- task: PowerShell@2
        displayName: 'Running build'
        inputs:
          targetType: 'inline'
          script: 'npm run nx affected -- --target=build --base=origin/master --prod --parallel'
</code>```

It looks like Powershell exited on this error which doesn't seem to be the case with either cmd.exe or pwsh.
Here is the version that works :

```<code>- pwsh: 'npm run nx affected -- --target=build --parallel --base=origin/master --prod'
        displayName: 'Running build'
</code>```

Body:
After further investigation, I found out the problem was with powershell.

Here is the yaml code I was using :

- task: PowerShell@2
        displayName: 'Running build'
        inputs:
          targetType: 'inline'
          script: 'npm run nx affected -- --target=build --base=origin/master --prod --parallel'

It looks like Powershell exited on this error which doesn't seem to be the case with either cmd.exe or pwsh.
Here is the version that works :

- pwsh: 'npm run nx affected -- --target=build --parallel --base=origin/master --prod'
        displayName: 'Running build'


问:
Looping over array in react native
enter image description herethese is my input array(service_item_list)
...

```<code>for (var k = 0; k < service_item_list.length; k++) {
            for (var l = 0; l < service_item_list[k].length; l++) {
                service_item_list[k][l].service_id=this.state.selected_services[k].id
            }
        }

service_item_list=[[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}],[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}]]

this.state.selected_services=[{id:'5',event_id:'1'},{id:'6',event_id:'1'}]
</code>```

...
i keep getting the output :
...

```<code>service_item_list=[[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}],[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}]]
</code>```

...
but i need the output :
...

```<code> service_item_list=[[{event_id:'1',service_id:'5',product_id:''},{event_id:'1',service_id:'5',product_id:''},{event_id:'1',service_id:'5',product_id:''}],[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}]]
</code>```

...
I'm not able to find where the error is???

答:
You can make things easier using JavaScript array map method. So the approach will be like this:

```<code>const service_item_list=[[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}],[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}]]

const selected_services=[{id:'5',event_id:'1'},{id:'6',event_id:'1'}]

const res = service_item_list.map((arr, outerIdx) => {
    return arr.map((obj) => {
        obj.service_id = selected_services[outerIdx].id
        return obj;
    })
})

console.log(res)

[
    [
        { event_id: '', service_id: '5', product_id: '' },
        { event_id: '', service_id: '5', product_id: '' },
        { event_id: '', service_id: '5', product_id: '' },
    ],
    [
        { event_id: '', service_id: '6', product_id: '' },
        { event_id: '', service_id: '6', product_id: '' },
        { event_id: '', service_id: '6', product_id: '' },
    ],
];
</code>```

The value stored in the res constant will be your result as shown above. More on JS array map method here

Title: Looping over array in react native

Body:
enter image description herethese is my input array(service_item_list)
...

for (var k = 0; k < service_item_list.length; k++) {
            for (var l = 0; l < service_item_list[k].length; l++) {
                service_item_list[k][l].service_id=this.state.selected_services[k].id
            }
        }

service_item_list=[[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}],[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}]]

this.state.selected_services=[{id:'5',event_id:'1'},{id:'6',event_id:'1'}]

...
i keep getting the output :
...

service_item_list=[[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}],[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}]]

...
but i need the output :
...

 service_item_list=[[{event_id:'1',service_id:'5',product_id:''},{event_id:'1',service_id:'5',product_id:''},{event_id:'1',service_id:'5',product_id:''}],[{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''},{event_id:'1',service_id:'6',product_id:''}]]

...
I'm not able to find where the error is???

Body:
You can make things easier using JavaScript array map method. So the approach will be like this:

const service_item_list=[[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}],[{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''},{event_id:'',service_id:'',product_id:''}]]

const selected_services=[{id:'5',event_id:'1'},{id:'6',event_id:'1'}]

const res = service_item_list.map((arr, outerIdx) => {
    return arr.map((obj) => {
        obj.service_id = selected_services[outerIdx].id
        return obj;
    })
})

console.log(res)

[
    [
        { event_id: '', service_id: '5', product_id: '' },
        { event_id: '', service_id: '5', product_id: '' },
        { event_id: '', service_id: '5', product_id: '' },
    ],
    [
        { event_id: '', service_id: '6', product_id: '' },
        { event_id: '', service_id: '6', product_id: '' },
        { event_id: '', service_id: '6', product_id: '' },
    ],
];

The value stored in the res constant will be your result as shown above. More on JS array map method here


问:
Mysterious margins on webpage
I am developing a Wordpress theme and noticed that the whole body of the page is pushed down a bit. I used the inspector in Chrome to find the problem and I found the following styles:

```

If I delete this in the inspector the body of the page snaps back to the top. But here is the weird thing. I tried deleting my whole stylesheet to see if the problem was in the css, but the problem is still there. So my guess id that Chrome must be adding these lines, but why? It works fine in IE and Edge.

Edit: I tried clearing css cache in Crome, but no difference..
Edit: I tried adding css reset to the stylesheet but still no difference...

CSS (quite messy, but work in progress): https://codeshare.io/sr0sg

答:
This question is a little bit old, but the suggested solution is too much drastic. I suggest to maintain the admin bar and just remove the weird CSS.

This can be accomplished with this snippet:

```<code>add_action('get_header', 'remove_admin_bar_weird_css');
function remove_admin_bar_weird_css() {
    remove_action('wp_head', '_admin_bar_bump_cb');
}
</code>```

Title: Mysterious margins on webpage

Body:
I am developing a Wordpress theme and noticed that the whole body of the page is pushed down a bit. I used the inspector in Chrome to find the problem and I found the following styles:

If I delete this in the inspector the body of the page snaps back to the top. But here is the weird thing. I tried deleting my whole stylesheet to see if the problem was in the css, but the problem is still there. So my guess id that Chrome must be adding these lines, but why? It works fine in IE and Edge.

Edit: I tried clearing css cache in Crome, but no difference..
Edit: I tried adding css reset to the stylesheet but still no difference...

CSS (quite messy, but work in progress): https://codeshare.io/sr0sg

Body:
This question is a little bit old, but the suggested solution is too much drastic. I suggest to maintain the admin bar and just remove the weird CSS.

This can be accomplished with this snippet:

add_action('get_header', 'remove_admin_bar_weird_css');
function remove_admin_bar_weird_css() {
    remove_action('wp_head', '_admin_bar_bump_cb');
}


问:
DropDownListFor why it gets the Key and Nothing else
I have a property in my model very simple one:

Now this dropDown doesn't work right

```<code>@Html.DropDownListFor(m => m.Camp, new SelectList(ViewBag.Camps, "Id", "Name"))
</code>```

it returns null instead of a chosen Camp, but if I change that into:

```<code>@Html.DropDownListFor(m => m.Camp.Id, new SelectList(ViewBag.Camps, "Id", "Name"))
</code>```

It would return me a Camp object with correct Id, but the Name would be still null.

Why?

UPD:

And now another problem is if I choose the second approach it would screw up with unobtrusive validation. Although I'll be able to get the right camp based on the chosen id.

答:
That's normal. Only the Id is posted to the controller action. That's how dropdown inside forms work. So that's all you can hope to get there. You will then use this Id to get the corresponding Camp object from the database:

```<code>[HttpPost]
public ActionResult Foo([Bind(Prefix = "Camp")]int id)
{
    Camp camp = Repository.GetCamp(id);
    ...
}
</code>```

Also please get rid of this ViewBag and use a real view model:

```<code>public class CampViewModel
{
    public int Id { get; set; }
    public IEnumerable<SelectListItem> Camps { get; set; }
}
</code>```

and in the controller:

```<code>public ActionResult Index()
{
    var model = new CampViewModel
    {
        Camps = Repository.GetCamps().Select(x => new SelectListItem
        {
            Value = x.Id.ToString(),
            Text = x.Name
        })
    };
    return View(model);
}

[HttpPost]
public ActionResult Index(int id)
{
    Camp camp = Repository.GetCamp(id);
    ...
}
</code>```

and the view:

```<code>@model CampViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.Id,
        new SelectList(Model.Camps, "Value", "Text")
    )
    <input type="submit" value="OK" />
}
</code>```

Body:
I have a property in my model very simple one:

Now this dropDown doesn't work right

@Html.DropDownListFor(m => m.Camp, new SelectList(ViewBag.Camps, "Id", "Name"))

it returns null instead of a chosen Camp, but if I change that into:

@Html.DropDownListFor(m => m.Camp.Id, new SelectList(ViewBag.Camps, "Id", "Name"))

It would return me a Camp object with correct Id, but the Name would be still null.

Why?

UPD:

And now another problem is if I choose the second approach it would screw up with unobtrusive validation. Although I'll be able to get the right camp based on the chosen id.

Body:
That's normal. Only the Id is posted to the controller action. That's how dropdown inside forms work. So that's all you can hope to get there. You will then use this Id to get the corresponding Camp object from the database:

[HttpPost]
public ActionResult Foo([Bind(Prefix = "Camp")]int id)
{
    Camp camp = Repository.GetCamp(id);
    ...
}

Also please get rid of this ViewBag and use a real view model:

public class CampViewModel
{
    public int Id { get; set; }
    public IEnumerable<SelectListItem> Camps { get; set; }
}

and in the controller:

public ActionResult Index()
{
    var model = new CampViewModel
    {
        Camps = Repository.GetCamps().Select(x => new SelectListItem
        {
            Value = x.Id.ToString(),
            Text = x.Name
        })
    };
    return View(model);
}

[HttpPost]
public ActionResult Index(int id)
{
    Camp camp = Repository.GetCamp(id);
    ...
}

and the view:

@model CampViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.Id,
        new SelectList(Model.Camps, "Value", "Text")
    )
    <input type="submit" value="OK" />
}


问:
Colormap issue in folium map
I am looking to create a heatmap of the USA based on data of COVID 19 cases. For that, I am using folium and geopandas. Here is the link for the data

and the code I used is given below.

```<code>colormap = cm.linear.YlGnBu_09.to_step(data=merged_data_cases['cases'],
           method='quant', quantiles=[0,0.1,0.75,0.9,0.98,1]

usa_map = folium.Map(location=[48, -102], zoom_start=3, tiles=None)
folium.TileLayer('CartoDB positron',name="Light Map",control=False).add_to(usa_map)
colormap.caption = 'Confirmed Cases'

style_function = lambda x: {"weight":0.5,
                        'color':'black',
                        'fillColor':colormap(x['properties']['cases']),
                        'fillOpacity':0.75}
highlight_function = lambda x: {'fillColor': '#000000',
                           'color':'#000000',
                            'fillOpacity': 0.50,
                            'weight': 0.1}
interactive = folium.features.GeoJson(
                merged_data_cases,
                style_function=style_function,
                control=False,
                highlight_function=highlight_function,
        tooltip=folium.features.GeoJsonTooltip(
                 fields=['Name','cases'],
                 aliases=['State: ','Confirmed Cases: '],
                 style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;"),
    sticky = True
   )
)
   colormap.add_to(usa_map)
   usa_map.add_child(interactive)
   usa_map
</code>```

While I run the code, I get the following error.

```<code>AssertionError: The field Name is not available in the data. Choose from: ('NAME', 'STATE', 'cases').
</code>```

I have gone through so many articles, blogs and documentation but still couldn't figure out my error. Can anybody point out what I am doing wrong here? I believe the error is due to style_function parameters.

答:
It seems that you should write name in capital letters as NAME in fields=['Name','cases'] as the available fields in the error message are stated as
NAME, STATE, cases

Title: Colormap issue in folium map

Body:
I am looking to create a heatmap of the USA based on data of COVID 19 cases. For that, I am using folium and geopandas. Here is the link for the data

and the code I used is given below.

colormap = cm.linear.YlGnBu_09.to_step(data=merged_data_cases['cases'],
           method='quant', quantiles=[0,0.1,0.75,0.9,0.98,1]

usa_map = folium.Map(location=[48, -102], zoom_start=3, tiles=None)
folium.TileLayer('CartoDB positron',name="Light Map",control=False).add_to(usa_map)
colormap.caption = 'Confirmed Cases'

style_function = lambda x: {"weight":0.5,
                        'color':'black',
                        'fillColor':colormap(x['properties']['cases']),
                        'fillOpacity':0.75}
highlight_function = lambda x: {'fillColor': '#000000',
                           'color':'#000000',
                            'fillOpacity': 0.50,
                            'weight': 0.1}
interactive = folium.features.GeoJson(
                merged_data_cases,
                style_function=style_function,
                control=False,
                highlight_function=highlight_function,
        tooltip=folium.features.GeoJsonTooltip(
                 fields=['Name','cases'],
                 aliases=['State: ','Confirmed Cases: '],
                 style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;"),
    sticky = True
   )
)
   colormap.add_to(usa_map)
   usa_map.add_child(interactive)
   usa_map

While I run the code, I get the following error.

AssertionError: The field Name is not available in the data. Choose from: ('NAME', 'STATE', 'cases').

I have gone through so many articles, blogs and documentation but still couldn't figure out my error. Can anybody point out what I am doing wrong here? I believe the error is due to style_function parameters.


问:
Not able to access my Flask server through ingress
I am new to the concepts of Flask and k8s and trying to implement a very simple Flask server via k8s for getting familiar with the concept.
Am able to access it via NodePort. But after adding ingress service and tweaking my host file in windows machine. When I tried to access the host URL, which I added in ingress-srv.yaml, I am getting a 404 error.

Here is the project Github link: https://github.com/bijay-ps/flask-poc

can someone help me out??

答:
You need to describe which k8s you are using. (ex. minikube, gcp, azure etc) And version of client and server

```<code>$ kubectl version
Client Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.3", GitCommit:"2d3c76f9091b6bec110a5e63777c332469e0cba2", GitTreeState:"clean", BuildDate:"2019-08-19T12:36:28Z", GoVersion:"go1.12.9", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"17+", GitVersion:"v1.17.5-gke.6", GitCommit:"de3e4dcd39464bc1601edd66681e663bff1fe530", GitTreeState:"clean", BuildDate:"2020-05-12T16:10:21Z", GoVersion:"go1.13.9b4", Compiler:"gc", Platform:"linux/amd64"}
</code>```

Make sure you install Nginx Ingress Controller. There's no default(pre-installed) ingress.

```<code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-0.32.0/deploy/static/provider/cloud/deploy.yaml
</code>```

Your yaml configs looks ok.

Body:
You need to describe which k8s you are using. (ex. minikube, gcp, azure etc) And version of client and server

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.3", GitCommit:"2d3c76f9091b6bec110a5e63777c332469e0cba2", GitTreeState:"clean", BuildDate:"2019-08-19T12:36:28Z", GoVersion:"go1.12.9", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"17+", GitVersion:"v1.17.5-gke.6", GitCommit:"de3e4dcd39464bc1601edd66681e663bff1fe530", GitTreeState:"clean", BuildDate:"2020-05-12T16:10:21Z", GoVersion:"go1.13.9b4", Compiler:"gc", Platform:"linux/amd64"}

Make sure you install Nginx Ingress Controller. There's no default(pre-installed) ingress.

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-0.32.0/deploy/static/provider/cloud/deploy.yaml

Your yaml configs looks ok.


问:
How to append a char to a std::string?
The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’

```<code>int main()
{
  char d = 'd';
  std::string y("Hello worl");
  y.append(d); // Line 5 - this fails
  std::cout << y;
  return 0;
}
</code>```

I also tried, the following, which compiles but behaves randomly at runtime:

```<code>int main()
{
  char d[1] = { 'd' };
  std::string y("Hello worl");
  y.append(d);
  std::cout << y;
  return 0;
}
</code>```

Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.

答:
Also adding insert option, as not mentioned yet. </p>

```<code>std::string str("Hello World");
char ch;

str.push_back(ch);  //ch is the character to be added
OR
str.append(sizeof(ch),ch);
OR
str.insert(str.length(),sizeof(ch),ch) //not mentioned above
</code>```

Title: How to append a char to a std::string?

Body:
The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’

int main()
{
  char d = 'd';
  std::string y("Hello worl");
  y.append(d); // Line 5 - this fails
  std::cout << y;
  return 0;
}

I also tried, the following, which compiles but behaves randomly at runtime:

int main()
{
  char d[1] = { 'd' };
  std::string y("Hello worl");
  y.append(d);
  std::cout << y;
  return 0;
}

Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.

Body:
Also adding insert option, as not mentioned yet.

std::string str("Hello World");
char ch;

str.push_back(ch);  //ch is the character to be added
OR
str.append(sizeof(ch),ch);
OR
str.insert(str.length(),sizeof(ch),ch) //not mentioned above


问:
Why does my mesh disappear wholly when only part of it is out of the screen
I use the following code to create a strip-shaped plane.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DynamicPlane : MonoBehaviour
{
    private GameObject _plane;
    private Mesh _planeMesh;
    private MeshRenderer _planMeshRenderer;
    private List<Vector3> _planeMeshVertices;
    private int[] _planeMeshIndices;

    // Start is called before the first frame update
    void Start()
    {
        _plane = new GameObject("My Plane");
        _plane.AddComponent<MeshFilter>();
        _plane.AddComponent<MeshRenderer>();
        _planeMeshVertices = new List<Vector3>() { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero };
        _planeMeshIndices = new int[6] { 0, 1, 2, 2, 1, 3 };
        _planeMesh = new Mesh();
        _planeMesh.SetVertices(_planeMeshVertices);
        _planeMesh.SetIndices(_planeMeshIndices, MeshTopology.Triangles, 0);
        _plane.GetComponent<MeshFilter>().sharedMesh = _planeMesh;
        _planMeshRenderer = _plane.GetComponent<MeshRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        _planeMeshVertices[0] = new Vector3(1, 0, 0);
        _planeMeshVertices[1] = new Vector3(0, 0, 0);
        _planeMeshVertices[2] = new Vector3(1, 0, 50);
        _planeMeshVertices[3] = new Vector3(0, 0, 50);
        _planeMesh.SetVertices(_planeMeshVertices);
    }

}
</code>```

I set vertices in Update() because in a real project I need to dynamically change the position of vertices.

Start the game and check the Scene view. The purple strip is my plane created by code and the white plane is a primitive. The strip disappears wholly when only a tiny part of it is out of the screen. The white plane is normal. Why does this happen?

答:
The Problem

Unity culls of objects that are off-screen by using the Render.bounds that are basically the Mesh.bounds but with applied local transformations (position, rotation, scale).

The moment you are creating the mesh via

_planeMesh = new Mesh();
```

<p>this mesh is empty and gets default bounds (center <code>0,0,0</code> and extends <code>0,0,0</code>).</p>

<p>Later when you change the vetices you do not calculate new bounds but still use the initial ones.</p>

<p>Therefore you will have noted that the "wrong" culling actually only happens if the bottom left corner (being on <code>0,0,0</code>) leaves the screen since Unity thinks that this is all of your mesh.</p>

<p><img src="https://i.stack.imgur.com/9DBOT.gif" alt="enter image description here"></p>

<h3>Solution</h3>

<p>Anytime you change something in the mesh you should call <code>RecalculateBounds</code> in order to update the bounds.</p>

<pre class="lang-c# prettyprint-override"><code>void Update()
{
    _planeMeshVertices[0] = new Vector3(1, 0, 0);
    _planeMeshVertices[1] = new Vector3(0, 0, 0);
    _planeMeshVertices[2] = new Vector3(1, 0, 50);
    _planeMeshVertices[3] = new Vector3(0, 0, 50);
    _planeMesh.SetVertices(_planeMeshVertices);

    _planeMesh.RecalculateBounds();
}
</code>```

Body:
I use the following code to create a strip-shaped plane.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DynamicPlane : MonoBehaviour
{
    private GameObject _plane;
    private Mesh _planeMesh;
    private MeshRenderer _planMeshRenderer;
    private List<Vector3> _planeMeshVertices;
    private int[] _planeMeshIndices;

    // Start is called before the first frame update
    void Start()
    {
        _plane = new GameObject("My Plane");
        _plane.AddComponent<MeshFilter>();
        _plane.AddComponent<MeshRenderer>();
        _planeMeshVertices = new List<Vector3>() { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero };
        _planeMeshIndices = new int[6] { 0, 1, 2, 2, 1, 3 };
        _planeMesh = new Mesh();
        _planeMesh.SetVertices(_planeMeshVertices);
        _planeMesh.SetIndices(_planeMeshIndices, MeshTopology.Triangles, 0);
        _plane.GetComponent<MeshFilter>().sharedMesh = _planeMesh;
        _planMeshRenderer = _plane.GetComponent<MeshRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        _planeMeshVertices[0] = new Vector3(1, 0, 0);
        _planeMeshVertices[1] = new Vector3(0, 0, 0);
        _planeMeshVertices[2] = new Vector3(1, 0, 50);
        _planeMeshVertices[3] = new Vector3(0, 0, 50);
        _planeMesh.SetVertices(_planeMeshVertices);
    }

}

I set vertices in Update() because in a real project I need to dynamically change the position of vertices.

Start the game and check the Scene view. The purple strip is my plane created by code and the white plane is a primitive. The strip disappears wholly when only a tiny part of it is out of the screen. The white plane is normal. Why does this happen?

Body:
The Problem

Unity culls of objects that are off-screen by using the Render.bounds that are basically the Mesh.bounds but with applied local transformations (position, rotation, scale).

The moment you are creating the mesh via

_planeMesh = new Mesh();

this mesh is empty and gets default bounds (center 0,0,0 and extends 0,0,0).

Later when you change the vetices you do not calculate new bounds but still use the initial ones.

Therefore you will have noted that the "wrong" culling actually only happens if the bottom left corner (being on 0,0,0) leaves the screen since Unity thinks that this is all of your mesh.

Solution

Anytime you change something in the mesh you should call RecalculateBounds in order to update the bounds.

void Update()
{
    _planeMeshVertices[0] = new Vector3(1, 0, 0);
    _planeMeshVertices[1] = new Vector3(0, 0, 0);
    _planeMeshVertices[2] = new Vector3(1, 0, 50);
    _planeMeshVertices[3] = new Vector3(0, 0, 50);
    _planeMesh.SetVertices(_planeMeshVertices);

    _planeMesh.RecalculateBounds();
}


问:
IsNumeric() allowing minus at last of the values
I am using IsNumeric() function in my code to validate numbers.

IsNumeric(100)  - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,

IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.

```<code>    Dim latitude As String = "12.56346-"
    If IsNumeric(latitude) Then
        If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
            isValidLatitude.Text = "true"
        Else
            isValidLatitude.Text = "false"
        End If
     Else
        isValidLatitude.Text = "false"
     End If
</code>```

Error while converting latitude to double

```<code>Input string was not in a correct format.
</code>```

答:
IsNumeric answers a question no sane person wants to ask. As quoted by Vitox's answer:

IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort. It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number.

Note, it doesn't tell you that the given string can be converted to all numeric types. It tells you that the string can be converted to at least one numeric type. And for bonus bad style points, of course, it doesn't tell you which types the string can be converted to.

Decimal.Parse("100-") will execute perfectly well and give you a Decimal containing a value of -100.

So, it's not a bug, it's a bad function that has been retained for backwards compatibility reasons. Nowadays, we know better, and that we want to test whether a string can be converted to a specific data type, for which the TryParse family of functions have been designed.

Body:
I am using IsNumeric() function in my code to validate numbers.

IsNumeric(100)  - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,

IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.

    Dim latitude As String = "12.56346-"
    If IsNumeric(latitude) Then
        If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
            isValidLatitude.Text = "true"
        Else
            isValidLatitude.Text = "false"
        End If
     Else
        isValidLatitude.Text = "false"
     End If

Error while converting latitude to double

Input string was not in a correct format.


问:
How to edit string in .ini file with user input VBScript
I have .ini file and I need to edit one line of that with user input

```<code>##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%
</code>```

In this .ini file I need to change the

```<code>PlayerName = SoulFlyers
</code>```

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

```<code>    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************
</code>```

but it adds lines to .ini files.

How can I solve it?

Thanks.

答:
This could be a nice solution for your issue, i found this neat function on a french forum :

NB : I will try to translate the comments as soon as possible in english

```<code>Option Explicit
Dim Title,fso,oFile,PlayerName,NewPlayerName
Title = "Read and Write from INI file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("Settings.ini")

PlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) 'For reading only
MsgBox "The content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title

NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName","Dariush") ' write the new variable here as example "Dariush"
MsgBox "The New content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title

Function WriteReadIni(oFile,section,key,value)
' *******************************************************************************************
' omen999 - mars 2018 v 1.1 - http://omen999.developpez.com/
' écrit/lit la clé <key> de section <section> de l'objet fichier oFile avec la valeur <value> si lecture : value = Null
' en écriture si la section et/ou la clé n'existent pas, elles seront créées
' en écriture renvoie faux si le couple clé/valeur existait déjà sinon vrai
' en lecture renvoie soit : la valeur de clé, une chaine vide en cas de  clé vide ou Faux si la clé n'existe pas
' ********************************************************************************************
Dim oText,iniText,sectText,newSectText,keyText,reg,regSub
  ' Initialisation des objets regexp
  ' peut être déplacé dans le code principal en cas d'appels successifs
  Set reg = New RegExp
  Set regSub = New RegExp
  reg.MultiLine=True 'simplifie le pattern
  reg.IgnoreCase = True
  regSub.IgnoreCase = True
  Set oText = oFile.OpenAsTextStream(1,0)
  iniText = oText.ReadAll
  oText.Close
  reg.Pattern = "^\[" & section & "\]((.|\n[^\[])+)"
  regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
  On Error Resume Next
  If IsNull(value) Then   ' lecture clé
    WriteReadIni = regSub.Execute(reg.Execute(iniText).Item(0).SubMatches(0)).Item(0).SubMatches(0)
    If Err.Number = 5 then WriteReadIni = False
  Else                                              ' écriture clé
    sectText = reg.Execute(iniText).Item(0).SubMatches(0)
    If Err.Number = 5 Then ' section inconnue
      iniText = iniText & vbCrLf & "[" & section & "]" & vbCrLf & key & "=" & value
    Else
      newSectText = regSub.Replace(sectText,key & "=" & value)
      If newSectText = sectText Then ' pas de remplacement constaté. soit le clé/valeur existe déjà soit c'est une nouvelle clé
        If regSub.Test(sectText) Then ' le couple clé/valeur existe déjà -> sortie
          WriteReadIni = False
          Exit Function
        End If
        If Right(sectText,1) = vbCr Then keyText = key & "=" & value Else keyText = vbCrLf & key & "=" & value
        newSectText = sectText & keyText
      End If
      iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
    End If
    Set oText = oFile.OpenAsTextStream(2,0)
    oText.Write iniText
    oText.Close
    WriteReadIni = True
  End If
End Function
</code>```

Body:
I have .ini file and I need to edit one line of that with user input

##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%

In this .ini file I need to change the

PlayerName = SoulFlyers

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************

but it adds lines to .ini files.

How can I solve it?

Thanks.

Body:
This could be a nice solution for your issue, i found this neat function on a french forum :

NB : I will try to translate the comments as soon as possible in english

Option Explicit
Dim Title,fso,oFile,PlayerName,NewPlayerName
Title = "Read and Write from INI file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("Settings.ini")

PlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) 'For reading only
MsgBox "The content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title

NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName","Dariush") ' write the new variable here as example "Dariush"
MsgBox "The New content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title

Function WriteReadIni(oFile,section,key,value)
' *******************************************************************************************
' omen999 - mars 2018 v 1.1 - http://omen999.developpez.com/
' écrit/lit la clé <key> de section <section> de l'objet fichier oFile avec la valeur <value> si lecture : value = Null
' en écriture si la section et/ou la clé n'existent pas, elles seront créées
' en écriture renvoie faux si le couple clé/valeur existait déjà sinon vrai
' en lecture renvoie soit : la valeur de clé, une chaine vide en cas de  clé vide ou Faux si la clé n'existe pas
' ********************************************************************************************
Dim oText,iniText,sectText,newSectText,keyText,reg,regSub
  ' Initialisation des objets regexp
  ' peut être déplacé dans le code principal en cas d'appels successifs
  Set reg = New RegExp
  Set regSub = New RegExp
  reg.MultiLine=True 'simplifie le pattern
  reg.IgnoreCase = True
  regSub.IgnoreCase = True
  Set oText = oFile.OpenAsTextStream(1,0)
  iniText = oText.ReadAll
  oText.Close
  reg.Pattern = "^\[" & section & "\]((.|\n[^\[])+)"
  regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
  On Error Resume Next
  If IsNull(value) Then   ' lecture clé
    WriteReadIni = regSub.Execute(reg.Execute(iniText).Item(0).SubMatches(0)).Item(0).SubMatches(0)
    If Err.Number = 5 then WriteReadIni = False
  Else                                              ' écriture clé
    sectText = reg.Execute(iniText).Item(0).SubMatches(0)
    If Err.Number = 5 Then ' section inconnue
      iniText = iniText & vbCrLf & "[" & section & "]" & vbCrLf & key & "=" & value
    Else
      newSectText = regSub.Replace(sectText,key & "=" & value)
      If newSectText = sectText Then ' pas de remplacement constaté. soit le clé/valeur existe déjà soit c'est une nouvelle clé
        If regSub.Test(sectText) Then ' le couple clé/valeur existe déjà -> sortie
          WriteReadIni = False
          Exit Function
        End If
        If Right(sectText,1) = vbCr Then keyText = key & "=" & value Else keyText = vbCrLf & key & "=" & value
        newSectText = sectText & keyText
      End If
      iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
    End If
    Set oText = oFile.OpenAsTextStream(2,0)
    oText.Write iniText
    oText.Close
    WriteReadIni = True
  End If
End Function


问:
How to access $PORT environment variable in React App on Heroku
I am running a server and a React site on the same Heroku app. My server.js is able to access the $PORT environment variable fine, but my React app is not getting anything from it (the variable is blank).

I need to be able to access the PORT environment variable because thats what my server (Radiks) is running on. From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.

My Procfile:

```<code>web: REACT_APP_PORT=$PORT node src/server.js
</code>```

In package.json:

```<code>...
"scripts": {
    "start": "node server.js",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install && npm run build",
    "build": "REACT_APP_PORT=$PORT react-scripts build",
    "test": "react-scripts build",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
...
</code>```

In my React app (App.js):

```<code>...
console.log("Connected to server:" + process.env.REACT_APP_PORT);
configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession})
...
</code>```

(This ends up only printing out Connected to server:)

Any help would be greatly appreciated, thank you in advance!

答:
From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.

That's new to me. I looked it up and also saw the passage that said this so I'm going to take your word for it.

web: REACT_APP_PORT=$PORT node src/server.js

Seems plausible.

"build": "REACT_APP_PORT=$PORT react-scripts build",

You are building your html, js, css files here. The port is never used. Heroku's $PORT value is dynamic. It changes from time to time. So when you are building your static files it still references a variable instead of a hardcoded value.

configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession}

Should be:

```<code>configure({ apiServer: "http://localhost:" + process.env.PORT || process.env.REACT_APP_PORT || 1260, userSession}
</code>```

Just in case $PORT works I put it in there. If it does not exist it will pick $REACT_APP_PORT.

Your previous code was missing protocol and host.

Body:
I am running a server and a React site on the same Heroku app. My server.js is able to access the $PORT environment variable fine, but my React app is not getting anything from it (the variable is blank).

I need to be able to access the PORT environment variable because thats what my server (Radiks) is running on. From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.

My Procfile:

web: REACT_APP_PORT=$PORT node src/server.js

In package.json:

...
"scripts": {
    "start": "node server.js",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install && npm run build",
    "build": "REACT_APP_PORT=$PORT react-scripts build",
    "test": "react-scripts build",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
...

In my React app (App.js):

...
console.log("Connected to server:" + process.env.REACT_APP_PORT);
configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession})
...

(This ends up only printing out Connected to server:)

Any help would be greatly appreciated, thank you in advance!

Body:
From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.

That's new to me. I looked it up and also saw the passage that said this so I'm going to take your word for it.

web: REACT_APP_PORT=$PORT node src/server.js

Seems plausible.

"build": "REACT_APP_PORT=$PORT react-scripts build",

You are building your html, js, css files here. The port is never used. Heroku's $PORT value is dynamic. It changes from time to time. So when you are building your static files it still references a variable instead of a hardcoded value.

configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession}

Should be:

configure({ apiServer: "http://localhost:" + process.env.PORT || process.env.REACT_APP_PORT || 1260, userSession}

Just in case $PORT works I put it in there. If it does not exist it will pick $REACT_APP_PORT.

Your previous code was missing protocol and host.


问:
Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams?
I have the following sample result when I query a database :

```<code>dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]
</code>```

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

```<code>{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }
</code>```

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

```<code>
    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

</code>```

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

答:
Here's complete example how to do it

```<code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<HashMap<String, String>> input = new ArrayList<>();
        HashMap<String, String> subinput1 = new HashMap<>();
        subinput1.put("name", "name1");
        subinput1.put("rollno", "rollno1");
        input.add(subinput1);
        HashMap<String, String> subinput2 = new HashMap<>();
        subinput2.put("name", "name2");
        subinput2.put("rollno", "rollno2");
        input.add(subinput2);
        HashMap<String, HashMap<String, String>> result = (HashMap<String, HashMap<String, String>>) input.stream()
                .collect(Collectors.toMap(v -> (String) v.get("rollno"), e -> e));
        System.out.println(result);
    }
}
</code>```

It iterates over a collection of HashMaps, takes the key in which it should be stored in the result HashMap, then it creates a Map of Maps where the key is the "rollno" from the input map, and value is the input map itself.

Body:
I have the following sample result when I query a database :

dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

Body:
Here's complete example how to do it

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<HashMap<String, String>> input = new ArrayList<>();
        HashMap<String, String> subinput1 = new HashMap<>();
        subinput1.put("name", "name1");
        subinput1.put("rollno", "rollno1");
        input.add(subinput1);
        HashMap<String, String> subinput2 = new HashMap<>();
        subinput2.put("name", "name2");
        subinput2.put("rollno", "rollno2");
        input.add(subinput2);
        HashMap<String, HashMap<String, String>> result = (HashMap<String, HashMap<String, String>>) input.stream()
                .collect(Collectors.toMap(v -> (String) v.get("rollno"), e -> e));
        System.out.println(result);
    }
}

It iterates over a collection of HashMaps, takes the key in which it should be stored in the result HashMap, then it creates a Map of Maps where the key is the "rollno" from the input map, and value is the input map itself.


问:
ServiceStack Redis Mq: is eventual consistency an issue?
I'm looking at turning a monolith application into a microservice-oriented application and in doing so will need a robust messaging system for interprocesses-communication. The idea is for the microserviceprocesses to be run on a cluster of servers for HA, with requests to be processed to be added on a message queue that all the applications can access. I'm looking at using Redis as both a KV-store for transient data and also as a message broker using the ServiceStack framework for .Net but I worry that the concept of eventual consistency applied by Redis will make processing of the requests unreliable. This is how I understand Redis to function in regards to Mq:

Client 1 posts a request to a queue on node 1

Node 1 will inform all listeners on that queue using pub/sub of the existence of
the request and will also push the requests to node 2 asynchronously.

The listeners on node 1 will pull the request from the node, only 1 of them will obtain it as should be. An update of the removal of the request is sent to node 2 asynchronously but will take some time to arrive.

The initial request is received by node 2 (assuming a bit of a delay in RTT) which will go ahead and inform listeners connected to it using pub/sub. Before the update from node 1 is received regarding the removal of the request from the queue a listener on node 2 may also pull the request. The result being that two listeners ended up processing the same request, which would cause havoc in our system.

Is there anything in Redis or the implementation of ServiceStack Redis Mq that would prevent the scenario described to occur? Or is there something else regarding replication in Redis that I have misunderstood? Or should I abandon the Redis/SS approach for Mq and use something like RabbitMQ instead that I have understood to be ACID-compliant?

答:
It's not possible for the same message to be processed twice in Redis MQ as the message worker pops the message off the Redis List backed MQ and all Redis operations are atomic so no other message worker will have access to the messages that have been removed from the List.

ServiceStack.Redis (which Redis MQ uses) only supports Redis Sentinel for HA which despite Redis supporting multiple replicas they only contain a read only view of the master dataset, so all write operations like List add/remove operations can only happen on the single master instance.

One notable difference from using Redis MQ instead of specific purpose MQ like Rabbit MQ is that Redis doesn't support ACK's, so if the message worker process that pops the message off the MQ crashes then it's message is lost, as opposed to Rabbit MQ where if the stateful connection of an un Ack'd message dies the message is restored by the RabbitMQ server back to the MQ.