问:
Saving Read/Write/Save to json from Struct of Map
I've been trying to have a " working " file to which i save certain basic state of my application instead of having them in Ram since they would need to be saved everyday, i've decided on creating  file per day, this part is working but i've stripped it from the code for more clarity.

Now i'm able to initialise my file with false value for the informations struct and then unmarshalling and reading from it.

The problem arise when i'm trying to update the "file" after it's been unmarshalled before i save it back to the text file.

The isImportStarted does work (when removing the erronous line obv ) but i can't seem to update the file properly i get this error :

```<code>./test.go:62:34: cannot assign to struct field
TheList[symbol].ImportStarted in map
./test.go:71:3: cannot take the address of
TheList[symbol].ImportStarted
./test.go:71:34: cannot assign to &TheList[symbol].ImportStarted
</code>```

My code :

```<code>                package main

                import (
                    "encoding/json"
                    "fmt"
                    "os"
                    "io/ioutil"
                    "log"
                )

                type Informations struct {
                        ImportStarted bool
                        ImportDone bool
                }

                var MyList = map[string]*Informations{
                    "test": &Informations{ImportStarted: false,ImportDone:false},
                    "test2": &Informations{ImportStarted: false,ImportDone:false},
                }

                func ReadFile(filename string) []byte{
                    data, err := ioutil.ReadFile(filename)
                    if err != nil {
                        log.Panicf("failed reading data from file: %s", err)
                    }
                        return data
                }

                func writeFile(json string,filename string){
                        file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
                        defer file.Close()

                        if err != nil {
                            fmt.Println(err)
                        }
                        _,err2 := file.WriteString(json)
                        fmt.Println(err2)
                }

                func main() {
                        isImportStarted("test")
                        ImportStart("test")
                }

                func ImportStart(symbol string){
                  filename := "test.txt"
                    _, err := os.Stat(filename)
                    if err != nil {
                        if os.IsNotExist(err) {
                            fmt.Println("File does not exist creating it...")
                            file, err := os.Create(filename)
                            jsonString, _ := json.Marshal(MyList)
                            writeFile(string(jsonString),filename)
                            if err != nil {
                                fmt.Println(err)
                            }
                            fmt.Println("reading from file"+filename )
                            x := ReadFile(filename)

                            var TheList = map[string]Informations{}
                            json.Unmarshal(x,&TheList )
                            TheList[symbol].ImportStarted = true
                            defer file.Close()
                      //wanting to save afterwards...
                        }
                    } else {
                        fmt.Println("reading from file "+ filename)
                        x := ReadFile(filename)
                        var TheList = map[string]Informations{}
                        json.Unmarshal(x,&TheList )
                        &TheList[symbol].ImportStarted = true
                    }
                }

                func isImportStarted(symbol string) bool{
                    filename := "test.txt"
                    x := ReadFile(filename)
                    var TheList = map[string]Informations{}
                    json.Unmarshal(x,&TheList )
                    return TheList[symbol].ImportStarted
                }
</code>```

I've tried the Why do I get a "cannot assign" error when setting value to a struct as a value in a map? question but it doesn't fit my use case at all as it would effectivly initialize all my structs with nil instead of {false,false}

Any ideas?

答: Try var TheList = map[string]*Informations{}, why you cannot assign a value in a map please refer to why-do-i-get-a-cannot-assing-error or access-struct-in-map-without-copying

Body:
I've been trying to have a " working " file to which i save certain basic state of my application instead of having them in Ram since they would need to be saved everyday, i've decided on creating  file per day, this part is working but i've stripped it from the code for more clarity.

Now i'm able to initialise my file with false value for the informations struct and then unmarshalling and reading from it.

The problem arise when i'm trying to update the "file" after it's been unmarshalled before i save it back to the text file.

The isImportStarted does work (when removing the erronous line obv ) but i can't seem to update the file properly i get this error :

./test.go:62:34: cannot assign to struct field
TheList[symbol].ImportStarted in map
./test.go:71:3: cannot take the address of
TheList[symbol].ImportStarted
./test.go:71:34: cannot assign to &TheList[symbol].ImportStarted

My code :

                package main

                import (
                    "encoding/json"
                    "fmt"
                    "os"
                    "io/ioutil"
                    "log"
                )

                type Informations struct {
                        ImportStarted bool
                        ImportDone bool
                }

                var MyList = map[string]*Informations{
                    "test": &Informations{ImportStarted: false,ImportDone:false},
                    "test2": &Informations{ImportStarted: false,ImportDone:false},
                }

                func ReadFile(filename string) []byte{
                    data, err := ioutil.ReadFile(filename)
                    if err != nil {
                        log.Panicf("failed reading data from file: %s", err)
                    }
                        return data
                }

                func writeFile(json string,filename string){
                        file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
                        defer file.Close()

                        if err != nil {
                            fmt.Println(err)
                        }
                        _,err2 := file.WriteString(json)
                        fmt.Println(err2)
                }

                func main() {
                        isImportStarted("test")
                        ImportStart("test")
                }

                func ImportStart(symbol string){
                  filename := "test.txt"
                    _, err := os.Stat(filename)
                    if err != nil {
                        if os.IsNotExist(err) {
                            fmt.Println("File does not exist creating it...")
                            file, err := os.Create(filename)
                            jsonString, _ := json.Marshal(MyList)
                            writeFile(string(jsonString),filename)
                            if err != nil {
                                fmt.Println(err)
                            }
                            fmt.Println("reading from file"+filename )
                            x := ReadFile(filename)

                            var TheList = map[string]Informations{}
                            json.Unmarshal(x,&TheList )
                            TheList[symbol].ImportStarted = true
                            defer file.Close()
                      //wanting to save afterwards...
                        }
                    } else {
                        fmt.Println("reading from file "+ filename)
                        x := ReadFile(filename)
                        var TheList = map[string]Informations{}
                        json.Unmarshal(x,&TheList )
                        &TheList[symbol].ImportStarted = true
                    }
                }

                func isImportStarted(symbol string) bool{
                    filename := "test.txt"
                    x := ReadFile(filename)
                    var TheList = map[string]Informations{}
                    json.Unmarshal(x,&TheList )
                    return TheList[symbol].ImportStarted
                }

I've tried the Why do I get a "cannot assign" error when setting value to a struct as a value in a map? question but it doesn't fit my use case at all as it would effectivly initialize all my structs with nil instead of {false,false}

Any ideas?


来源: stackexchange

问:
How to get the last changed table if they have the same table name and different table_PK
I want to take the last changed record for multiple TableName and display it only one time.
For some TableName I have multiple Table_Pk, for exp:

```<code>SELECT COUNT(Table_PK), TableName
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
GROUP BY TableName
HAVING COUNT(Table_PK) > 1
</code>```

result looks like:

```<code>Table_PK   TableName
   9       L0L001T03
   2       L0L001T05
   ....
</code>```

and I want to take Table_Pk, TableName once ordered by LastChanged.

Here is the code which I've tried but I get all records

```<code>SELECT  Distinct(Table_PK), TableName, LastChanged
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
ORDER BY LastChanged
</code>```

result is:

```<code>Table_Pk                            TableName            LastChanged
91A5249DB797FF4BB44579AC7D3C0949    L0L003T41             2019-05-29
7070D39FAF65674DA8537B93FFDE2371    L0L003T41             2019-05-28
......
</code>```

I should have 1153 rows but I have 2220

答:
I'm guessing you need below query:</p>

