问:
How to create a new csv file with separate columns in a shorter way
I created a function that does a few calculations, and managed to get the right data in the right way in the csv file. However, my code is really long and reading through other threads on this topic I did not find an easy way to shorten it. My code is the following:

```<code>def modelc(x,Mblood,Mliver,dt):
createFile = open('Time.csv', 'w')
createFile.write('t'+'\n')
createFile.close()

createFile = open('Blood.csv', 'w')
createFile.write('Mblood'+'\n')
createFile.close()

createFile = open('Liver.csv', 'w')
createFile.write('Mliver'+'\n')
createFile.close()

while x<24:
    Mblood = Mblood-Mblood*0.5*dt
    Mliver = Mliver+Mblood*0.5*dt
    x+=dt

    appendFile = open('Time.csv','a')
    appendFile.write('%f'%x+'\n')
    appendFile.close()

    appendFile = open('Blood.csv','a')
    appendFile.write('%f'%Mblood+'\n')
    appendFile.close()

    appendFile = open('Liver.csv','a')
    appendFile.write('%f'%Mliver+'\n')
    appendFile.close()

    csv_input = pandas.read_csv('Time.csv')
    csv_blood = pandas.read_csv('Blood.csv')
    csv_liver = pandas.read_csv('Liver.csv')
    csv_input['MassBlood'] = csv_blood['Mblood']
    csv_input['MassLiver'] = csv_liver['Mliver']
    csv_input.to_csv('Modeloutput.csv', index=False)

modelc(0,20,0,0.001)
</code>```

The CSV file then looks like this:
enter image description here

Does anyone have a simple way of achieving the same result with a shorter code?

答:
Opening and closing takes a long time since it uses the HD memory. Instead leave the file opened (in secondary memory), do all the operations and close and save in the very end.</p>

```<code>   def modelc(x,Mblood,Mliver,dt):
       createFile = open('Liver.csv', 'wt')
       createFile.write("t,MassBlood,MassLiver")
       for i in range(24):
          Mblood = Mblood-Mblood*0.5*dt
          Mliver = Mliver+Mblood*0.5*dt
          x+=dt
          createFile.write(str(x)+","+str(Mblood)+","+str(Mliver))
    createFile.close()
</code>```

Body:
I created a function that does a few calculations, and managed to get the right data in the right way in the csv file. However, my code is really long and reading through other threads on this topic I did not find an easy way to shorten it. My code is the following:

def modelc(x,Mblood,Mliver,dt):
createFile = open('Time.csv', 'w')
createFile.write('t'+'\n')
createFile.close()

createFile = open('Blood.csv', 'w')
createFile.write('Mblood'+'\n')
createFile.close()

createFile = open('Liver.csv', 'w')
createFile.write('Mliver'+'\n')
createFile.close()

while x<24:
    Mblood = Mblood-Mblood*0.5*dt
    Mliver = Mliver+Mblood*0.5*dt
    x+=dt

    appendFile = open('Time.csv','a')
    appendFile.write('%f'%x+'\n')
    appendFile.close()

    appendFile = open('Blood.csv','a')
    appendFile.write('%f'%Mblood+'\n')
    appendFile.close()

    appendFile = open('Liver.csv','a')
    appendFile.write('%f'%Mliver+'\n')
    appendFile.close()

    csv_input = pandas.read_csv('Time.csv')
    csv_blood = pandas.read_csv('Blood.csv')
    csv_liver = pandas.read_csv('Liver.csv')
    csv_input['MassBlood'] = csv_blood['Mblood']
    csv_input['MassLiver'] = csv_liver['Mliver']
    csv_input.to_csv('Modeloutput.csv', index=False)

modelc(0,20,0,0.001)

The CSV file then looks like this:
enter image description here

Does anyone have a simple way of achieving the same result with a shorter code?

Body:
Opening and closing takes a long time since it uses the HD memory. Instead leave the file opened (in secondary memory), do all the operations and close and save in the very end.

   def modelc(x,Mblood,Mliver,dt):
       createFile = open('Liver.csv', 'wt')
       createFile.write("t,MassBlood,MassLiver")
       for i in range(24):
          Mblood = Mblood-Mblood*0.5*dt
          Mliver = Mliver+Mblood*0.5*dt
          x+=dt
          createFile.write(str(x)+","+str(Mblood)+","+str(Mliver))
    createFile.close()


来源: stackexchange

问:
Get a Div Value in JQuery
I have a page containing the following div element:

```<code><div id="myDiv" class="myDivClass" style="">Some Value</div>
</code>```

How would I retrieve the value ("Some Value") either through JQuery or through standard JS?  I tried:

```<code>var mb = document.getElementById("myDiv");
</code>```

But the debugger console shows "mb is null".  Just wondering how to retrieve this value.

---- UPDATE ----
When I try the suggestion I get:  $ is not a function

This is part of a JQuery event handler where I am trying to read the value when I click a button.  The handler function is working but it can't interpret the jQuery value it seems:

```<code>jQuery('#gregsButton').click(function() {
   var mb = $('#myDiv').text();
   alert("Value of div is: " + mb.value);
});
</code>```

答:
You can do get id value by using

test_alert = $('#myDiv').val();
alert(test_alert);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div></code>```

ContentLicense: CC BY-SA 3.0

Title: Get a Div Value in JQuery

Body:
I have a page containing the following div element:

Some Value

How would I retrieve the value ("Some Value") either through JQuery or through standard JS?  I tried:

var mb = document.getElementById("myDiv");

But the debugger console shows "mb is null".  Just wondering how to retrieve this value.

---- UPDATE ----
When I try the suggestion I get:  $ is not a function

This is part of a JQuery event handler where I am trying to read the value when I click a button.  The handler function is working but it can't interpret the jQuery value it seems:

jQuery('#gregsButton').click(function() {
   var mb = $('#myDiv').text();
   alert("Value of div is: " + mb.value);
});

Body:
You can do get id value by using

test_alert = $('#myDiv').val();
alert(test_alert);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>

ContentLicense: CC BY-SA 4.0


问:
Efficient Way to Aggregate and Construct Matrix out of User Product Data in Python
I have data in the form of csv/pandas that looks like this:

I want to aggregate the user product data into a matrix like this.

How can I do this efficiently? Efficiency is really important.

答:
I can't add comments yet so here's my answer instead:
you can simply pivot the table.</p>

```<code># df <- dataframe
df.pivot(index='User', columns='Product', values='Cost').fillna(0)
</code>```

Body:
I can't add comments yet so here's my answer instead:
you can simply pivot the table.

# df <- dataframe
df.pivot(index='User', columns='Product', values='Cost').fillna(0)


问:
Why is a named function passed as 1st parameter to useEffect not a necessary dependency?
[Solved] I believe the 2 effects below should have the same effect.
But why does the eslint rule not complain in the second case?

It should be mandatory dependency in both case as doSomething can change and change the effect.

```<code>  const doSomething = useCallback(() => {
    void someProp;
  }, [someProp]);