```<code>SELECT * from (
SELECT  Table_PK, TableName, LastChanged, row_numbeR() over(partition by table_pk order by lastchanged desc) as RN FROM TBL_TECTABLES
INNER JOIN sys.tables ON 'TBL_Tec' + Table_PK = name
collate SQL_Latin1_General_CP1_CI_AS WHERE LEN(name) = 39 ) a Where RN = 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to take the last changed record for multiple TableName and display it only one time.
For some TableName I have multiple Table_Pk, for exp:

SELECT COUNT(Table_PK), TableName
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
GROUP BY TableName
HAVING COUNT(Table_PK) > 1

result looks like:

Table_PK   TableName
   9       L0L001T03
   2       L0L001T05
   ....

and I want to take Table_Pk, TableName once ordered by LastChanged.

Here is the code which I've tried but I get all records

SELECT  Distinct(Table_PK), TableName, LastChanged
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
ORDER BY LastChanged

result is:

Table_Pk                            TableName            LastChanged
91A5249DB797FF4BB44579AC7D3C0949    L0L003T41             2019-05-29
7070D39FAF65674DA8537B93FFDE2371    L0L003T41             2019-05-28
......

I should have 1153 rows but I have 2220

Body:
I'm guessing you need below query:

SELECT * from (
SELECT  Table_PK, TableName, LastChanged, row_numbeR() over(partition by table_pk order by lastchanged desc) as RN FROM TBL_TECTABLES
INNER JOIN sys.tables ON 'TBL_Tec' + Table_PK = name
collate SQL_Latin1_General_CP1_CI_AS WHERE LEN(name) = 39 ) a Where RN = 1


问:
set visible false to button using reflection, is posible?
I just trying hide button through relfection.

```<code>Class userClass = Class.forName("vistas.RegistroPersonal");
Field f = userClass.getDeclaredField("btneliminar");
f.setAccessible(true);
f.setVisible(false);
</code>```

is there a way... field does not have setVisible method...

答:
The setVisible() method on a Field does not exist, what you need to do is get a reference on the setVisible(boolean) Method (by its name & parameter types) and then invoke it:

```<code>public static void main(String[] args) throws Exception {
    TestApplication application = new TestApplication();
    Field field = TestApplication.class.getDeclaredField("button1");
    // This will allow us to access the button1 field even if it's private
    field.setAccessible(true);
    Method method = JButton.class.getMethod("setVisible", Boolean.TYPE);

    Object button = field.get(application);
    method.invoke(button, Boolean.FALSE);
}

public static class TestApplication {
    private JButton button1 = new JButton();
}
</code>```

You need an instance of something to start with, if you start with the object owning your button then you can get its button via a Field and then invoke the Method. If you start with a button instance you can call the Method.

Please note that reflection seems like a convoluted way to do things here, the equivalent would be simply:

```<code>    TestApplication application = new TestApplication();
    application.button1.setVisible(false);
</code>```

Body:
I just trying hide button through relfection.

Class userClass = Class.forName("vistas.RegistroPersonal");
Field f = userClass.getDeclaredField("btneliminar");
f.setAccessible(true);
f.setVisible(false);

is there a way... field does not have setVisible method...

Body:
The setVisible() method on a Field does not exist, what you need to do is get a reference on the setVisible(boolean) Method (by its name & parameter types) and then invoke it:

public static void main(String[] args) throws Exception {
    TestApplication application = new TestApplication();
    Field field = TestApplication.class.getDeclaredField("button1");
    // This will allow us to access the button1 field even if it's private
    field.setAccessible(true);
    Method method = JButton.class.getMethod("setVisible", Boolean.TYPE);

    Object button = field.get(application);
    method.invoke(button, Boolean.FALSE);
}

public static class TestApplication {
    private JButton button1 = new JButton();
}

You need an instance of something to start with, if you start with the object owning your button then you can get its button via a Field and then invoke the Method. If you start with a button instance you can call the Method.

Please note that reflection seems like a convoluted way to do things here, the equivalent would be simply:

    TestApplication application = new TestApplication();
    application.button1.setVisible(false);


问:
Receive any Keyboard input and use with Switch statement on Unity
I don't want to use if statement. For simplicity and performance I want to use switch case and execute that method. I want all the keyboard Input to get detected. But is there any method that will pass any key press information?
My current approach is :

```<code>// Update is called once per frame
void Update()
{
    char a = Input.GetKey();//anything like this method?
    switch (a)
    {
        case 'a':
                //print'';
                break;
        case 'b':
                //print'';
                break;
        default:
            break;
    }

}
</code>```

How can I achieve this any key press information detection without if statement?

答:
Best Solution - Use Input.inputString

You may use Input.inputString to catch the keyboard input entered in the last frame as a string.

void Update()
{
    //get the input
    var input = Input.inputString;
    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
        //logic related to the char pressed
        Debug.Log("Pressed char: " + Input.inputString);
}
```

Other solutions

Foreach Loop

You might use foreach loop approach, like suggested in other answers, but it is not as performant. Foreach allocates more memory and must check against all possible keys (it is also less readable).

If you do not care about time and memory performance, then you might follow this answer. It uses the foreach loop approach and create a reusable interface.

OnGUI

Finally you could catch the Event.current (that is a unityGUI Event), like explained in this answer, but doing so you would rely on the OnGUI method.  This method has the worst performance.

Body:
I don't want to use if statement. For simplicity and performance I want to use switch case and execute that method. I want all the keyboard Input to get detected. But is there any method that will pass any key press information?
My current approach is :

// Update is called once per frame
void Update()
{
    char a = Input.GetKey();//anything like this method?
    switch (a)
    {
        case 'a':
                //print'';
                break;
        case 'b':
                //print'';
                break;
        default:
            break;
    }

}

How can I achieve this any key press information detection without if statement?

Body:
Best Solution - Use Input.inputString

You may use Input.inputString to catch the keyboard input entered in the last frame as a string.

void Update()
{
    //get the input
    var input = Input.inputString;
    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
        //logic related to the char pressed
        Debug.Log("Pressed char: " + Input.inputString);
}

Other solutions

Foreach Loop

You might use foreach loop approach, like suggested in other answers, but it is not as performant. Foreach allocates more memory and must check against all possible keys (it is also less readable).

If you do not care about time and memory performance, then you might follow this answer. It uses the foreach loop approach and create a reusable interface.

OnGUI

Finally you could catch the Event.current (that is a unityGUI Event), like explained in this answer, but doing so you would rely on the OnGUI method.  This method has the worst performance.


问:
Is there a way to return an array of structs in Solidity without de-structuring the fields?
I've been doing some research around this issue, but I couldn't find a definite answer. I'm using solidity 0.4.24.

I have a contract like this:

```<code>contract {
    struct FutureOperation is Ownable {
        uint256 date;
        uint256 price;
        uint256 amount;
        string name;
    }

    FutureOperation[] futureOperations;

    // ...

    function getAllFutureOperations() public onlyOwner returns (FutureOperation[]) {
        return futureOperations;
    }
}
</code>```

When I compile this in Remix I get the following error:

```<code>browser/myfuturetoken.sol:53:64: TypeError: This type is only supported in the new experimental ABI encoder. Use "pragma experimental ABIEncoderV2;" to enable the feature.
</code>```

I found some blog posts saying that I should de-structure the fields in the struct to return them as arrays of the primitive types. So, in this case, it would look something like this:

```<code>function getAllFutureOperations() public onlyOwner returns (uint256[] dates, uint256[] prices, uint256[] amounts, string[] names) {
        return futureOperations;
    }
</code>```

Is there an alternative for that? Are the newer compilers capable of returning an array of structs?

Thanks.

答:
As error stated, returning dynamic array is not supported by compiler yet. However, experiment feature supported it. To use experimental compiler, you need to make some changes as follows,

```<code>pragma experimental ABIEncoderV2;

contract myContract{

    struct FutureOperation {
        uint256 date;
        uint256 price;
        uint256 amount;
        string name;
    }

    string[] futureOperations;

    function getAllFutureOperations() public view returns (string[] memory) {
        return futureOperations;
    }

}
</code>```

Note: make sure to not use experimental things in production version

Body:
I've been doing some research around this issue, but I couldn't find a definite answer. I'm using solidity 0.4.24.

I have a contract like this:

contract {
    struct FutureOperation is Ownable {
        uint256 date;
        uint256 price;
        uint256 amount;
        string name;
    }

    FutureOperation[] futureOperations;

    // ...

    function getAllFutureOperations() public onlyOwner returns (FutureOperation[]) {
        return futureOperations;
    }
}

When I compile this in Remix I get the following error:

browser/myfuturetoken.sol:53:64: TypeError: This type is only supported in the new experimental ABI encoder. Use "pragma experimental ABIEncoderV2;" to enable the feature.

I found some blog posts saying that I should de-structure the fields in the struct to return them as arrays of the primitive types. So, in this case, it would look something like this:

function getAllFutureOperations() public onlyOwner returns (uint256[] dates, uint256[] prices, uint256[] amounts, string[] names) {
        return futureOperations;
    }

Is there an alternative for that? Are the newer compilers capable of returning an array of structs?

Thanks.

Body:
As error stated, returning dynamic array is not supported by compiler yet. However, experiment feature supported it. To use experimental compiler, you need to make some changes as follows,

pragma experimental ABIEncoderV2;

contract myContract{

    struct FutureOperation {
        uint256 date;
        uint256 price;
        uint256 amount;
        string name;
    }

    string[] futureOperations;

    function getAllFutureOperations() public view returns (string[] memory) {
        return futureOperations;
    }

}

Note: make sure to not use experimental things in production version


问:
C# MVC Query with WHERE clause and 2 params from the View
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

```<code>select * from myTable where column1=16 and column2=24
</code>```

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

```<code>    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}
</code>```

And in my View I would retrieve the values for my where clause from input fields.
Example:

```<code><input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />
</code>```

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

答:
I'm afraid your code would not compile. What you annotated as your controller does not inherit from controller class at all and your actionresult method has no name. I wonder how could you visit your page in the browser. The code should be like

```<code>public class MyApplicationModel:Controller
{

    //use entity framework
    private MyApplicationEntities entities = new MyApplicationEntities();

    //
    // Method to query database for price lists table
    public IQueryable<pricingUploaded> GetPricingList()
    {
        return entities.pricingUploadeds;
    }

    //
    // Method to query Column1 and Column2 in table pricingUploaded
    [HttpGet]
    public ActionResult Query()
    {
       //this action will render the page the first time
       return View();
    }
    [HttpPost]//this method will only accept posted requests
    public ActionResult Query(int column1, int column2)
    {
         //do something here.
         var _result = entities.Where(x=>x.column1 == column1 && x.column2 == column2);
         return View(_result);//pass result to strongly typed view
    }
</code>```

In your view you have to create a form, that when submitted can post values to HttpPost overload of Query method

```<code><%:Html.BeginForm();%>
<input type="text" name="column1">
<input type="text" name="column2">
<input type="submit" id="save" value="query">
<%:Html.EndForm();%>
</code>```

Now you enter values in your form and click query button, you will have column1 and column2 values in you Query Actionresult accepting posted request. You better put a break point there and inspect how things are really working and figure out how to do what you need to do.

Edit: based on your comment that you want to pass values ajaxically you can do little bit of jQuery:

```<code><script type="text/javascript">
$(function(){
   $("form").submit(function(){
       $.ajax({
              type:"post",
              url:"myapplicationmodel/query",
              success:function(data)
             {
                  //do something with returned data
             }
              });
return false;// to prevent normal form post
  });
});
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

select * from myTable where column1=16 and column2=24

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}

And in my View I would retrieve the values for my where clause from input fields.
Example:

<input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

Body:
I'm afraid your code would not compile. What you annotated as your controller does not inherit from controller class at all and your actionresult method has no name. I wonder how could you visit your page in the browser. The code should be like

public class MyApplicationModel:Controller
{

    //use entity framework
    private MyApplicationEntities entities = new MyApplicationEntities();

    //
    // Method to query database for price lists table
    public IQueryable<pricingUploaded> GetPricingList()
    {
        return entities.pricingUploadeds;
    }

    //
    // Method to query Column1 and Column2 in table pricingUploaded
    [HttpGet]
    public ActionResult Query()
    {
       //this action will render the page the first time
       return View();
    }
    [HttpPost]//this method will only accept posted requests
    public ActionResult Query(int column1, int column2)
    {
         //do something here.
         var _result = entities.Where(x=>x.column1 == column1 && x.column2 == column2);
         return View(_result);//pass result to strongly typed view
    }

In your view you have to create a form, that when submitted can post values to HttpPost overload of Query method

<%:Html.BeginForm();%>
<input type="text" name="column1">
<input type="text" name="column2">
<input type="submit" id="save" value="query">
<%:Html.EndForm();%>

Now you enter values in your form and click query button, you will have column1 and column2 values in you Query Actionresult accepting posted request. You better put a break point there and inspect how things are really working and figure out how to do what you need to do.

Edit: based on your comment that you want to pass values ajaxically you can do little bit of jQuery:

<script type="text/javascript">
$(function(){
   $("form").submit(function(){
       $.ajax({
              type:"post",
              url:"myapplicationmodel/query",
              success:function(data)
             {
                  //do something with returned data
             }
              });
return false;// to prevent normal form post
  });
});
</script>


问:
Setting React children typescript definition breaks parent props type checking
I am trying to work out why setting the children prop for React/JSX components break the type-checking of the parent component.

The simple code example is shown below, if I do not define the children type the top Test fails to show an error on the someOtherProp, if I define the children prop then the second Test component fails to show an error on the someOtherProp, if I make children optional, then it fails on both components.

```<code>import React from 'react';

export interface TestProps {
  style: {
    flex?: number;
  };
  children: React.ReactNode;
}

const Test = ({ style }: TestProps) => <div style={style} />;

export const MainTest = () => (
  <>
    <Test style={{ flex: 1, someOtherProp: 'center' }} />;
    <Test style={{ flex: 1, someOtherProp: 'center' }}>
      <p>Children Breaks TypeChecking</p>
    </Test>
  </>
);
</code>```

答: This seems to have been fixed upgrading from typescript version 3.4.5 to 3.5.1.</p>

Body:
I am trying to work out why setting the children prop for React/JSX components break the type-checking of the parent component.

The simple code example is shown below, if I do not define the children type the top Test fails to show an error on the someOtherProp, if I define the children prop then the second Test component fails to show an error on the someOtherProp, if I make children optional, then it fails on both components.

import React from 'react';

export interface TestProps {
  style: {
    flex?: number;
  };
  children: React.ReactNode;
}

const Test = ({ style }: TestProps) =>
;

export const MainTest = () => (
  <>
    <Test style={{ flex: 1, someOtherProp: 'center' }} />;
    <Test style={{ flex: 1, someOtherProp: 'center' }}>

Children Breaks TypeChecking

    </Test>
  </>
);


问:
How can I perform a "Group By" query directly or indirectly on Cosmos DB?
I have a Cosmos DB collection with 4 millions items.
My main problem is how I can perform a 'group by' query on it.

For now I export it to json.gz blob storage. Convert it to a local CSV file from a local C# program. Then run a simple R script on it that performs that group by.

I would like to run the whole process in Azure (using a Azure Logic App).

What would be the best way to do that?

Thank you!

答:
For .NET and Node.js

Larry Maccherone has provided a great package documentdb-lumenize which supports Aggregations (Group-by, Pivot-table, and N-dimensional Cube) and Time Series Transformations as Stored Procedures in DocumentDB.
Additionally, for Python and Scala, you could refer to azure-cosmosdb-spark.

You can refer this thread.

Hope it helps.


问:
Can I pass custom data in the HTTP header?
I have a whole bunch of web services each with several web methods. The consumers of these services are varied and many. I want to augment each of these web methods with an extra optional parameter (Int64 or Int32) but adding new methods with this extra (optional parameter) is a lot of work and getting the clients to use the new methods will be even more time consuming.

So I was wondering if I could allow the clients that wanted to take advantage of the new feature that this param provides could pass this Int in the HTTP header or some other way.

So the first question is can I pass an int in the HTTP header? If so, how would one do that in C#/ASP.NET?

Otherwise, what other suggestions do you have for tackling this problem?

答:
```<code>Request.Headers.Add("headername", "headervalue");
Response.Headers.Add("headername", "headervalue");
</code>```

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Demi


问:
How can I use `git diff --color-words` outside a Git repository?
How can I get output like in  git diff --color-words, but outside Git?

Closest thing is wdiff  -t, but it underlines/inverts things instead of using green/red colours and does not allow specifying my whitespace regex.

答: you can say git diff --color=always --color-words, which will give you the color escape codes in the output. you are going to have some shell to interpret the color codes though …


问:
Kubernetes Cron Jobs - Run multiple pods for a cron job
Our requirement is we need to do batch processing every 3 hours but single process can not handle the work load. we have to run multiple pods for the same cron job. Is there any way to do that ?

Thank you.

答:
You can provide parallelism: <num_of_pods> to cronjob.spec.jobTemplate.spec and it will run the multiple pods () at the same time.

Following is the example of a cronjob which runs 3 nginx pod every minute.

```<code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
  creationTimestamp: null
  labels:
    run: cron1
  name: cron1
spec:
  concurrencyPolicy: Allow
  jobTemplate:
    metadata:
      creationTimestamp: null
    spec:
      parallelism: 3
      template:
        metadata:
          creationTimestamp: null
          labels:
            run: cron1
        spec:
          containers:
          - image: nginx
            name: cron1
            resources: {}
          restartPolicy: OnFailure
  schedule: '*/1 * * * *'
  concurrencyPolicy: Forbid