useEffect(()=> doSomething(), [doSomething]); // eslint(react-hooks/exhaustive-deps) complains if I remove the dependency
useEffect(doSomething, []); // no complaint here, why?
</code>```

Edit:
It was actually fixed a while back (even before I wrote that question).
https://github.com/facebook/react/pull/18435

答:
The second argument for useEffect is the dependency array, in which you can describe that the effect should run if the given values are changed.
On your second case the doSomething function is not something the effect uses, but it is the effect function itself.

If you use it inside your effect function, eslint will notify about it.

```<code>useEffect(() => {
  doSomething();
}, []);
</code>```

Body:
[Solved] I believe the 2 effects below should have the same effect.
But why does the eslint rule not complain in the second case?

It should be mandatory dependency in both case as doSomething can change and change the effect.

  const doSomething = useCallback(() => {
    void someProp;
  }, [someProp]);

useEffect(()=> doSomething(), [doSomething]); // eslint(react-hooks/exhaustive-deps) complains if I remove the dependency
useEffect(doSomething, []); // no complaint here, why?

Edit:
It was actually fixed a while back (even before I wrote that question).
https://github.com/facebook/react/pull/18435

Body:
The second argument for useEffect is the dependency array, in which you can describe that the effect should run if the given values are changed.
On your second case the doSomething function is not something the effect uses, but it is the effect function itself.

If you use it inside your effect function, eslint will notify about it.

useEffect(() => {
  doSomething();
}, []);


问:
DAX function to check the amount of dates that is greater than another set of dates in 2 different columns
I'm currently doing an internship where I have been asked to make a few visuals in Power BI

I've searched around, tried a couple of things. But the truth is I am very much a beginner at coding and functions in general. Only had basic courses of different languages during my education and to be fair, it's a bit outside my scope of work.

So I have 2 columns I need to compare in order to find out how many dates in column 2 that is greater than the dates in column 1

So I'm imagining something like:

```<code>Measure = IF[(Investments(Expected closure)]<[(Investments(Actualclosure)]
</code>```

Basically I want an overview of how many investments have a later closure date than expected.

Next thing would possibly be to create a boxplot showing the distribution (by how far we are off).

I know this is very basic, and possibly not formulated in the best way possible, please let me know if you need any more information.

Thanks in advance

答:
Welcome to the community. Be sure to read to read this for posting questions.

For your questions, you can use the following code. You are filter the table with your logical expression with FILTER and then you count the lines of a column with COUNTA.

```<code>Measure = CALCULATE(COUNTA('Investments'[Actualclosure]),FILTER(ALL('Investments'),'Investments'[Actualclosure]>'Investments'[Expected closure]))
</code>```

Hope this solves your problem.

Body:
I'm currently doing an internship where I have been asked to make a few visuals in Power BI

I've searched around, tried a couple of things. But the truth is I am very much a beginner at coding and functions in general. Only had basic courses of different languages during my education and to be fair, it's a bit outside my scope of work.

So I have 2 columns I need to compare in order to find out how many dates in column 2 that is greater than the dates in column 1

So I'm imagining something like:

Measure = IF[(Investments(Expected closure)]<[(Investments(Actualclosure)]

Basically I want an overview of how many investments have a later closure date than expected.

Next thing would possibly be to create a boxplot showing the distribution (by how far we are off).

I know this is very basic, and possibly not formulated in the best way possible, please let me know if you need any more information.

Thanks in advance

Body:
Welcome to the community. Be sure to read to read this for posting questions.

For your questions, you can use the following code. You are filter the table with your logical expression with FILTER and then you count the lines of a column with COUNTA.

Measure = CALCULATE(COUNTA('Investments'[Actualclosure]),FILTER(ALL('Investments'),'Investments'[Actualclosure]>'Investments'[Expected closure]))

Hope this solves your problem.


问:
Different and multiple logging outputs
I have created an ASP.NET Core 3 application with the API template. I've added an information logging row in WeatherForecastController:

```<code>_logger.LogInformation("HELLO!");
</code>```

The console output of this row is is different depending on where how I run the application.

When I run the application with dotnet run in Windows Terminal:

```<code>info: WebApplication1.Controllers.WeatherForecastController[0]
      HELLO!
</code>```

When I run in debug mode in Visual Studio 2019:

```<code>WebApplication1.Controllers.WeatherForecastController: Information: HELLO!
</code>```

When I run in debug mode in Visual Studio Code I get both variants at the same time:

```<code>info: WebApplication1.Controllers.WeatherForecastController[0]
      HELLO!
WebApplication1.Controllers.WeatherForecastController: Information: HELLO!
</code>```

The differences bugs me, but the main reason I bother is because I use Visual Studio Code and the duplicate output makes it much harder to read.

Why are the outputs different and can I somehow control this to get the same everywhere or at least only one of them in Visual Studio Code?

答:
In ASP.NET default template the row Host.CreateDefaultBuilder(args) adds both DebugLogger and ConsoleLogger. Running dotnet run shows from console and Visual Studio 2019 shows from debug. Visual Studio Code shows from both.

My best solution so far is to add this to my appsettings.development.json to disable Debug logging (and only keep Console logging):

```<code>{
    "Logging": {
        "Debug": {
            "LogLevel": {
                "Default": "None"
            }
        }
    }
}
</code>```

Title: Different and multiple logging outputs

Body:
I have created an ASP.NET Core 3 application with the API template. I've added an information logging row in WeatherForecastController:

_logger.LogInformation("HELLO!");

The console output of this row is is different depending on where how I run the application.

When I run the application with dotnet run in Windows Terminal:

info: WebApplication1.Controllers.WeatherForecastController[0]
      HELLO!

When I run in debug mode in Visual Studio 2019:

WebApplication1.Controllers.WeatherForecastController: Information: HELLO!

When I run in debug mode in Visual Studio Code I get both variants at the same time:

info: WebApplication1.Controllers.WeatherForecastController[0]
      HELLO!
WebApplication1.Controllers.WeatherForecastController: Information: HELLO!

The differences bugs me, but the main reason I bother is because I use Visual Studio Code and the duplicate output makes it much harder to read.

Why are the outputs different and can I somehow control this to get the same everywhere or at least only one of them in Visual Studio Code?

Body:
In ASP.NET default template the row Host.CreateDefaultBuilder(args) adds both DebugLogger and ConsoleLogger. Running dotnet run shows from console and Visual Studio 2019 shows from debug. Visual Studio Code shows from both.

My best solution so far is to add this to my appsettings.development.json to disable Debug logging (and only keep Console logging):

{
    "Logging": {
        "Debug": {
            "LogLevel": {
                "Default": "None"
            }
        }
    }
}


问:
How to place child element without being affected of transformation of parent element? UPDATED!!! [Javascript]
I have a parent div that displays a graph that can be rotated.
I want to place dots at mouse clicks. This is my place function:

```<code>module.exports.place = function (event, id) {
  let div = document.createElement("div");
  div.className = "container-fluid";
  div.id = id;
  let avakio_wrapper = document.getElementById("avakio");
  avakio_wrapper.appendChild(div);
  let parentPosition = getPosition(event.currentTarget);

  xPosition = event.clientX - parentPosition.x - div.clientWidth / 2;
  yPosition = event.clientY - parentPosition.y - div.clientHeight / 2;
  div.style.left = xPosition + "px";
  div.style.top = yPosition + "px";
}
</code>```

When the graph isn't rotated it works as expected, though when i rotate the graph it places the dot first under mouse click and then it applies the rotation transform and moves it. I have screenshots showing what i describe. The red dot is showing the click position. I appreciate any help.

UPDATE!!!!

Here is an implementation of my code:

```<code>// Calculate clicking pos based of top-left corner of div
  xPosition = event.clientX - parentPosition.x - dot.clientWidth / 2;
  yPosition = event.clientY - parentPosition.y - dot.clientHeight / 2;

  let centerx = parentDiv.clientWidth / 2;
  let centery = parentDiv.clientHeight / 2;

  // Find Rotation angle
  let rot = parentDiv.style.getPropertyValue("transform");
  if (rot != "") {
    rot = rot.split("(")[1].split("deg")[0];
  } else {
    rot = 0;
  }

  // Perform Invert Rotation
  xPosition = centerx - xPosition;
  yPosition = centery - yPosition;

  let xRot =
    xPosition * Math.cos(rot * (Math.PI / 180)) +
    yPosition * Math.sin(rot * (Math.PI / 180));
  let yRot =
    -xPosition * Math.sin(rot * (Math.PI / 180)) +
    yPosition * Math.cos(rot * (Math.PI / 180));

  // Calculate again based top-left corner
  dot.style.left = centerx - xRot + "px";
  dot.style.top = centery - yRot + "px";
</code>```

However i run on some issues. When the parent div is rotated the dots are placed some pixels off based on the rotation angle. I have some screenshots of different rotation angles. I' ve done the maths on paper for many days but still can't figure out what causing it.

答:
Here an application of the math.
They still move a bit (I think that is because of calculus imprecision). I'm kinda stuck here, maybe some will be able to fix it.

function rotate() {
  let parent = document.getElementById("parent")
  let rot = document.getElementById("value").value
  let transform = parent.style.transform
  transform = "rotate("+ (Number(transform.substr(7,transform.length-11)) + Number(rot)) +"deg)"
  parent.style.transform = transform
  let dots = document.getElementsByClassName("dot")
 for (i = 0; i < dots.length; i++)
  dotpos(parent, dots[i],rot)
}

function dotpos(parent,dot,rot) {
 rot = rot * (Math.PI/180) //convert to radian
 let xCenter = parent.offsetWidth /2
 let yCenter = parent.offsetHeight /2
 let x = xCenter - Number(dot.style.left.substring(0, dot.style.left.length - 2))
 let y = yCenter - Number(dot.style.top.substring(0, dot.style.top.length - 2))
 let xRot = x*Math.cos(rot)+y*Math.sin(rot)
 let yRot = -x*Math.sin(rot)+y*Math.cos(rot)
 dot.style.left = xCenter -xRot + "px"
 dot.style.top = yCenter -yRot + "px"
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#parent {
  height: 100px;
  width : 100px;
  background-color: grey;
}
.dot {
  height: 5px;
  width : 5px;
  border-radius: 5px;
  background-color: red;
}</code>```

<form>
  <input type="text" id="value">

</form>

<button onclick="rotate()">rotate</button>```

Body:
I have a parent div that displays a graph that can be rotated.
I want to place dots at mouse clicks. This is my place function:

module.exports.place = function (event, id) {
  let div = document.createElement("div");
  div.className = "container-fluid";
  div.id = id;
  let avakio_wrapper = document.getElementById("avakio");
  avakio_wrapper.appendChild(div);
  let parentPosition = getPosition(event.currentTarget);

  xPosition = event.clientX - parentPosition.x - div.clientWidth / 2;
  yPosition = event.clientY - parentPosition.y - div.clientHeight / 2;
  div.style.left = xPosition + "px";
  div.style.top = yPosition + "px";
}

When the graph isn't rotated it works as expected, though when i rotate the graph it places the dot first under mouse click and then it applies the rotation transform and moves it. I have screenshots showing what i describe. The red dot is showing the click position. I appreciate any help.

UPDATE!!!!

Here is an implementation of my code:

// Calculate clicking pos based of top-left corner of div
  xPosition = event.clientX - parentPosition.x - dot.clientWidth / 2;
  yPosition = event.clientY - parentPosition.y - dot.clientHeight / 2;

  let centerx = parentDiv.clientWidth / 2;
  let centery = parentDiv.clientHeight / 2;

  // Find Rotation angle
  let rot = parentDiv.style.getPropertyValue("transform");
  if (rot != "") {
    rot = rot.split("(")[1].split("deg")[0];
  } else {
    rot = 0;
  }

  // Perform Invert Rotation
  xPosition = centerx - xPosition;
  yPosition = centery - yPosition;

  let xRot =
    xPosition * Math.cos(rot * (Math.PI / 180)) +
    yPosition * Math.sin(rot * (Math.PI / 180));
  let yRot =
    -xPosition * Math.sin(rot * (Math.PI / 180)) +
    yPosition * Math.cos(rot * (Math.PI / 180));

  // Calculate again based top-left corner
  dot.style.left = centerx - xRot + "px";
  dot.style.top = centery - yRot + "px";

However i run on some issues. When the parent div is rotated the dots are placed some pixels off based on the rotation angle. I have some screenshots of different rotation angles. I' ve done the maths on paper for many days but still can't figure out what causing it.

Body:
Here an application of the math.
They still move a bit (I think that is because of calculus imprecision). I'm kinda stuck here, maybe some will be able to fix it.

function rotate() {
  let parent = document.getElementById("parent")
  let rot = document.getElementById("value").value
  let transform = parent.style.transform
  transform = "rotate("+ (Number(transform.substr(7,transform.length-11)) + Number(rot)) +"deg)"
  parent.style.transform = transform
  let dots = document.getElementsByClassName("dot")
 for (i = 0; i < dots.length; i++)
  dotpos(parent, dots[i],rot)
}

function dotpos(parent,dot,rot) {
 rot = rot * (Math.PI/180) //convert to radian
 let xCenter = parent.offsetWidth /2
 let yCenter = parent.offsetHeight /2
 let x = xCenter - Number(dot.style.left.substring(0, dot.style.left.length - 2))
 let y = yCenter - Number(dot.style.top.substring(0, dot.style.top.length - 2))
 let xRot = x*Math.cos(rot)+y*Math.sin(rot)
 let yRot = -x*Math.sin(rot)+y*Math.cos(rot)
 dot.style.left = xCenter -xRot + "px"
 dot.style.top = yCenter -yRot + "px"
}

#parent {
  height: 100px;
  width : 100px;
  background-color: grey;
}
.dot {
  height: 5px;
  width : 5px;
  border-radius: 5px;
  background-color: red;
}

<div id="parent" style = "transform:rotate(0deg)">
  <div class ="dot" style="position:relative;left:15px;top:30px;"></div>
  <div class ="dot" style="position:relative;left:60px;top:50px;"></div>
</div>
<form>
  <input type="text" id="value"><br>
</form>

<button onclick="rotate()">rotate</button>


问:
List devices by IPs?
How could I list the devices by IP instead of name ?

I am aware that I can get the device name and description but since I have many devices installed it would be rather easier if I could get it by IP to select one, but I couldnt find any option related so I am wondering if there is an approach to it ?

```<code>foreach (var dev in CaptureDeviceList.Instance)
{
    var str = String.Format("{0} {1}", dev.Name, dev.Description);
    iDeviceDropDown.Items.Add(str);
}
</code>```

答:
UPDATE, Found a solution:

```<code>private void GetDevices()
{
    foreach (SharpPcap.LibPcap.LibPcapLiveDevice dev in SharpPcap.LibPcap.LibPcapLiveDeviceList.Instance)
    {
        for (int i = 0; i < dev.Addresses.Count; i++)
        {
            var ip = dev.Addresses[i].Addr.ipAddress;
            if (ip == null)
                continue;

            iDeviceDropDown.Items.Add(ip.ToString());
        }
    }
}
</code>```

Title: List devices by IPs?

Body:
How could I list the devices by IP instead of name ?

I am aware that I can get the device name and description but since I have many devices installed it would be rather easier if I could get it by IP to select one, but I couldnt find any option related so I am wondering if there is an approach to it ?

foreach (var dev in CaptureDeviceList.Instance)
{
    var str = String.Format("{0} {1}", dev.Name, dev.Description);
    iDeviceDropDown.Items.Add(str);
}

Body:
UPDATE, Found a solution:

private void GetDevices()
{
    foreach (SharpPcap.LibPcap.LibPcapLiveDevice dev in SharpPcap.LibPcap.LibPcapLiveDeviceList.Instance)
    {
        for (int i = 0; i < dev.Addresses.Count; i++)
        {
            var ip = dev.Addresses[i].Addr.ipAddress;
            if (ip == null)
                continue;

            iDeviceDropDown.Items.Add(ip.ToString());
        }
    }
}


问:
Is there a way to plot columns with the same name as the same colour?
I am attempting to plot one dataset which has many columns with the same name. I was trying to reuse a plotting program I made earlier, but the issue is that it plots each column in a different colour, instead I would like each column with the same name to be the same colour. Furthermore, it adds each column to the legend causing a lot of mess in the figure which I have attached. Is there a way to just put one label per colour? Any help to fix these issues would be greatly appreciated!

Here is an example plot As you can see instead of plotting both "O" as one colour, it plots it as two since there are two columns of data, and created a duplicate in the legend.

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

s = pd.read_csv('Edit_This.csv') # reads the .csv file can be found in dropbox > shared manuscripts > Ravi Ben MoOx Nucleation and LEIS > Figures

xmin = 0 # Change these bounds as needed
xmax = 1
ymin = 0
ymax = 2500

y_axis_columns = s.columns[1:] # Reads column data to plot y values from index 1 onwards

for col_name in y_axis_columns: # Loop to plot all columns until it finds an empty one
   plt.plot(s.depth,s[col_name], label=col_name)
   plt.tight_layout()
   from matplotlib.ticker import MaxNLocator
   axes = plt.gca()
   axes.yaxis.set_major_locator(MaxNLocator(integer=True))
   axes.set_xlim([xmin,xmax])
   axes.set_ylim(ymin,ymax)
   plt.xlabel('Depth (nm)', fontsize=12) # Edit as needed
   plt.ylabel('Intensity (counts/nC)', fontsize=12)
   plt.legend(loc='upper center', fontsize=10) # Defines legend formatting
   plt.savefig("6_Sputter1_5-222cyc_SiOx.png", dpi = 1200) # Edit export file name and DPI here
plt.show()
</code>```

You can download the data from this link

答:
Ok, the problem emerges because you have multiple columns with the same name. So, you need to handle that. The following code does so:

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

s = pd.read_csv('Edit_This.csv') # reads the .csv file can be found in dropbox > shared manuscripts > Ravi Ben MoOx Nucleation and LEIS > Figures

xmin = 0 # Change these bounds as needed
xmax = 1
ymin = 0
ymax = 2500

y_axis_columns = s.columns[1:] # Reads column data to plot y values from index 1 onwards

# this is the color dictionary
colors = {"O": 'r', "Mo": 'b', 'Al':'g'}

for col_name in y_axis_columns: # Loop to plot all columns until it finds an empty one
   plt.plot(s.depth,s[col_name], label=col_name, color=colors[col_name.split('.')[0]])
   plt.tight_layout()
   from matplotlib.ticker import MaxNLocator
   axes = plt.gca()

axes.yaxis.set_major_locator(MaxNLocator(integer=True))
axes.set_xlim([xmin,xmax])
axes.set_ylim(ymin,ymax)
plt.xlabel('Depth (nm)', fontsize=12) # Edit as needed
plt.ylabel('Intensity (counts/nC)', fontsize=12)

# Defines legend formatting
custom_lines = [Line2D([0], [0], color='r', lw=4),
                Line2D([0], [0], color='b', lw=4),
                Line2D([0], [0], color='g', lw=4)]
plt.legend(custom_lines, ['O', 'Mo', 'Al'], loc='upper center', fontsize=10)

plt.savefig("6_Sputter1_5-222cyc_SiOx.png", dpi = 1200) # Edit export file name and DPI here
plt.show()
</code>```

Which produces the following image:

Body:
I am attempting to plot one dataset which has many columns with the same name. I was trying to reuse a plotting program I made earlier, but the issue is that it plots each column in a different colour, instead I would like each column with the same name to be the same colour. Furthermore, it adds each column to the legend causing a lot of mess in the figure which I have attached. Is there a way to just put one label per colour? Any help to fix these issues would be greatly appreciated!

Here is an example plot As you can see instead of plotting both "O" as one colour, it plots it as two since there are two columns of data, and created a duplicate in the legend.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

s = pd.read_csv('Edit_This.csv') # reads the .csv file can be found in dropbox > shared manuscripts > Ravi Ben MoOx Nucleation and LEIS > Figures

xmin = 0 # Change these bounds as needed
xmax = 1
ymin = 0
ymax = 2500

y_axis_columns = s.columns[1:] # Reads column data to plot y values from index 1 onwards

for col_name in y_axis_columns: # Loop to plot all columns until it finds an empty one
   plt.plot(s.depth,s[col_name], label=col_name)
   plt.tight_layout()
   from matplotlib.ticker import MaxNLocator
   axes = plt.gca()
   axes.yaxis.set_major_locator(MaxNLocator(integer=True))
   axes.set_xlim([xmin,xmax])
   axes.set_ylim(ymin,ymax)
   plt.xlabel('Depth (nm)', fontsize=12) # Edit as needed
   plt.ylabel('Intensity (counts/nC)', fontsize=12)
   plt.legend(loc='upper center', fontsize=10) # Defines legend formatting
   plt.savefig("6_Sputter1_5-222cyc_SiOx.png", dpi = 1200) # Edit export file name and DPI here
plt.show()

You can download the data from this link

Body:
Ok, the problem emerges because you have multiple columns with the same name. So, you need to handle that. The following code does so:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

s = pd.read_csv('Edit_This.csv') # reads the .csv file can be found in dropbox > shared manuscripts > Ravi Ben MoOx Nucleation and LEIS > Figures

xmin = 0 # Change these bounds as needed
xmax = 1
ymin = 0
ymax = 2500

y_axis_columns = s.columns[1:] # Reads column data to plot y values from index 1 onwards

# this is the color dictionary
colors = {"O": 'r', "Mo": 'b', 'Al':'g'}

for col_name in y_axis_columns: # Loop to plot all columns until it finds an empty one
   plt.plot(s.depth,s[col_name], label=col_name, color=colors[col_name.split('.')[0]])
   plt.tight_layout()
   from matplotlib.ticker import MaxNLocator
   axes = plt.gca()

axes.yaxis.set_major_locator(MaxNLocator(integer=True))
axes.set_xlim([xmin,xmax])
axes.set_ylim(ymin,ymax)
plt.xlabel('Depth (nm)', fontsize=12) # Edit as needed
plt.ylabel('Intensity (counts/nC)', fontsize=12)

# Defines legend formatting
custom_lines = [Line2D([0], [0], color='r', lw=4),
                Line2D([0], [0], color='b', lw=4),
                Line2D([0], [0], color='g', lw=4)]
plt.legend(custom_lines, ['O', 'Mo', 'Al'], loc='upper center', fontsize=10)

plt.savefig("6_Sputter1_5-222cyc_SiOx.png", dpi = 1200) # Edit export file name and DPI here
plt.show()

Which produces the following image:


问:
How to shutdown a computer using Python
I've written a Python script which should eventually shutdown the computer.

This line is a part of it :

```<code>os.system("shutdown /p")
</code>```

It makes some sort of a shutdown but remains on the turn-on Windows control pannel (where the user can switch the computer users).

Is there a way to fully shutdown the computer?

I've tried other os.system("shutdown ___") methods with no success.

Is there another method which might help?

答:
Try this code snippet:</p>

```<code>import os

shutdown = input("Do you wish to shutdown your computer ? (yes / no): ")

if shutdown == 'no':
    exit()
else:
    os.system("shutdown /s /t 1")
</code>```

Title: How to shutdown a computer using Python

Body:
I've written a Python script which should eventually shutdown the computer.

This line is a part of it :

os.system("shutdown /p")

It makes some sort of a shutdown but remains on the turn-on Windows control pannel (where the user can switch the computer users).

Is there a way to fully shutdown the computer?

I've tried other os.system("shutdown ___") methods with no success.

Is there another method which might help?

Body:
Try this code snippet:

import os

shutdown = input("Do you wish to shutdown your computer ? (yes / no): ")

if shutdown == 'no':
    exit()
else:
    os.system("shutdown /s /t 1")


问:
PyQt: Adding rows to QTableView using QAbstractTableModel
I am super new to Qt programming. I am trying to make a simple table that can have rows added by clicking a button. I can implement the table fine but can't seem to get the updated data to show on the table. I believe my problem stems from the fact that I can't seem to properly call any sort of "change data" method using the button. I've tried several different solutions online all of which have lead to 4 year old, dead-end posts. What I have so far is the basic structure, I just can't figure out how to make the table update with new data.

This is the basic view

I have set up with some test data.

In the final implementation, the table will start empty and I would like to append rows and have them displayed in the table view.

```<code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        # create table
        self.get_table_data()
        self.table = self.createTable()

        # layout
        self.layout = QVBoxLayout()

        self.testButton = QPushButton("test")
        self.connect(self.testButton, SIGNAL("released()"), self.test)

        self.layout.addWidget(self.testButton)
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

    def get_table_data(self):
        self.tabledata = [[1234567890,2,3,4,5],
                          [6,7,8,9,10],
                          [11,12,13,14,15],
                          [16,17,18,19,20]]

    def createTable(self):
        # create the view
        tv = QTableView()

        # set the table model
        header = ['col_0', 'col_1', 'col_2', 'col_3', 'col_4']
        tablemodel = MyTableModel(self.tabledata, header, self)
        tv.setModel(tablemodel)

        # set the minimum size
        tv.setMinimumSize(400, 300)

        # hide grid
        tv.setShowGrid(False)

        # hide vertical header
        vh = tv.verticalHeader()
        vh.setVisible(False)

        # set horizontal header properties
        hh = tv.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        tv.resizeColumnsToContents()

        # set row height
        tv.resizeRowsToContents()

        # enable sorting
        tv.setSortingEnabled(False)

        return tv

    def test(self):
        self.tabledata.append([1,1,1,1,1])
        self.emit(SIGNAL('dataChanged()'))
        print 'success'

class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, headerdata, parent=None):
        """
        Args:
            datain: a list of lists\n
            headerdata: a list of strings
        """
        QAbstractTableModel.__init__(self, parent)
        self.arraydata = datain
        self.headerdata = headerdata

    def rowCount(self, parent):
        return len(self.arraydata)

    def columnCount(self, parent):
        if len(self.arraydata) > 0:
            return len(self.arraydata[0])
        return 0

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.arraydata[index.row()][index.column()])

    def setData(self, index, value, role):
        pass         # not sure what to put here

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.headerdata[col])
        return QVariant()

    def sort(self, Ncol, order):
        """
        Sort table by given column number.
        """
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))
        if order == Qt.DescendingOrder:
            self.arraydata.reverse()
        self.emit(SIGNAL("layoutChanged()"))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())