status: {}
</code>```

Body:
You can provide parallelism: <num_of_pods> to cronjob.spec.jobTemplate.spec and it will run the multiple pods () at the same time.

Following is the example of a cronjob which runs 3 nginx pod every minute.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  creationTimestamp: null
  labels:
    run: cron1
  name: cron1
spec:
  concurrencyPolicy: Allow
  jobTemplate:
    metadata:
      creationTimestamp: null
    spec:
      parallelism: 3
      template:
        metadata:
          creationTimestamp: null
          labels:
            run: cron1
        spec:
          containers:
          - image: nginx
            name: cron1
            resources: {}
          restartPolicy: OnFailure
  schedule: '*/1 * * * *'
  concurrencyPolicy: Forbid
status: {}


问:
Editor template for DropDownList, can't bind property from View to template
I have editor template for DropDownList

```<code>@model object
<div class='form-fields @ViewData["class"]'>
@Html.LabelFor(x => x, new { @class = "form-fields__label" })
@Html.DropDownListFor(x => x, (SelectList)ViewData["selectList"], new { @class = "form-fields__input width-max d-block " + @ViewData["inputClass"]})
@Html.ValidationMessageFor(x => x, "", new { @class = "form-fields__form-error" })
</code>```

And I am reading List data from View, using ViewData, but I am getting error that System.String doesn't have property 'P' (that is my status). I think this is happening because when data come to my template, he is reading only value, not property. Is there any workaround for this?

View

```<code>@Html.EditorFor(x => x.AdminForEdit.Status.Status, "DropDownList", new { selectList = new SelectList(MDC.Models.Accounts.UserStatus.GetStatuses(), Model.AdminForEdit.Status.Status, NinjectWebCommon.Dictionary.GetLocalization(Model.Device.Language.LanguageId, Model.AdminForEdit.Status.Name), Model.AdminForEdit.Status.Status)})
</code>```

UserStatus class

```<code>public class UserStatus
{
    public string Status { get; set; }
    public string Name { get; set; }
    public bool AlowLogIn { get; set; }
    public string ErrorMessage { get; set; }

    public UserStatus()
    {

    }

    public UserStatus(string status, string name, bool alowLogin, string errorMessage)
    {
        Status = status;
        Name = name;
        AlowLogIn = alowLogin;
        ErrorMessage = errorMessage;
    }

    public static UserStatus Pending = new UserStatus("P", "L_USERSTATUS_PENDING", false, "L_ADMIN_LOGIN_ERRORUSERPENDING");

    public static UserStatus Active = new UserStatus("A", "L_USERSTATUS_ACTIVE", true, "L_ADMIN_LOGIN_WRONGCREDENTIALS");

    public static UserStatus Blocked = new UserStatus("B", "L_USERSTATUS_BLOCKED", false, "L_ADMIN_LOGIN_ERRORUSERBLOCKED");

    public static UserStatus Deleted = new UserStatus("D", "L_USERSTATUS_DELETED", false, "L_ADMIN_LOGIN_ERRORUSERBLOCKED");

    public static UserStatus Unknown = new UserStatus("X", "L_USERSTATUS_UNKNOWN", false, "L_ADMIN_LOGIN_ERRORUSERBLOCKED");

    public static List<UserStatus> GetStatuses()
    {
        return new List<UserStatus> { Pending, Active, Blocked, Deleted };
    }

    public static UserStatus GetStatus(string status)
    {
        switch (status)
        {
            case "P":
                return Pending;
            case "A":
                return Active;
            case "B":
                return Blocked;
            case "D":
                return Deleted;
            default:
                return Unknown;
        }
    }
}
</code>```

答:
So, as @vikscool stated, I fixed this problem by using (IEnumerable<SelectListItem>)ViewData["selectList"] in my template,
and in view, I am selecting item like this:

```<code>@Html.EditorFor(x => x.AdminForEdit.Status.Status, "DropDownList", new { selectList = MDC.Models.Accounts.UserStatus.GetStatuses().Select(x => new SelectListItem()
                           {
                                Text = NinjectWebCommon.Dictionary.GetLocalization(Model.Device.Language.LanguageId, x.Name),
                                Value = x.Status
                           }) })
</code>```

Body:
I have editor template for DropDownList

@model object

@Html.LabelFor(x => x, new { @class = "form-fields__label" })
@Html.DropDownListFor(x => x, (SelectList)ViewData["selectList"], new { @class = "form-fields__input width-max d-block " + @ViewData["inputClass"]})
@Html.ValidationMessageFor(x => x, "", new { @class = "form-fields__form-error" })

And I am reading List data from View, using ViewData, but I am getting error that System.String doesn't have property 'P' (that is my status). I think this is happening because when data come to my template, he is reading only value, not property. Is there any workaround for this?

View

@Html.EditorFor(x => x.AdminForEdit.Status.Status, "DropDownList", new { selectList = new SelectList(MDC.Models.Accounts.UserStatus.GetStatuses(), Model.AdminForEdit.Status.Status, NinjectWebCommon.Dictionary.GetLocalization(Model.Device.Language.LanguageId, Model.AdminForEdit.Status.Name), Model.AdminForEdit.Status.Status)})

UserStatus class

public class UserStatus
{
    public string Status { get; set; }
    public string Name { get; set; }
    public bool AlowLogIn { get; set; }
    public string ErrorMessage { get; set; }

    public UserStatus()
    {

    }

    public UserStatus(string status, string name, bool alowLogin, string errorMessage)
    {
        Status = status;
        Name = name;
        AlowLogIn = alowLogin;
        ErrorMessage = errorMessage;
    }

    public static UserStatus Pending = new UserStatus("P", "L_USERSTATUS_PENDING", false, "L_ADMIN_LOGIN_ERRORUSERPENDING");

    public static UserStatus Active = new UserStatus("A", "L_USERSTATUS_ACTIVE", true, "L_ADMIN_LOGIN_WRONGCREDENTIALS");

    public static UserStatus Blocked = new UserStatus("B", "L_USERSTATUS_BLOCKED", false, "L_ADMIN_LOGIN_ERRORUSERBLOCKED");

    public static UserStatus Deleted = new UserStatus("D", "L_USERSTATUS_DELETED", false, "L_ADMIN_LOGIN_ERRORUSERBLOCKED");

    public static UserStatus Unknown = new UserStatus("X", "L_USERSTATUS_UNKNOWN", false, "L_ADMIN_LOGIN_ERRORUSERBLOCKED");

    public static List<UserStatus> GetStatuses()
    {
        return new List<UserStatus> { Pending, Active, Blocked, Deleted };
    }

    public static UserStatus GetStatus(string status)
    {
        switch (status)
        {
            case "P":
                return Pending;
            case "A":
                return Active;
            case "B":
                return Blocked;
            case "D":
                return Deleted;
            default:
                return Unknown;
        }
    }
}

Body:
So, as @vikscool stated, I fixed this problem by using (IEnumerable<SelectListItem>)ViewData["selectList"] in my template,
and in view, I am selecting item like this:

@Html.EditorFor(x => x.AdminForEdit.Status.Status, "DropDownList", new { selectList = MDC.Models.Accounts.UserStatus.GetStatuses().Select(x => new SelectListItem()
                           {
                                Text = NinjectWebCommon.Dictionary.GetLocalization(Model.Device.Language.LanguageId, x.Name),
                                Value = x.Status
                           }) })


问:
Get Action and Action Parameters in Controller.OnException
We're using the OnException virtual method in BaseController to log our exception.

But how can we get the controller action and parameters that the exception originated from?

答:
As far as Action Parameters go, you will need to pass them explicitly.

We don't provide the action arguments on ExceptionContext because it would most often be empty.

Source: https://github.com/aspnet/Mvc/issues/6154

Which is stupid IMO.

UPDATE: You could have your error handler class implement ActionFilterAttribute, which implements:

public virtual void OnActionExecuting(ActionExecutingContext filterContext)

where filterContext.ActionParameters are what you are looking for.


问:
Docker command/option to display or list the build context
Is there a command/option to display or list the context which is sent to the Docker daemon for building an image?

```<code>$ docker build -t "image-name"
Sending build context to Docker daemon 8.499 MB
...
</code>```

Files and directories can be excluded from the build context by specifying patterns in a .dockerignore file. I guess what I'm looking for amounts to testing the .dockerignore in addition to any other niche rules Docker uses when determined the context.

答:
Answers above are great, but there is a low-tech solution for most cases - ncdu. This utility will show pretty and interactive tree structure with sizes. It has an option that will take patterns from a file and exclude them from scan. So you can just do ncdu -X .dockerignore. You will get something like this:

This is pretty close to what you will get in your docker image. One caveat is thou if you add a dot directory (like .yarn) into an image, it will not show in ncdu output.

Body:
Is there a command/option to display or list the context which is sent to the Docker daemon for building an image?

$ docker build -t "image-name"
Sending build context to Docker daemon 8.499 MB
...

Files and directories can be excluded from the build context by specifying patterns in a .dockerignore file. I guess what I'm looking for amounts to testing the .dockerignore in addition to any other niche rules Docker uses when determined the context.


问:
How can I make the Eclipse Python debugger more reliable?
I've found that under some circumstances the Eclipse python debugger can be unreliable. For example, when stepping through a memory-hungry Python program I've found that after a certain point the debugger fails to respond. The entire process hangs with 100% cpu load.

I've heard (unconfirmed) reports from developers that when this occurs it might actually not be a hang but very slow, for example a step which usually takes a micro-second might be taking five minutes.

I've observed this with both the regular eclipse debugger (e.g. when you do debug as->python run) and the pydev network debugger. The point at which things stop working seems quite arbitrary but re-producable. I'm debugging purely numerical functions so there's no obvious socket or tcp activity which could disrupt a network debugger. Nevertheless, the point at which the failure occurs seems to be quite consistent for a given workstation & task.

I get almost exactly the same effect whether I debug using debug as->python run as I might if I use the pydev's network debugger ('import pydevd;pydevd.settrace()') - where one fails the other is also likely to fail.

If I were to run the script normally (no debugger) it executes without any hangs. Furthermore, if I replace the eclipse debugger with the old-skool inline break-point ('import pdb;pdb.set_trace()') everything works just fine. Pdb almost never goes wrong, however there are times I simply cannot use it, for example when I am debugging a python function invoked from Excel - as there is no console present.

I've noticed that this failure never seems to occur with trivial programs, hence I've tentatively concluded that the fault may be memory related.

So - is anybody aware of what might be causing this unreliability. Are there any tweaks  I can make to the debugger or environment that might make the debugger work more reliably?

FYI, running Python 2.4.4 on Windows XP 32bit with the latest Eclipse & Pydev. Psyco (JIT Compiler) is not available.

答: Not sure if its related, but I had a scenario where too many debug messages will cause my PC to become very slow. You can try go to Window -> Preferences -> Run/Debug -> Console... tick Limit console output, and reduce Console buffer size (mine is set to 40000).</p>


问:
Handle setOnClickListener and setOnLongClickListener in Kotlin adapter
I'm trying to use setOnClickListener and setOnLongClickListener in adapter to pass the click to the activity. I've searched a lot of and I only found some examples of how to do one clicklistener but not handle both at the same time.

How can I handle both listeners in the activity?

ADAPTER

```<code>class BrowserAdapter(private val voucherList: List<String>?, private val listener: (String) -> Unit) : RecyclerView.Adapter<BrowserAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(inflate(parent.context, R.layout.item_web, parent, false))
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(voucherList!![position], listener)
    }

    override fun getItemCount(): Int {
        return voucherList!!.size
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(urlData: String, listener: (String) -> Unit) = with(itemView) {
            tx_url.text = urlData

            itemView.setOnClickListener{
                listener(urlData)
            }

            itemView.setOnLongClickListener{
                listener(urlData)
                true
            }
        }
    }
}
</code>```

ACTIVITY

```<code> rv_web_items.adapter = BrowserAdapter(Preferences.getFavouritesWebsites()) {
            presenter.onItemClick(it)
        }
</code>```

答:
I will suggest you to add listeners at onBindViewHolder like this:

```<code>holder.itemView.setOnClickListener {
        }
</code>```

and also long click:

```<code>holder.itemView.setOnLongClickListener { true  }
</code>```

and what about sending data to activity. First step - create interface:

```<code>interface Click {
    fun sendData(..., position: Int, ...) // it is only example
}
</code>```

the the second step use it at your adapter:

```<code>open class Adapter(..., ..., private val click: Click)
</code>```

then handle click and send data:

```<code>holder.itemView.setOnClickListener {
            click.sendData(your_data)
        }
</code>```

then in activity you have to declare this interface:

```<code> val adapter = Adapter(..., ..., this@YourActivity)
</code>```

function for getting data in your activity:

```<code>override fun sendData(your_data) {
    }
</code>```

and also don't forget to implement this interface:

```<code>class JobsList : ..., ..., Click
</code>```

I hope it will help you. Good Luck :)

Body:
I'm trying to use setOnClickListener and setOnLongClickListener in adapter to pass the click to the activity. I've searched a lot of and I only found some examples of how to do one clicklistener but not handle both at the same time.

How can I handle both listeners in the activity?

ADAPTER

class BrowserAdapter(private val voucherList: List<String>?, private val listener: (String) -> Unit) : RecyclerView.Adapter<BrowserAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(inflate(parent.context, R.layout.item_web, parent, false))
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(voucherList!![position], listener)
    }

    override fun getItemCount(): Int {
        return voucherList!!.size
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(urlData: String, listener: (String) -> Unit) = with(itemView) {
            tx_url.text = urlData

            itemView.setOnClickListener{
                listener(urlData)
            }

            itemView.setOnLongClickListener{
                listener(urlData)
                true
            }
        }
    }
}

ACTIVITY

 rv_web_items.adapter = BrowserAdapter(Preferences.getFavouritesWebsites()) {
            presenter.onItemClick(it)
        }

Body:
I will suggest you to add listeners at onBindViewHolder like this:

holder.itemView.setOnClickListener {
        }

and also long click:

holder.itemView.setOnLongClickListener { true  }

and what about sending data to activity. First step - create interface:

interface Click {
    fun sendData(..., position: Int, ...) // it is only example
}

the the second step use it at your adapter:

open class Adapter(..., ..., private val click: Click)

then handle click and send data:

holder.itemView.setOnClickListener {
            click.sendData(your_data)
        }

then in activity you have to declare this interface:

 val adapter = Adapter(..., ..., this@YourActivity)

function for getting data in your activity:

override fun sendData(your_data) {
    }

and also don't forget to implement this interface:

class JobsList : ..., ..., Click

I hope it will help you. Good Luck :)


问:
AJAX to call java method
There are many similar questions but I am not clear about one thing as mentioned below-

I have ajax call

```<code>var url = '/test/testjsp.do?param1=' + xyz;
$.ajax({
                    type:'GET',
                    dataType:'html',
                    url:url,
                    success:function (data) {
                        alert("Success");
                    }
                });
</code>```

which is calling an JSP page
and in that file, I am calling method from SM class

```<code><%@ page import="com.testAjax.SM" %>