</code>```

答:
QAbstractTableModel have two special methods for that ( beginInsertRows() and endInsertRows()).

You can add api-point in your custom model. For example:

```<code>    def insertGuest(self, guest):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self.guestsTableData.append(guest)
        self.endInsertRows()
</code>```

Body:
I am super new to Qt programming. I am trying to make a simple table that can have rows added by clicking a button. I can implement the table fine but can't seem to get the updated data to show on the table. I believe my problem stems from the fact that I can't seem to properly call any sort of "change data" method using the button. I've tried several different solutions online all of which have lead to 4 year old, dead-end posts. What I have so far is the basic structure, I just can't figure out how to make the table update with new data.

This is the basic view

I have set up with some test data.

In the final implementation, the table will start empty and I would like to append rows and have them displayed in the table view.

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        # create table
        self.get_table_data()
        self.table = self.createTable()

        # layout
        self.layout = QVBoxLayout()

        self.testButton = QPushButton("test")
        self.connect(self.testButton, SIGNAL("released()"), self.test)

        self.layout.addWidget(self.testButton)
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

    def get_table_data(self):
        self.tabledata = [[1234567890,2,3,4,5],
                          [6,7,8,9,10],
                          [11,12,13,14,15],
                          [16,17,18,19,20]]

    def createTable(self):
        # create the view
        tv = QTableView()

        # set the table model
        header = ['col_0', 'col_1', 'col_2', 'col_3', 'col_4']
        tablemodel = MyTableModel(self.tabledata, header, self)
        tv.setModel(tablemodel)

        # set the minimum size
        tv.setMinimumSize(400, 300)

        # hide grid
        tv.setShowGrid(False)

        # hide vertical header
        vh = tv.verticalHeader()
        vh.setVisible(False)

        # set horizontal header properties
        hh = tv.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        tv.resizeColumnsToContents()

        # set row height
        tv.resizeRowsToContents()

        # enable sorting
        tv.setSortingEnabled(False)

        return tv

    def test(self):
        self.tabledata.append([1,1,1,1,1])
        self.emit(SIGNAL('dataChanged()'))
        print 'success'

class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, headerdata, parent=None):
        """
        Args:
            datain: a list of lists\n
            headerdata: a list of strings
        """
        QAbstractTableModel.__init__(self, parent)
        self.arraydata = datain
        self.headerdata = headerdata

    def rowCount(self, parent):
        return len(self.arraydata)

    def columnCount(self, parent):
        if len(self.arraydata) > 0:
            return len(self.arraydata[0])
        return 0

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.arraydata[index.row()][index.column()])

    def setData(self, index, value, role):
        pass         # not sure what to put here

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.headerdata[col])
        return QVariant()

    def sort(self, Ncol, order):
        """
        Sort table by given column number.
        """
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))
        if order == Qt.DescendingOrder:
            self.arraydata.reverse()
        self.emit(SIGNAL("layoutChanged()"))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

Body:
QAbstractTableModel have two special methods for that ( beginInsertRows() and endInsertRows()).

You can add api-point in your custom model. For example:

    def insertGuest(self, guest):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self.guestsTableData.append(guest)
        self.endInsertRows()


问:
Not able to execute the sql file script from docker compose
I am trying to execute the sql files from docker compose.

My compose file is:

```<code>    - ../folder:/docker-entrypoint-initdb.d/folder1/
    - ../folder2:/docker-entrypoint-initdb.d/folder2/