<%

    if (null != request.getParameter("
        SM.randomMethod(request.getParameter("param1"));
    }
%>
</code>```

So my question is ,

I there any alternative method where I don't have to create extra Jsp file and call java method directly from Ajax call

Please help and Advise

答:
As javascript is a client side script, it cannot invoke java methods directly which resides on the server.

To do that you have to create a web service or jsp like you did.

But I have seen vaadin gives option to call java code from javascript without writing a service or jsp. I dont know how it will help you.

https://vaadin.com/tutorials/calling-java-from-javascript

There are some concept like java adaptors and javavm to combine javascript and java try them to find it suits your need.

Title: AJAX to call java method

Body:
There are many similar questions but I am not clear about one thing as mentioned below-

I have ajax call

var url = '/test/testjsp.do?param1=' + xyz;
$.ajax({
                    type:'GET',
                    dataType:'html',
                    url:url,
                    success:function (data) {
                        alert("Success");
                    }
                });

which is calling an JSP page
and in that file, I am calling method from SM class

<%@ page import="com.testAjax.SM" %>

<%

    if (null != request.getParameter("
        SM.randomMethod(request.getParameter("param1"));
    }
%>

So my question is ,

I there any alternative method where I don't have to create extra Jsp file and call java method directly from Ajax call

Please help and Advise


问:
How to find big-0 of a nested loop
I assume "length" is my N. When I calculate my inner loop, second while loop, I get 3i+1. But when we calculate big-o, it should be N based. My professor gives 3i+1 = 3/2n^2-1/2n. But he didn't show me the procedure. </p>

```<code>int dup_chk(int a[], int length) {
    int i = length;
    while (i > 0) {
         i--;
         int j = i - 1;
         while (j >= 0) {
             if (a[i] == a[j]) {
                 return 1;
             }
             j--;
        }
    }
    return 0;
}
</code>```

答:
Second while loop runs J times , with

```<code>if condition O(1) + j-- O(1)
</code>```

Whereas return will run only once when O(1)

this is : 2J+1

Title: How to find big-0 of a nested loop

Body:
I assume "length" is my N. When I calculate my inner loop, second while loop, I get 3i+1. But when we calculate big-o, it should be N based. My professor gives 3i+1 = 3/2n^2-1/2n. But he didn't show me the procedure.

int dup_chk(int a[], int length) {
    int i = length;
    while (i > 0) {
         i--;
         int j = i - 1;
         while (j >= 0) {
             if (a[i] == a[j]) {
                 return 1;
             }
             j--;
        }
    }
    return 0;
}

Body:
Second while loop runs J times , with

if condition O(1) + j-- O(1)

Whereas return will run only once when O(1)

this is : 2J+1


问:
How to select a nonblank date
In power BI, I am computing the percentage difference between Stock price index levels over the last year.

```<code> Ann pch =

VAR __EarliestValue =   CALCULATE(SUM('Equity Markets (2)'[Value]),
                         DATEADD(LASTDATE('Calendar'[Date]),-1,YEAR))

VAR __LastDateValue = CALCULATE(SUM('Equity Markets (2)'[Value]),
                        LASTDATE('Calendar'[Date]))

RETURN
CALCULATE(
    DIVIDE(__LastDateValue,__EarliestValue) -1)
</code>```

The above is correct but there is a bug: some dates fall on the weekend, or other non-trading days, in which case I want to select the next nonblank value for __EarliestValue and the previous nonblank value in the case of __LastDateValue.

Could anyone suggest the code to implement this.

I am very much a DAX/Power BI novice. Thank you very much.

Data Sample:

答:
I created a slicer based on the column 'Equity Markets(2)'[Date].

note: Do not make the slicer on your calendar date, then you get your "holes"

Then I created a measure with following formula:

```<code>Measure = LOOKUPVALUE(EquityMarkets[Value];EquityMarkets[Date]; MAX(EquityMarkets[Date]))/ LOOKUPVALUE(EquityMarkets[Value];EquityMarkets[Date]; MIN(EquityMarkets[Date]))
</code>```

This measure I show in the card visual. The result is when using the slicer, the calculation is made.

Title: How to select a nonblank date

Body:
In power BI, I am computing the percentage difference between Stock price index levels over the last year.

 Ann pch =

VAR __EarliestValue =   CALCULATE(SUM('Equity Markets (2)'[Value]),
                         DATEADD(LASTDATE('Calendar'[Date]),-1,YEAR))

VAR __LastDateValue = CALCULATE(SUM('Equity Markets (2)'[Value]),
                        LASTDATE('Calendar'[Date]))

RETURN
CALCULATE(
    DIVIDE(__LastDateValue,__EarliestValue) -1)

The above is correct but there is a bug: some dates fall on the weekend, or other non-trading days, in which case I want to select the next nonblank value for __EarliestValue and the previous nonblank value in the case of __LastDateValue.

Could anyone suggest the code to implement this.

I am very much a DAX/Power BI novice. Thank you very much.

Data Sample:

Body:
I created a slicer based on the column 'Equity Markets(2)'[Date].

note: Do not make the slicer on your calendar date, then you get your "holes"

Then I created a measure with following formula:

Measure = LOOKUPVALUE(EquityMarkets[Value];EquityMarkets[Date]; MAX(EquityMarkets[Date]))/ LOOKUPVALUE(EquityMarkets[Value];EquityMarkets[Date]; MIN(EquityMarkets[Date]))

This measure I show in the card visual. The result is when using the slicer, the calculation is made.


问:
How to equally space empty divs with CSS only in flex?
So I have a structure pretty similar to the snippet below.
The issue I have is that I am trying to make it so that the divs such as child always take the same height relative to the container even if they are empty. So if there are two children they have to be 50% of the parent if there are three children 33.3% of the parent and ec.
Did a lot of digging, tried usingflex-grow and setting it on the children, adding an after content on the childContent class if it was empty but the empty children still collapse.
Is it even possible to achieve equal heights on the children without using js and fixed heights and if yes how?

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: auto;
}

.child {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.childHeader {
  display: flex;
  flex-direction: row;
}

.headerItem {
  background-color: red;
}

.childContent {
  background-color: white;
}

.childContent:empty:after {
  content: '.';
  visibility: hidden;
  min-height: 300px;
}

.contentItem {
  background-color: skyblue;
  border: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
      <div class="contentItem">1</div>
      <div class="contentItem">2</div>
      <div class="contentItem">3</div>
      <div class="contentItem">4</div>
      <div class="contentItem">5</div>
      <div class="contentItem">6</div>
      <div class="contentItem">7</div>
    </div>
  </div>
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
    </div>
  </div>
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
    </div>
  </div>
</div></code>```

答:
Check this out, I'm not really sure if this is what you want to do.

 I just added min-height: calc(100vh - 60px); in your .childContent

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: auto;
}

.child {
  display: flex;
  flex-direction: column;
}

.childHeader {
  display: flex;
  flex-direction: row;
}

.headerItem {
  display:flex;
  flex-basis:100%;
  background-color: red;
}

.childContent {
  background-color: grey;
  position: relative;
  display: block;
  min-height: calc(80vh - 60px);
}

.childContent:empty::after {
  content: '.';
  visibility: hidden;

}

.contentItem {
  background-color: skyblue;
  border: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
      <div class="contentItem">1</div>
      <div class="contentItem">2</div>
      <div class="contentItem">3</div>
      <div class="contentItem">4</div>
      <div class="contentItem">5</div>
      <div class="contentItem">6</div>
      <div class="contentItem">7</div>
    </div>
  </div>
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
    </div>
  </div>
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
    </div>
  </div>
</div></code>```

Check this one out https://developer.mozilla.org/en-US/docs/Web/CSS/calc

Body:
So I have a structure pretty similar to the snippet below.
The issue I have is that I am trying to make it so that the divs such as child always take the same height relative to the container even if they are empty. So if there are two children they have to be 50% of the parent if there are three children 33.3% of the parent and ec.
Did a lot of digging, tried usingflex-grow and setting it on the children, adding an after content on the childContent class if it was empty but the empty children still collapse.
Is it even possible to achieve equal heights on the children without using js and fixed heights and if yes how?

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: auto;
}

.child {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.childHeader {
  display: flex;
  flex-direction: row;
}

.headerItem {
  background-color: red;
}

.childContent {
  background-color: white;
}

.childContent:empty:after {
  content: '.';
  visibility: hidden;
  min-height: 300px;
}

.contentItem {
  background-color: skyblue;
  border: 3px solid black;
}

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

4

5

6

7

Body:
Check this out, I'm not really sure if this is what you want to do.

 I just added min-height: calc(100vh - 60px); in your .childContent

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: auto;
}

.child {
  display: flex;
  flex-direction: column;
}

.childHeader {
  display: flex;
  flex-direction: row;
}

.headerItem {
  display:flex;
  flex-basis:100%;
  background-color: red;
}

.childContent {
  background-color: grey;
  position: relative;
  display: block;
  min-height: calc(80vh - 60px);
}

.childContent:empty::after {
  content: '.';
  visibility: hidden;

}

.contentItem {
  background-color: skyblue;
  border: 3px solid black;
}

<div class="container">
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
      <div class="contentItem">1</div>
      <div class="contentItem">2</div>
      <div class="contentItem">3</div>
      <div class="contentItem">4</div>
      <div class="contentItem">5</div>
      <div class="contentItem">6</div>
      <div class="contentItem">7</div>
    </div>
  </div>
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
    </div>
  </div>
  <div class="child">
    <div class="childHeader">
      <div class="headerItem">1</div>
      <div class="headerItem">2</div>
      <div class="headerItem">3</div>
      <div class="headerItem">4</div>
      <div class="headerItem">5</div>
      <div class="headerItem">6</div>
      <div class="headerItem">7</div>
    </div>
    <div class="childContent">
    </div>
  </div>
</div>

Check this one out https://developer.mozilla.org/en-US/docs/Web/CSS/calc


问:
when page refresh "404 - File or directory not found."
my react app is working locally but after the deploy, I faced the problem when I press any button there is no problem but if I want to refresh I see that problem "404 - File or directory not found."

I found this solution:
https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md#browserhistory

Configure Your Server

"Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /accounts/23 your web server will get a request to /accounts/23. You will need it to handle that URL and include your JavaScript application in the response."

But I don't know how can I do this
I try something but it doesn't work

答:
Since the server cannot find the static content in the directory (i.e. not found the file /tomcat/accounts/23), it will give you 404 unless you have additional route handling.

In React routing I think you can try with HashRouter

See more details here:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/HashRouter.md

HashRouter vs BrowserRouter


问:
No matching function for call to 'std::basic_ofstream<char>::write(std::string*, long long unsigned int)'
So I was playing around a bit with file ofstream and ifstream and got stuck into a compiler problem that I just simply don't know what it means...

Let's start.

I have the following class:

```<code>class FS{
    public:
        string name;
        long long int size;
        long long int freeBlocks;
        long long int usedBlocks = 0;
        int blocksize = 128;
        vector<FS_File> file_list;
        char * ptr;                      //This is a malloc pointer
        void saveTo(ofstream& of);
        void openFrom(ifstream& inf);
    };
</code>```

The problem occurs in the saveTo() function:

```<code>void FS::saveTo(ofstream& of){
  of.write(&name, sizeof(name));
  of.write(&size, sizeof(size));
  of.write(&freeBlocks, sizeof(freeBlocks));
  of.write(&usedBlocks, sizeof(usedBlocks));
  of.write(&blocksize, sizeof(blocksize));
  of.write(&file_list, sizeof(file_list));
  of.write((char *)&ptr, sizeof(ptr));
}
</code>```

The compiler gives me the next error:

```<code>functions.cpp   In member function 'void FS::saveTo(std::ofstream&)':

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(std::string*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(std::vector<FS_File>*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(std::string*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(std::vector<FS_File>*, long long unsigned int)'
</code>```

Whenever I try to call the next code:

```<code>ofstream outfile;
string filename = curFS.name + ".dat";
outfile.open(filename, ios::binary | ios::out);
curFS.save(outfile);
outfile.close();
</code>```

I've tried a few things, but nothing has worked...

What does the compiler error means?
How can I solve it?

答:
The error messages are self explanatory. std::ifstream and std::ofstream are streams of char data, but you are trying to read/write data using pointers to non-char types. There are no overloads of the write() and read() methods for non-char pointers.

For POD types, you can simply type cast your pointers to char*.

That won't work for non-POD types, like std::string and std::vector. For those types, you need to marshal the data instead.

Try something more like this instead:

```<code>void FS::saveTo(ofstream& of)
{
    // std::string needs to be marshaled...
    size_t value = name.size();
    of.write(reinterpret_cast<char*>(&value), sizeof(value));
    of.write(name.c_str(), value);

    // POD types can be written as-is...
    of.write(reinterpret_cast<char*>(&size), sizeof(size));
    of.write(reinterpret_cast<char*>(&freeBlocks), sizeof(freeBlocks));
    of.write(reinterpret_cast<char*>(&usedBlocks), sizeof(usedBlocks));
    of.write(reinterpret_cast<char*>(&blocksize), sizeof(blocksize));

    // std::vector needs to be marshaled...
    value = file_list.size();
    of.write(reinterpret_cast<char*>(&value), sizeof(value));
    for (size_t i = 0; i < value; ++i) {
        // write file_list[i] to the stream as needed...
    }

    // dynamic data needs to be marshaled...
    value = strlen(ptr); // or whatever the actual allocated size is...
    of.write(reinterpret_cast<char*>(&value), sizeof(value));
    of.write(ptr, value);
}

void FS::openFrom(ifstream& inf)
{
    size_t value;

    // std::string needs to be marshaled...
    inf.read(reinterpret_cast<char*>(&value), sizeof(value));
    name.resize(value);
    inf.read(&name[0], value);

    // POD types can be read as-is...
    inf.read(reinterpret_cast<char*>(&size), sizeof(size));
    inf.read(reinterpret_cast<char*>(&freeBlocks), sizeof(freeBlocks));
    inf.read(reinterpret_cast<char*>(&usedBlocks), sizeof(usedBlocks));
    inf.read(reinterpret_cast<char*>(&blocksize), sizeof(blocksize));

    // std::vector needs to be marshaled...
    inf.read(reinterpret_cast<char*>(&value), sizeof(value));
    file_list.resize(value);
    for (size_t i = 0; i < value; ++i) {
        // read file_list[i] from stream as needed...
    }

    // dynamic data needs to be marshaled...
    inf.read(reinterpret_cast<char*>(&value), sizeof(value));
    free(ptr);
    ptr = (char*) malloc(value+1);
    inf.read(ptr, value);
    ptr[value] = '\0';
}
</code>```

Just be sure to always open the streams with the std::ios_base::binary flag enabled. To help ensure that, I would suggest passing the filename to saveTo()/openFrom() instead of user-supplied streams:

```<code>void FS::saveTo(const string& filename)
{
    ofstream outfile(filename, ios::binary);
    saveTo(outfile);
}

void FS::openFrom(const string& filename)
{
    ifstream infile(filename, ios::binary);
    openFrom(infile);
}
</code>```

```<code>curFS.saveTo(curFS.name + ".dat");
</code>```

```<code>curFS.openFrom(curFS.name + ".dat");
</code>```

Body:
So I was playing around a bit with file ofstream and ifstream and got stuck into a compiler problem that I just simply don't know what it means...

Let's start.

I have the following class:

class FS{
    public:
        string name;
        long long int size;
        long long int freeBlocks;
        long long int usedBlocks = 0;
        int blocksize = 128;
        vector<FS_File> file_list;
        char * ptr;                      //This is a malloc pointer
        void saveTo(ofstream& of);
        void openFrom(ifstream& inf);
    };

The problem occurs in the saveTo() function:

void FS::saveTo(ofstream& of){
  of.write(&name, sizeof(name));
  of.write(&size, sizeof(size));
  of.write(&freeBlocks, sizeof(freeBlocks));
  of.write(&usedBlocks, sizeof(usedBlocks));
  of.write(&blocksize, sizeof(blocksize));
  of.write(&file_list, sizeof(file_list));
  of.write((char *)&ptr, sizeof(ptr));
}

The compiler gives me the next error:

functions.cpp   In member function 'void FS::saveTo(std::ofstream&)':

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(std::string*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(std::vector<FS_File>*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(std::string*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(std::vector<FS_File>*, long long unsigned int)'

Whenever I try to call the next code:

ofstream outfile;
string filename = curFS.name + ".dat";
outfile.open(filename, ios::binary | ios::out);
curFS.save(outfile);
outfile.close();

I've tried a few things, but nothing has worked...

What does the compiler error means?
How can I solve it?

Body:
The error messages are self explanatory. std::ifstream and std::ofstream are streams of char data, but you are trying to read/write data using pointers to non-char types. There are no overloads of the write() and read() methods for non-char pointers.

For POD types, you can simply type cast your pointers to char*.

That won't work for non-POD types, like std::string and std::vector. For those types, you need to marshal the data instead.

Try something more like this instead:

void FS::saveTo(ofstream& of)
{
    // std::string needs to be marshaled...
    size_t value = name.size();
    of.write(reinterpret_cast<char*>(&value), sizeof(value));
    of.write(name.c_str(), value);

    // POD types can be written as-is...
    of.write(reinterpret_cast<char*>(&size), sizeof(size));
    of.write(reinterpret_cast<char*>(&freeBlocks), sizeof(freeBlocks));
    of.write(reinterpret_cast<char*>(&usedBlocks), sizeof(usedBlocks));
    of.write(reinterpret_cast<char*>(&blocksize), sizeof(blocksize));

    // std::vector needs to be marshaled...
    value = file_list.size();
    of.write(reinterpret_cast<char*>(&value), sizeof(value));
    for (size_t i = 0; i < value; ++i) {
        // write file_list[i] to the stream as needed...
    }

    // dynamic data needs to be marshaled...
    value = strlen(ptr); // or whatever the actual allocated size is...
    of.write(reinterpret_cast<char*>(&value), sizeof(value));
    of.write(ptr, value);
}

void FS::openFrom(ifstream& inf)
{
    size_t value;

    // std::string needs to be marshaled...
    inf.read(reinterpret_cast<char*>(&value), sizeof(value));
    name.resize(value);
    inf.read(&name[0], value);

    // POD types can be read as-is...
    inf.read(reinterpret_cast<char*>(&size), sizeof(size));
    inf.read(reinterpret_cast<char*>(&freeBlocks), sizeof(freeBlocks));
    inf.read(reinterpret_cast<char*>(&usedBlocks), sizeof(usedBlocks));
    inf.read(reinterpret_cast<char*>(&blocksize), sizeof(blocksize));

    // std::vector needs to be marshaled...
    inf.read(reinterpret_cast<char*>(&value), sizeof(value));
    file_list.resize(value);
    for (size_t i = 0; i < value; ++i) {
        // read file_list[i] from stream as needed...
    }

    // dynamic data needs to be marshaled...
    inf.read(reinterpret_cast<char*>(&value), sizeof(value));
    free(ptr);
    ptr = (char*) malloc(value+1);
    inf.read(ptr, value);
    ptr[value] = '\0';
}

Just be sure to always open the streams with the std::ios_base::binary flag enabled. To help ensure that, I would suggest passing the filename to saveTo()/openFrom() instead of user-supplied streams:

void FS::saveTo(const string& filename)
{
    ofstream outfile(filename, ios::binary);
    saveTo(outfile);
}

void FS::openFrom(const string& filename)
{
    ifstream infile(filename, ios::binary);
    openFrom(infile);
}

curFS.saveTo(curFS.name + ".dat");

curFS.openFrom(curFS.name + ".dat");


问:
How to read complex objects from json file in .net core
I have a json like this to read in c# but it showing null.

Provices.json contains this json

```<code>{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}
</code>```

start up file contains

```<code> services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));
</code>```

This is c# models

```<code>   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }
</code>```

This is how I am reading this file which is giving me null values

```<code>public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}
</code>```

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

答:
I got my problem.

Well, the answer was in type.

```<code>        "CountryId": 1,
        "Name": "AE (Armed Forces Europe)",
       // "Abbreviation": null,
       // "Published": false,
       //"DisplayOrder": 0,
       // "Country": null,
        "Id": 54