</code>```

The sql files are in folder named folder.

Docker file is:

```<code>COPY init.sh /docker-entrypoint-initdb.d/init.sh
</code>```

init.sh file:

```<code>"${psql[@]}" -f folder1/*.sql
"${psql[@]}" -f folder2/*.sql

</code>```

I am getting :

postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh
postgres_1  | /docker-entrypoint-initdb.d/init.sh: line : -f: command not found

答:
According to mysql image documentation on docker hub:

When a container is started for the first time, a new database with
  the specified name will be created and initialized with the provided
  configuration variables. Furthermore, it will execute files with
  extensions .sh, .sql and .sql.gz that are found in
  /docker-entrypoint-initdb.d. Files will be executed in alphabetical
  order. You can easily populate your mysql services by mounting a SQL
  dump into that directory and provide custom images with contributed
  data. SQL files will be imported by default to the database specified
  by the MYSQL_DATABASE variable.

Also, the logs show your .sh file is getting executed and got errors. Looking into the code it seems you are trying to execute an init script which execute other *.sql files which is redundant.

If an order of execution is desirable, stick to naming them to comply with an alphabetical order execution.

Body:
I am trying to execute the sql files from docker compose.

My compose file is:

    - ../folder:/docker-entrypoint-initdb.d/folder1/
    - ../folder2:/docker-entrypoint-initdb.d/folder2/

The sql files are in folder named folder.

Docker file is:

COPY init.sh /docker-entrypoint-initdb.d/init.sh

init.sh file:

"${psql[@]}" -f folder1/*.sql
"${psql[@]}" -f folder2/*.sql

I am getting :

postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh
postgres_1  | /docker-entrypoint-initdb.d/init.sh: line : -f: command not found


问:
Spring 3 RestTemplate to WebClient
I'm trying to migrate Spring version 3 RestTemplate with the WebClient. But I'm getting this compilation error while doing this migration.

```<code>cannot access org.springframework.core.ParameterizedTypeReference
</code>```

Here is the Spring RestTemplate code that I'm trying to change

```<code>private ResponseEntity<Assignment[]> getAssignmentsPage(RestTemplate restTemplate, HttpEntity<Object> httpEntity, String url) {

            ResponseEntity<Assignment[]> responseEntity =
                    restTemplate.exchange(url, HttpMethod.GET, httpEntity, Assignment[].class);

            return responseEntity;
    }
</code>```

Replaced code with WebClient

```<code>Flux<Assignment[]> quoteFlux = WebClient.create()
                .get()
                .uri(url)
                .retrieve()
                .bodyToFlux(Assignment[].class);
</code>```

Here are the POM file configurations

```<code><properties>
    <java-version>1.8</java-version>
    <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
    <org.aspectj-version>1.6.9</org.aspectj-version>
</properties><dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <!-- added       -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <version>2.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectreactor</groupId>
        <artifactId>reactor-spring</artifactId>
        <version>1.0.1.RELEASE</version>
    </dependency>
</code>```

答:
Your Flux should be of type

ParameterizedTypeReference<Assignment[]>(){}

Please check this out: https://github.com/spring-projects/spring-framework/issues/20195

Title: Spring 3 RestTemplate to WebClient

Body:
I'm trying to migrate Spring version 3 RestTemplate with the WebClient. But I'm getting this compilation error while doing this migration.

cannot access org.springframework.core.ParameterizedTypeReference

Here is the Spring RestTemplate code that I'm trying to change

private ResponseEntity<Assignment[]> getAssignmentsPage(RestTemplate restTemplate, HttpEntity<Object> httpEntity, String url) {

            ResponseEntity<Assignment[]> responseEntity =
                    restTemplate.exchange(url, HttpMethod.GET, httpEntity, Assignment[].class);

            return responseEntity;
    }

Replaced code with WebClient

Flux<Assignment[]> quoteFlux = WebClient.create()
                .get()
                .uri(url)
                .retrieve()
                .bodyToFlux(Assignment[].class);

Here are the POM file configurations

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
    <org.aspectj-version>1.6.9</org.aspectj-version>
</properties><dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <version>2.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectreactor</groupId>
        <artifactId>reactor-spring</artifactId>
        <version>1.0.1.RELEASE</version>
    </dependency>


问:
Bypass Min SDK Version - or what else?
I am starting with flutter, and overall, I am getting an idea but have hit the wall with what I find to be one of the main reasons to consider migrating from HTML + JQueryMobile: speech to text implementation.

I have found the speech_to_text package (https://pub.dev/packages/speech_to_text#-installing-tab-), followed the instructions to :
1. update the pubspec.yaml file with the dependency &
2. instal the package from command line
3. import the package in the code

but have hit the wall with the minimum SDK requirements not being met by the package. Here is the error message:

C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\android\app\src\debug\AndroidManifest.xml
    Error:  uses-sdk:minSdkVersion 16 cannot be smaller than version 21
    declared in library [:speech_to_text]
    C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\build\speech_to_text\intermediates\library_manifest\debug\AndroidManifest.xml
    as the library might be using APIs not available in 16  Suggestion:
    use a compatible library with a minSdk of at most 16,       or increase
    this project's minSdk version to at least 21,       or use
    tools:overrideLibrary="com.csdcorp.speech_to_text" to force usage (may
    lead to runtime failures)

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [:speech_to_text]
      C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\build\speech_to_text\intermediates\library_manifest\debug\AndroidManifest.xml
      as the library might be using APIs not available in 16      Suggestion:
      use a compatible library with a minSdk of at most 16,
          or increase this project's minSdk version to at least 21,
          or use tools:overrideLibrary="com.csdcorp.speech_to_text" to force usage (may lead to runtime failures)

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 11s Exception: Gradle task assembleDebug failed with
    exit code 1

Strangely, I have managed to bypass this once but can not find the
   relevant piece of code in the app folder now. Worse, the mentioned file

```<code>> C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\android\app\src\debug\AndroidManifest.xml
does not contain any reference to SDK, only this:
< <manifest
 <xmlns:android="http://schemas.android.com/apk/res/android"
  <   package="com.example.flutter4">
>     <!-- Flutter needs it to communicate with the running application
>          to allow setting breakpoints, to provide hot reload, etc.
>     -->
>     <uses-permission android:name="android.permission.INTERNET"/> </manifest>

As for the other mentioned file, which looks like this:

> <?xml version="1.0" encoding="utf-8"?> <manifest
> xmlns:android="http://schemas.android.com/apk/res/android"
>     package="com.csdcorp.speech_to_text" >
>
>     <uses-sdk android:minSdkVersion="21" />
>
> </manifest>
</code>```

changing the 21 to 16 is reverted after the attempt to run this app.

How to handle this
1. technically, ie. what is the workaround for this minSDK limitation - one that is at least worth trying?
2. A step back, if there are version issues, how  do you do to avoid them?
Thanks a lot

答:
Edit the build.gradle file in app folder. Search defaultConfig, edit the minSdkVersion from 16 to 21.

File path.

```<code>android\app\build.gradle
</code>```

Title: Bypass Min SDK Version - or what else?

Body:
I am starting with flutter, and overall, I am getting an idea but have hit the wall with what I find to be one of the main reasons to consider migrating from HTML + JQueryMobile: speech to text implementation.

I have found the speech_to_text package (https://pub.dev/packages/speech_to_text#-installing-tab-), followed the instructions to :
1. update the pubspec.yaml file with the dependency &
2. instal the package from command line
3. import the package in the code

but have hit the wall with the minimum SDK requirements not being met by the package. Here is the error message:

C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\android\app\src\debug\AndroidManifest.xml
    Error:  uses-sdk:minSdkVersion 16 cannot be smaller than version 21
    declared in library [:speech_to_text]
    C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\build\speech_to_text\intermediates\library_manifest\debug\AndroidManifest.xml
    as the library might be using APIs not available in 16  Suggestion:
    use a compatible library with a minSdk of at most 16,       or increase
    this project's minSdk version to at least 21,       or use
    tools:overrideLibrary="com.csdcorp.speech_to_text" to force usage (may
    lead to runtime failures)

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [:speech_to_text]
      C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\build\speech_to_text\intermediates\library_manifest\debug\AndroidManifest.xml
      as the library might be using APIs not available in 16      Suggestion:
      use a compatible library with a minSdk of at most 16,
          or increase this project's minSdk version to at least 21,
          or use tools:overrideLibrary="com.csdcorp.speech_to_text" to force usage (may lead to runtime failures)

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 11s Exception: Gradle task assembleDebug failed with
    exit code 1

Strangely, I have managed to bypass this once but can not find the
   relevant piece of code in the app folder now. Worse, the mentioned file

> C:\Users\TOTAL\FlutterPro\Flutter4\flutter4\android\app\src\debug\AndroidManifest.xml
does not contain any reference to SDK, only this:
< <manifest
 <xmlns:android="http://schemas.android.com/apk/res/android"
  <   package="com.example.flutter4">
>
>     <uses-permission android:name="android.permission.INTERNET"/> </manifest>

As for the other mentioned file, which looks like this:

> <?xml version="1.0" encoding="utf-8"?> <manifest
> xmlns:android="http://schemas.android.com/apk/res/android"
>     package="com.csdcorp.speech_to_text" >
>
>     <uses-sdk android:minSdkVersion="21" />
>
> </manifest>

changing the 21 to 16 is reverted after the attempt to run this app.

How to handle this
1. technically, ie. what is the workaround for this minSDK limitation - one that is at least worth trying?
2. A step back, if there are version issues, how  do you do to avoid them?
Thanks a lot

Body:
Edit the build.gradle file in app folder. Search defaultConfig, edit the minSdkVersion from 16 to 21.

File path.

android\app\build.gradle


问:
I can't access my private data member and function in my operator functions
I made this short code and I want to know that why I can't access my private data member and
function in my overloaded insertion & extraction operator even though I can access them from other functions. Can someone please point out the errors for me and explain it to me why is this happening?
Thanks in Advance.

The interface file and implementation file is given below.

Program:-

Header File

```<code>#pragma once
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<cctype>

class  Money {
    long all_cents;
    int digit_to_int(char);
public:
    long getAll_cents();
    friend std::ostream& operator <<(std::ostream&, const Money&);
    friend std::istream& operator >>(std::istream&, Money&);
    friend Money add(const Money&, const Money&);
    friend bool equal(const Money&, const Money&);
    friend Money operator+(const Money&, const Money&);
    friend Money operator==(const Money&, const Money&);
    Money operator-(const Money&);
    Money(long, int);
    Money(long);
    Money();
    double get_values();
    void setMoney(std::istream&);
    void output(std::ostream&);
};
</code>```

Source File:-

```<code>#include "Money.h"

int Money::digit_to_int(char c) {
    return(static_cast<int>(c) - static_cast<int>('0'));
}
long Money::getAll_cents() {
    return this->all_cents;
}
Money Money::operator-(const Money& amount) {
    Money temp;
    temp = -amount.all_cents;
    return temp;
}
Money::Money(long dollars, int cents) :all_cents((dollars * 100) + cents) {
    if (dollars * cents < 0) {
        std::cerr << "Illegal values for dollars and cents !!!";
        exit(1);
    }
}
Money::Money(long dollars) :all_cents(dollars * 100) {
    if (dollars < 0) {
        std::cerr << "Invalid arguments for dollars!!!";
        exit(1);
    }
}
Money::Money() :all_cents(0) {}
double Money::get_values() {
    return (all_cents * 0.01);
}
void Money::setMoney(std::istream& ins) {

    char one_char, decimal_point, digit1, digit2;
    //digits for the amount of cents
    long dollars;
    int cents;
    bool negative; //set to true if input is negative

    std::cout << "Enter the amount = ";

    ins >> one_char;
    if (one_char == ' ') {
        negative = true;
        ins >> one_char;   //read '$'
    }
    else {
        negative = false;
    }

    ins >> dollars >> decimal_point >> digit1 >> digit2;

    if (one_char != '$' || decimal_point != '.' || !isdigit(digit1) || !isdigit(digit2)) {
        std::cerr << "Error  Illegal form for money input\n";
        exit(1);
    }
    cents = digit_to_int(digit1) * 10 + digit_to_int(digit2);

    all_cents = dollars * 100 + cents;
    if (negative)
    {
        all_cents = -all_cents;
    }
}
void Money::output(std::ostream& outs)
{
    long positive_cents, dollars, cents;
    positive_cents = labs(all_cents);
    dollars = positive_cents / 100;
    cents = positive_cents % 100;
    if (all_cents < 0) {
        outs << "-$" << dollars << ".";
    }
    else {
        outs << "$" << dollars << ".";
    }
    if (cents < 10) {
        outs << '0';
    }
    outs << cents << std::endl;
}

std::ostream& operator<<(std::ostream& outs, const Money& amount)
{
    long positive_cents, dollars, cents;
    positive_cents = labs(amount.all_cents);
    dollars = positive_cents / 100;
    cents = positive_cents % 100;
    if (amount.all_cents < 0) {
        outs << "-$" << dollars << ".";
    }
    else {
        outs << "$" << dollars << ".";
    }
    if (cents < 10) {
        outs << '0';
    }
    outs << cents << std::endl;
    return outs;
}

std::istream& operator>>(std::istream& ins, Money& amount)
{
    char one_char, decimal_point, digit1, digit2;
    //digits for the amount of cents
    long dollars;
    int cents;
    bool negative; //set to true if input is negative

    ins >> one_char;
    if (one_char == ' ') {
        negative = true;
        ins >> one_char;   //read '$'
    }
    else {
        negative = false;
    }

    ins >> dollars >> decimal_point >> digit1 >> digit2;

    if (one_char != '$' || decimal_point != '.' || !isdigit(digit1) || !isdigit(digit2)) {
        std::cerr << "Error  Illegal form for money input\n";
        exit(1);
    }
    cents = amount.digit_to_int(digit1) * 10 + amount.digit_to_int(digit2);

    amount.all_cents = dollars * 100 + cents;
    if (negative) {
        amount.all_cents = -amount.all_cents;
    }
    return ins;
}

Money add(const Money& amount1, const Money& amount2) {
    Money temp;
    temp.all_cents = amount1.all_cents + amount2.all_cents;
    return temp;
}

bool equal(const Money& amount1, const Money& amount2) {
    return (amount1.all_cents == amount2.all_cents);
}

Money operator+(const Money& amount1, const Money& amount2) {
    Money temp;
    temp.all_cents = amount1.all_cents + amount2.all_cents;
    return temp;
}

Money operator==(const Money& amount1, const Money& amount2) {
    return (amount1.all_cents == amount2.all_cents);
}
</code>```

答:
In your ostream line number 84 and 87 you should write amount.all_cents as you are in a friend fucntion and you cannot access the private data member all_cents without the object that is amount which you passed in you fucntion.

on line number 83

```<code>positive_cents = labs(amount.all_cents);
</code>```

on line number 86

```<code>if(amount.all_cents<0)
</code>```

and the same error occurs in the istream overloaded fucntion as you are trying to access digit_to_int() which is also private so you need to access it with the . operator through object

on line number 122 - 125

```<code>cents=amount.digit_to_int(digit1)*10+amount.digit_to_int(digit2);
amount.all_cents=dollars*100+cents;
if(negative)
{
amount.all_cents=-amount.all_cents;
}
</code>```

Do know you cant just magically access private members everywhere you need to have appropriate setters and getters for accessing them orelse what is the use of access modifiers in object orientated programming in c++ if you just want them having accessed anywhere then there is no use of object orientated programming and you will just follow procedural programming , Hope this helps out :)

Body:
I made this short code and I want to know that why I can't access my private data member and
function in my overloaded insertion & extraction operator even though I can access them from other functions. Can someone please point out the errors for me and explain it to me why is this happening?
Thanks in Advance.

The interface file and implementation file is given below.

Program:-

Header File

#pragma once
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<cctype>

class  Money {
    long all_cents;
    int digit_to_int(char);
public:
    long getAll_cents();
    friend std::ostream& operator <<(std::ostream&, const Money&);
    friend std::istream& operator >>(std::istream&, Money&);
    friend Money add(const Money&, const Money&);
    friend bool equal(const Money&, const Money&);
    friend Money operator+(const Money&, const Money&);
    friend Money operator==(const Money&, const Money&);
    Money operator-(const Money&);
    Money(long, int);
    Money(long);
    Money();
    double get_values();
    void setMoney(std::istream&);
    void output(std::ostream&);
};

Source File:-

#include "Money.h"

int Money::digit_to_int(char c) {
    return(static_cast<int>(c) - static_cast<int>('0'));
}
long Money::getAll_cents() {
    return this->all_cents;
}
Money Money::operator-(const Money& amount) {
    Money temp;
    temp = -amount.all_cents;
    return temp;
}
Money::Money(long dollars, int cents) :all_cents((dollars * 100) + cents) {
    if (dollars * cents < 0) {
        std::cerr << "Illegal values for dollars and cents !!!";
        exit(1);
    }
}
Money::Money(long dollars) :all_cents(dollars * 100) {
    if (dollars < 0) {
        std::cerr << "Invalid arguments for dollars!!!";
        exit(1);
    }
}
Money::Money() :all_cents(0) {}
double Money::get_values() {
    return (all_cents * 0.01);
}
void Money::setMoney(std::istream& ins) {

    char one_char, decimal_point, digit1, digit2;
    //digits for the amount of cents
    long dollars;
    int cents;
    bool negative; //set to true if input is negative

    std::cout << "Enter the amount = ";

    ins >> one_char;
    if (one_char == ' ') {
        negative = true;
        ins >> one_char;   //read '$'
    }
    else {
        negative = false;
    }

    ins >> dollars >> decimal_point >> digit1 >> digit2;

    if (one_char != '$' || decimal_point != '.' || !isdigit(digit1) || !isdigit(digit2)) {
        std::cerr << "Error  Illegal form for money input\n";
        exit(1);
    }
    cents = digit_to_int(digit1) * 10 + digit_to_int(digit2);

    all_cents = dollars * 100 + cents;
    if (negative)
    {
        all_cents = -all_cents;
    }
}
void Money::output(std::ostream& outs)
{
    long positive_cents, dollars, cents;
    positive_cents = labs(all_cents);
    dollars = positive_cents / 100;
    cents = positive_cents % 100;
    if (all_cents < 0) {
        outs << "-$" << dollars << ".";
    }
    else {
        outs << "$" << dollars << ".";
    }
    if (cents < 10) {
        outs << '0';
    }
    outs << cents << std::endl;
}

std::ostream& operator<<(std::ostream& outs, const Money& amount)
{
    long positive_cents, dollars, cents;
    positive_cents = labs(amount.all_cents);
    dollars = positive_cents / 100;
    cents = positive_cents % 100;
    if (amount.all_cents < 0) {
        outs << "-$" << dollars << ".";
    }
    else {
        outs << "$" << dollars << ".";
    }
    if (cents < 10) {
        outs << '0';
    }
    outs << cents << std::endl;
    return outs;
}

std::istream& operator>>(std::istream& ins, Money& amount)
{
    char one_char, decimal_point, digit1, digit2;
    //digits for the amount of cents
    long dollars;
    int cents;
    bool negative; //set to true if input is negative

    ins >> one_char;
    if (one_char == ' ') {
        negative = true;
        ins >> one_char;   //read '$'
    }
    else {
        negative = false;
    }

    ins >> dollars >> decimal_point >> digit1 >> digit2;

    if (one_char != '$' || decimal_point != '.' || !isdigit(digit1) || !isdigit(digit2)) {
        std::cerr << "Error  Illegal form for money input\n";
        exit(1);
    }
    cents = amount.digit_to_int(digit1) * 10 + amount.digit_to_int(digit2);

    amount.all_cents = dollars * 100 + cents;
    if (negative) {
        amount.all_cents = -amount.all_cents;
    }
    return ins;
}

Money add(const Money& amount1, const Money& amount2) {
    Money temp;
    temp.all_cents = amount1.all_cents + amount2.all_cents;
    return temp;
}

bool equal(const Money& amount1, const Money& amount2) {
    return (amount1.all_cents == amount2.all_cents);
}

Money operator+(const Money& amount1, const Money& amount2) {
    Money temp;
    temp.all_cents = amount1.all_cents + amount2.all_cents;
    return temp;
}

Money operator==(const Money& amount1, const Money& amount2) {
    return (amount1.all_cents == amount2.all_cents);
}

Body:
In your ostream line number 84 and 87 you should write amount.all_cents as you are in a friend fucntion and you cannot access the private data member all_cents without the object that is amount which you passed in you fucntion.

on line number 83

positive_cents = labs(amount.all_cents);

on line number 86

if(amount.all_cents<0)

and the same error occurs in the istream overloaded fucntion as you are trying to access digit_to_int() which is also private so you need to access it with the . operator through object

on line number 122 - 125

cents=amount.digit_to_int(digit1)*10+amount.digit_to_int(digit2);
amount.all_cents=dollars*100+cents;
if(negative)
{
amount.all_cents=-amount.all_cents;
}

Do know you cant just magically access private members everywhere you need to have appropriate setters and getters for accessing them orelse what is the use of access modifiers in object orientated programming in c++ if you just want them having accessed anywhere then there is no use of object orientated programming and you will just follow procedural programming , Hope this helps out :)


问:
How to use resources from an Ammonite script?
I have a few ammonite scripts, they are stored in a folder. That folder is on my PATH, so I can invoke those scripts easily wherever I am.

I can import other ammonite scripts in the same folder:

```<code>$import $file.<name_of_the_other_script>
</code>```

However I want to 'import' a simple text file, save it's content as a string and use it later.

I can do:

val myString = os.read(os.root/"absolute"/"path"/"to"/"the"/"file")

But I would prefer not to use absolute paths, for obvious reasons. Relative path does not work, beacuse it is relative to the folder where I am invoking the script from, and not to where the script is located.

Is there any way to achieve this?

EDIT:

```<code>#/bin/bash

echo $BASH_SOURCE
</code>```

The problem could be solved easily if the functionality in the above bash script could be replicated in Ammonite.

答:
I think you can read resources using ammonite.ops like so:

```<code>val resourcePath = resource/'test/'ammonite/'ops/'folder/"file.txt"
read(resourcePath).length        ==> 18
read.bytes(resourcePath).length  ==> 18
read.lines(resourcePath).length  ==> 1
</code>```

See Reading Resources in the Ammonite documentation.

Body:
I have a few ammonite scripts, they are stored in a folder. That folder is on my PATH, so I can invoke those scripts easily wherever I am.

I can import other ammonite scripts in the same folder:

$import $file.<name_of_the_other_script>

However I want to 'import' a simple text file, save it's content as a string and use it later.

I can do:

val myString = os.read(os.root/"absolute"/"path"/"to"/"the"/"file")

But I would prefer not to use absolute paths, for obvious reasons. Relative path does not work, beacuse it is relative to the folder where I am invoking the script from, and not to where the script is located.

Is there any way to achieve this?

EDIT:

#/bin/bash

echo $BASH_SOURCE

The problem could be solved easily if the functionality in the above bash script could be replicated in Ammonite.

Body:
I think you can read resources using ammonite.ops like so:

val resourcePath = resource/'test/'ammonite/'ops/'folder/"file.txt"
read(resourcePath).length        ==> 18
read.bytes(resourcePath).length  ==> 18
read.lines(resourcePath).length  ==> 1

See Reading Resources in the Ammonite documentation.


问:
Django - validating and saving ModelForm with editable=false fields
I do apologise for all the questions I'm posting today, but I'm at my wits end on this one.

I'm trying to make a Q&A thing for a video site, and I'm trying to get the question to submit via AJAX.

Question model:

```<code>class Question(models.Model):
    user = models.ForeignKey(User, editable=False)
    video = models.ForeignKey(Video, editable=False)
    section = models.ForeignKey(Section, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
</code>```

ModelForm:

```<code>class QuestionForm(ModelForm):
    def __init__(self, video, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['section'].queryset = Section.objects.filter(video=video)

    class Meta:
        model = Question
</code>```

POST parameters sent by jQuery's AJAX request (the video parameter is added by the Javascript code):

```<code>section=6&title=test&description=test&video=1
</code>```

And finally, here's the view I'm working on to handle the submit:

```<code>def question_submit(request):
    u = request.user
    if u.is_authenticated():
        q=QuestionForm(request.POST)

        if q.is_valid():
            logger.debug("YES!")
        else:
            logger.debug("NO!")

        f=q.save(commit=False)
        f.user=u
        f.video_id=int(request.POST['video'])

        f.save()
        return HttpResponse("OK")
    else:
        return JsonResponse({'failed': 'You are not logged in. Try logging in in a new tab, then re-submit your question.'})
</code>```

As suggested by the docs, I'm saving with commit=false so that I can modify the object.

I have two problems:

When it reaches q.is_valid(), it throws the error "'QuestionForm' object has no attribute 'cleaned_data'".

If I take out the q.is_valid() bit, f.save() succeeds, but it inserts a blank row into the database.

To anyone who can help, I owe you my sanity.

答:
It's look like your request.POST is empty. Are you sure that the data is sent by POST method?, check

```<code>if request.method == 'POST:
</code>```

or use

```<code>q=QuestionForm(request.REQUEST)
</code>```

to get POST/GET data.

Body:
I do apologise for all the questions I'm posting today, but I'm at my wits end on this one.

I'm trying to make a Q&A thing for a video site, and I'm trying to get the question to submit via AJAX.

Question model:

class Question(models.Model):
    user = models.ForeignKey(User, editable=False)
    video = models.ForeignKey(Video, editable=False)
    section = models.ForeignKey(Section, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)

ModelForm:

class QuestionForm(ModelForm):
    def __init__(self, video, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['section'].queryset = Section.objects.filter(video=video)

    class Meta:
        model = Question

POST parameters sent by jQuery's AJAX request (the video parameter is added by the Javascript code):

section=6&title=test&description=test&video=1

And finally, here's the view I'm working on to handle the submit:

def question_submit(request):
    u = request.user
    if u.is_authenticated():
        q=QuestionForm(request.POST)

        if q.is_valid():
            logger.debug("YES!")
        else:
            logger.debug("NO!")

        f=q.save(commit=False)
        f.user=u
        f.video_id=int(request.POST['video'])

        f.save()
        return HttpResponse("OK")
    else:
        return JsonResponse({'failed': 'You are not logged in. Try logging in in a new tab, then re-submit your question.'})

As suggested by the docs, I'm saving with commit=false so that I can modify the object.

I have two problems:

When it reaches q.is_valid(), it throws the error "'QuestionForm' object has no attribute 'cleaned_data'".

If I take out the q.is_valid() bit, f.save() succeeds, but it inserts a blank row into the database.

To anyone who can help, I owe you my sanity.

Body:
It's look like your request.POST is empty. Are you sure that the data is sent by POST method?, check

if request.method == 'POST:

or use

q=QuestionForm(request.REQUEST)

to get POST/GET data.


问:
Words frequency with number of letters (basic loop only)
I Want to write C program to print words length and their frequency by letters number with basic loops techniques. I could get the word length work but I stuck with frequency
(example: Do 2 not 3 judge 5 a 1 book 4 (had solved this))

there are # words with 1 letter

there are # words with 2 letter

etc...

```<code>#include <stdio.h>
int main(void) {

char word[30];
int i = 0,b=0,c=0,j=0,d=0;
printf("Please enter a word: ");

for (i = 0; i < 30 ; i++){
    scanf("%s", word);
          while (word[b]!='\0'){
              b++;
          }
    printf("%s %d ", word, b);
    b = 0;
}

return 0;
}
</code>```

答:
Your question wasn't completely clear. But from what I understood, you also wanted to print the number of times(frequency) a word of length 'l' is inputted by the user. So I will answer that :

You could just store the length of the word in an array that the user inputs. Once all the inputs are read, you can just print the frequency of each word length from the stored array

Refer the following code to understand what I meant :

```<code>#include <stdio.h>
int main(void) {

char word[30];
int i = 0,b=0,c=0,j=0,d=0;
int word_length_freq[30]={0};       //an array which will store the frequency of word length(all initialized to 0)
                                   //eg. if word is "hello" it will increase count of word_length_freq[5] by 1
printf("Please enter a word: ");

for (i = 0; i < 3 ; i++){
    scanf("%s", word);
          while (word[b]!='\0'){
              b++;
          }
    word_length_freq[b]++;
    printf("%s %d ", word, b);
    b = 0;
}

for(int i=1;i<30;i++){          //This will print the frequency of all words from length 1 to 30
    printf("There are %d words of length %d\n",word_length_freq[i],i);
}

return 0;
}
</code>```

I hope this solves your question !

Body:
I Want to write C program to print words length and their frequency by letters number with basic loops techniques. I could get the word length work but I stuck with frequency
(example: Do 2 not 3 judge 5 a 1 book 4 (had solved this))

there are # words with 1 letter

there are # words with 2 letter

etc...

#include <stdio.h>
int main(void) {

char word[30];
int i = 0,b=0,c=0,j=0,d=0;
printf("Please enter a word: ");

for (i = 0; i < 30 ; i++){
    scanf("%s", word);
          while (word[b]!='\0'){
              b++;
          }
    printf("%s %d ", word, b);
    b = 0;
}

return 0;
}

Body:
Your question wasn't completely clear. But from what I understood, you also wanted to print the number of times(frequency) a word of length 'l' is inputted by the user. So I will answer that :

You could just store the length of the word in an array that the user inputs. Once all the inputs are read, you can just print the frequency of each word length from the stored array

Refer the following code to understand what I meant :

#include <stdio.h>
int main(void) {

char word[30];
int i = 0,b=0,c=0,j=0,d=0;
int word_length_freq[30]={0};       //an array which will store the frequency of word length(all initialized to 0)
                                   //eg. if word is "hello" it will increase count of word_length_freq[5] by 1
printf("Please enter a word: ");

for (i = 0; i < 3 ; i++){
    scanf("%s", word);
          while (word[b]!='\0'){
              b++;
          }
    word_length_freq[b]++;
    printf("%s %d ", word, b);
    b = 0;
}

for(int i=1;i<30;i++){          //This will print the frequency of all words from length 1 to 30
    printf("There are %d words of length %d\n",word_length_freq[i],i);
}

return 0;
}

I hope this solves your question !


问:
Azure P2S client traffic to S2S network
My VNet won't allow me to connect to the s2s location via p2s connection.

I'm trying to connect the Azure VPN client on my machine and reach a site that is allowed in a network which I have a s2s connection to.

Here's the thing, I can't get traffic to flow from my pc running the VPN client, out to the target site.

Topology

PC > VPN Client > VNet via p2s > Remote network via s2s > FTP server

I'd like to be able to ping the FTP server from my machine.
Currently only devices in the VNet can ping.

I tried setting up BGP but it broke the connection, as I don't really know how things should be set.

I don't have access to the remote site or it's devices.
I have a Azure local network gateway which is configured as the s2s location.

I'm sorry if that doesn't make sense.

Edit: here is the picture of the network

答: My solution to this as I can't enable BPG is to use a proxy server within the VNet.</p>

Title: Azure P2S client traffic to S2S network


问:
Process.Start(url) in a loop not launching every instance
I have a need to launch multiple browser instances / tabs in succession but using Process.Start(url) I am finding that not every URL is launched.

```<code>    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("http://localhost/#" + i.ToString());
    }
</code>```

For any value n > 1 I find that only the last URL is opened in the browser (I'm testing with IE as the default browser). If I add a Thread.Sleep(1000) after Process.Start then I see a variety of behavior: sometimes all n are created; sometimes a subset.

The following does work as expected, but assumes IE (would rather use the default browser) and launches n browser instances rather than n tabs:

```<code>    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("iexplore.exe", "http://localhost/#" + i.ToString());
    }
</code>```

I would prefer to get it working with the default browser behavior, but need it to be deterministic.

答:
I'm completely winging this one, but here it goes.  Derived from @tofutim's answer.  Basically, use locking and monitor the Process state with a Timer.  This of course is highly dependent on being able to determine if the process has successfully started, which is being tested with

```<code>if (p.HasExited == false && p.Id != 0){ }
</code>```

The full solution:

```<code>bool isLaunching = false;
object launchingLock = new object();
Process p = null;

Timer timer = new Timer(new TimerCallback((state) =>
{
    lock (launchingLock)
    {
        if (isLaunching)
        {
            if (p != null && p.HasExited == false && p.Id != 0)
            {
                // Success!
                isLaunching = false;
                Monitor.PulseAll(launchingLock);
            }
            else if(p != null && p.HasExited)
            {
                // Some sort of failure code/notification?
                // We still want to pulse though, otherwise thread will be forever kept waiting
                isLaunching = false;
                Monitor.PulseAll(launchingLock);
            }
        }
    }
}));

timer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

foreach (string url in urls)
{
    try
    {
        lock (launchingLock)
        {
            isLaunching = true;
            p = new Process();
            p.StartInfo.FileName = browser;
            p.StartInfo.Arguments = url;
            p.Start();

            // Wait until the process has finished starting before moving on
            Monitor.Wait(launchingLock);
        }
    }
    catch (Exception ex)
    {
        // something
    }
}

timer.Dispose();
</code>```

Body:
I have a need to launch multiple browser instances / tabs in succession but using Process.Start(url) I am finding that not every URL is launched.

    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("http://localhost/#" + i.ToString());
    }

For any value n > 1 I find that only the last URL is opened in the browser (I'm testing with IE as the default browser). If I add a Thread.Sleep(1000) after Process.Start then I see a variety of behavior: sometimes all n are created; sometimes a subset.

The following does work as expected, but assumes IE (would rather use the default browser) and launches n browser instances rather than n tabs:

    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("iexplore.exe", "http://localhost/#" + i.ToString());
    }

I would prefer to get it working with the default browser behavior, but need it to be deterministic.

Body:
I'm completely winging this one, but here it goes.  Derived from @tofutim's answer.  Basically, use locking and monitor the Process state with a Timer.  This of course is highly dependent on being able to determine if the process has successfully started, which is being tested with

if (p.HasExited == false && p.Id != 0){ }

The full solution:

bool isLaunching = false;
object launchingLock = new object();
Process p = null;

Timer timer = new Timer(new TimerCallback((state) =>
{
    lock (launchingLock)
    {
        if (isLaunching)
        {
            if (p != null && p.HasExited == false && p.Id != 0)
            {
                // Success!
                isLaunching = false;
                Monitor.PulseAll(launchingLock);
            }
            else if(p != null && p.HasExited)
            {
                // Some sort of failure code/notification?
                // We still want to pulse though, otherwise thread will be forever kept waiting
                isLaunching = false;
                Monitor.PulseAll(launchingLock);
            }
        }
    }
}));

timer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

foreach (string url in urls)
{
    try
    {
        lock (launchingLock)
        {
            isLaunching = true;
            p = new Process();
            p.StartInfo.FileName = browser;
            p.StartInfo.Arguments = url;
            p.Start();

            // Wait until the process has finished starting before moving on
            Monitor.Wait(launchingLock);
        }
    }
    catch (Exception ex)
    {
        // something
    }
}

timer.Dispose();


问:
How to combine a pagination with Observables and the AsyncPipe in Angular 9?
There's a list of products coming from an API. The products are paginated and the user can switch to another page. The simplified template looks like this:

```<code><ul>
  <li *ngFor="let product of products$ | async">{{ product.name }}</li>
</ul>

<button type="button" (click)="gotoPage(1)">1</button>
<button type="button" (click)="gotoPage(2)">2</button>
</code>```

The component does look like this:

```<code>export class ProductsComponent implements OnInit {
  products$: Observable<Product[]>;

  constructor(
    private service: ProductService
  ) { }

  ngOnInit() {
    this.products$ = this.service.getAll({page: 1});
  }

  gotoPage(page: number): void {
    this.products$ = this.service.getAll({page: page});
  }
}
</code>```

My questions are:
Is this the correct way to update the Obersavble? Or does this produce memory leaks?

As a note: The URL will not change and the component should not reloaded on pagination change.

答:
You can always prevent memory leaks the takeUntil + ngOnDestroy pattern.

For example,

declare a new variable private onDestroy$: Subject<void> = new Subject<void>();

```<code>this.service.getAll({page: page})
.pipe(takeUntil(this.onDestroy$))
.subscribe(... do the necessary ...);
</code>```

And later, in the onDestroy() life cycle hook, you may implement the following :

```<code> public ngOnDestroy(): void {
   this.onDestroy$.next();
   this.onDestroy$.complete()
 }
</code>```

What we have actually done is declare a new observable; Then, by using pipe method with takeUntil we inform compiler that we want to unsubscribe from the observable when any value appear in onDestroy$, Then, by using pipe method with takeUntil we inform compiler that we want to unsubscribe from the observable when any value appear in onDestroy$, thereby preventing memory leaks.

Body:
There's a list of products coming from an API. The products are paginated and the user can switch to another page. The simplified template looks like this:

{{ product.name }}

<button type="button" (click)="gotoPage(1)">1</button>
<button type="button" (click)="gotoPage(2)">2</button>

The component does look like this:

export class ProductsComponent implements OnInit {
  products$: Observable<Product[]>;

  constructor(
    private service: ProductService
  ) { }

  ngOnInit() {
    this.products$ = this.service.getAll({page: 1});
  }

  gotoPage(page: number): void {
    this.products$ = this.service.getAll({page: page});
  }
}

My questions are:
Is this the correct way to update the Obersavble? Or does this produce memory leaks?

As a note: The URL will not change and the component should not reloaded on pagination change.

Body:
You can always prevent memory leaks the takeUntil + ngOnDestroy pattern.

For example,

declare a new variable private onDestroy$: Subject<void> = new Subject<void>();

this.service.getAll({page: page})
.pipe(takeUntil(this.onDestroy$))
.subscribe(... do the necessary ...);

And later, in the onDestroy() life cycle hook, you may implement the following :

 public ngOnDestroy(): void {
   this.onDestroy$.next();
   this.onDestroy$.complete()
 }

What we have actually done is declare a new observable; Then, by using pipe method with takeUntil we inform compiler that we want to unsubscribe from the observable when any value appear in onDestroy$, Then, by using pipe method with takeUntil we inform compiler that we want to unsubscribe from the observable when any value appear in onDestroy$, thereby preventing memory leaks.


问:
What I'm doing wrong with CompletableFuture that aren't executing in parallel
I have splitted a list in 5 parts, and I want to execute in parallel using restTemplate, I have the following method:

```<code>@Async
private CompletableFuture<List<Cidade>> MontarCidadesPorEstado(List<Cidade> listaCidades, List<UF> estado) {

    estado.forEach(es -> {
            Map<String, String> param = new HashMap<String, String>();
            param.put("UF", es.getSigla());

            Cidade[] cidades = restTemplate.getForObject(url, Cidade[].class, param);

            listaCidades.addAll(Arrays.asList(cidades));
     });

    return CompletableFuture.completedFuture(listaCidades);
}
</code>```

So created a List of CompletableFuture to execute all of them in parallel, but when an add each CompletableFuture into a list it's already execute it without make it parallel, ex:

```<code>     List<List<UF>> subSets = Lists.partition(estados, 5);
     List<CompletableFuture<List<Cidade>>> lstCompletableFuture = new ArrayList();

     subSets.forEach(estado -> {
         lstCompletableFuture.add(MontarCidadesPorEstado(listaCidades, estado));
     });

     CompletableFuture.allOf(lstCompletableFuture.toArray(new CompletableFuture[lstCompletableFuture.size()]));
</code>```

What I'm doing wrong, I thought it's supposed to execute the method MontarCidadesPorEstado when I call CompletableFuture.allOf.

答:
I assume that MontarCidadesPorEstado is a local method call.

Therefore the call is local it doesn't go through a proxy and is not asynchronous.

You have define the MontarCidadesPorEstado method in another bean and then call this bean.

Body:
I have splitted a list in 5 parts, and I want to execute in parallel using restTemplate, I have the following method:

@Async
private CompletableFuture<List<Cidade>> MontarCidadesPorEstado(List<Cidade> listaCidades, List<UF> estado) {

    estado.forEach(es -> {
            Map<String, String> param = new HashMap<String, String>();
            param.put("UF", es.getSigla());

            Cidade[] cidades = restTemplate.getForObject(url, Cidade[].class, param);

            listaCidades.addAll(Arrays.asList(cidades));
     });

    return CompletableFuture.completedFuture(listaCidades);
}

So created a List of CompletableFuture to execute all of them in parallel, but when an add each CompletableFuture into a list it's already execute it without make it parallel, ex:

     List<List<UF>> subSets = Lists.partition(estados, 5);
     List<CompletableFuture<List<Cidade>>> lstCompletableFuture = new ArrayList();

     subSets.forEach(estado -> {
         lstCompletableFuture.add(MontarCidadesPorEstado(listaCidades, estado));
     });

     CompletableFuture.allOf(lstCompletableFuture.toArray(new CompletableFuture[lstCompletableFuture.size()]));

What I'm doing wrong, I thought it's supposed to execute the method MontarCidadesPorEstado when I call CompletableFuture.allOf.