</code>```

On commenting out these lines, it started working.

Second Mistake is to add json file in Program.cs[.net core version 2.0]

Body:
I have a json like this to read in c# but it showing null.

Provices.json contains this json

{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}

start up file contains

 services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));

This is c# models

   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }

This is how I am reading this file which is giving me null values

public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

Body:
I got my problem.

Well, the answer was in type.

        "CountryId": 1,
        "Name": "AE (Armed Forces Europe)",
       // "Abbreviation": null,
       // "Published": false,
       //"DisplayOrder": 0,
       // "Country": null,
        "Id": 54

On commenting out these lines, it started working.

Second Mistake is to add json file in Program.cs[.net core version 2.0]


问:
Is there a way to throttle/slow a PHP script without missing streaming results from STDOUT?
I'm testing out an interesting "threading" concept in PHP. Basically, I'm working to have a parent process spawn children that do stuff and return the results back to the parent via STDOUT in sort of a callback manner.

The way my example  does it, the inner loop is too tight and burns 99% CPU:

```<code>while(true){
        $ret = $thread->Listen();
        if( $ret == 'DOINGSTUFF' ){
                break;
        }
}
</code>```

I'd like to tone this while loop down to looping every 5 seconds using, for example, a sleep(). This brings CPU utilization to a much more rational level; however I'm concerned it will then "miss" some of the children "threads" returning results in case one child finishes during the parent's sleeping process.

Can a PHP expert tell me whether this concern is well founded and if so, whether there's anything I can do to cope?

答:
Your example uses proc_open, which isn't exactly multi-threading. Anyway, when using proc_open, the pipes streams will be available as long as proc_close is not called, even if the process has actually terminated:

```<code>$proc = proc_open('which ls', $descriptorspec, $pipes);
sleep(5);
echo stream_get_contents($pipes[1]); // output '/bin/ls'

$proc = proc_open('which ls', $descriptorspec, $pipes);
sleep(5);
proc_close($proc);
echo stream_get_contents($pipes[1]); // E_WARNING: $pipes[1] not a valid stream
</code>```

Also, it is not necessary to use sleep. Usually, you don't want a script hanging for 5 seconds every pass doing nothing. Use usleep instead, which will also reduce the CPU usage but will still make the script responsive:

```<code>while (true) {
   // do stuff
   usleep(50);
}
</code>```

The above will sleep for 50 micro-seconds, leaving CPU cycles to other running processes.

As for pure multi-threading, it is not possible in PHP. All you can do is fork a process. The difference with actual forking and the method you use (proc_open) is that parent process data (variables, etc.) are forked to the child process as well. Forking should not be used in web applications, but only command-line programs, because web servers do not support it very well.

Body:
I'm testing out an interesting "threading" concept in PHP. Basically, I'm working to have a parent process spawn children that do stuff and return the results back to the parent via STDOUT in sort of a callback manner.

The way my example  does it, the inner loop is too tight and burns 99% CPU:

while(true){
        $ret = $thread->Listen();
        if( $ret == 'DOINGSTUFF' ){
                break;
        }
}

I'd like to tone this while loop down to looping every 5 seconds using, for example, a sleep(). This brings CPU utilization to a much more rational level; however I'm concerned it will then "miss" some of the children "threads" returning results in case one child finishes during the parent's sleeping process.

Can a PHP expert tell me whether this concern is well founded and if so, whether there's anything I can do to cope?

Body:
Your example uses proc_open, which isn't exactly multi-threading. Anyway, when using proc_open, the pipes streams will be available as long as proc_close is not called, even if the process has actually terminated:

$proc = proc_open('which ls', $descriptorspec, $pipes);
sleep(5);
echo stream_get_contents($pipes[1]); // output '/bin/ls'

$proc = proc_open('which ls', $descriptorspec, $pipes);
sleep(5);
proc_close($proc);
echo stream_get_contents($pipes[1]); // E_WARNING: $pipes[1] not a valid stream

Also, it is not necessary to use sleep. Usually, you don't want a script hanging for 5 seconds every pass doing nothing. Use usleep instead, which will also reduce the CPU usage but will still make the script responsive:

while (true) {
   // do stuff
   usleep(50);
}

The above will sleep for 50 micro-seconds, leaving CPU cycles to other running processes.

As for pure multi-threading, it is not possible in PHP. All you can do is fork a process. The difference with actual forking and the method you use (proc_open) is that parent process data (variables, etc.) are forked to the child process as well. Forking should not be used in web applications, but only command-line programs, because web servers do not support it very well.


问:
How to get a vectorized np.argmax random tiebreaker?
I know I can vectorize np.argmax via inputting a 2D array and specifying an axis, eg: np.argmax(2Darray,axis=1) to get the maximum index per row.

I know in the event two entries are equal in a single 1D vector whereby I wish to return the maximum index, I can tiebreak them via np.random.choice(np.flatnonzero(1Dvector == 1Dvector.max()))

The question is, how can I do both together? Ie: How to vectorize np.argmax whereby equal entries are randomly tiebroken?

答:
Here is one way. For large data one may consider replacing the permutation with something cheaper. I've hardcoded axis=1 but that shouldn't obscure the principle.

```<code>def fair_argmax_2D(a):
    y, x = np.where((a.T==a.max(1)).T)
    aux = np.random.permutation(len(y))
    xa = np.empty_like(x)
    xa[aux] = x
    return xa[np.maximum.reduceat(aux, np.where(np.diff(y, prepend=-1))[0])]

a = np.random.randint(0,5,(4,5))
a
# array([[2, 2, 2, 2, 1],
#        [3, 3, 3, 3, 2],
#        [3, 4, 2, 1, 4],
#        [3, 2, 4, 2, 1]])

# draw 10000 times
res = np.array([fair_argmax_2D(a) for _ in range(10000)])

# check
np.array([np.bincount(r, None, 5) for r in res.T])
# array([[ 2447,  2567,  2449,  2537,     0],
#        [ 2511,  2465,  2536,  2488,     0],
#        [    0,  5048,     0,     0,  4952],
#        [    0,     0, 10000,     0,     0]])
</code>```

Body:
Here is one way. For large data one may consider replacing the permutation with something cheaper. I've hardcoded axis=1 but that shouldn't obscure the principle.

def fair_argmax_2D(a):
    y, x = np.where((a.T==a.max(1)).T)
    aux = np.random.permutation(len(y))
    xa = np.empty_like(x)
    xa[aux] = x
    return xa[np.maximum.reduceat(aux, np.where(np.diff(y, prepend=-1))[0])]

a = np.random.randint(0,5,(4,5))
a
# array([[2, 2, 2, 2, 1],
#        [3, 3, 3, 3, 2],
#        [3, 4, 2, 1, 4],
#        [3, 2, 4, 2, 1]])

# draw 10000 times
res = np.array([fair_argmax_2D(a) for _ in range(10000)])

# check
np.array([np.bincount(r, None, 5) for r in res.T])
# array([[ 2447,  2567,  2449,  2537,     0],
#        [ 2511,  2465,  2536,  2488,     0],
#        [    0,  5048,     0,     0,  4952],
#        [    0,     0, 10000,     0,     0]])