问:
I need to map keys to csv values that I read from an URL using Python 2.7
I need to map keys to csv values that I read from an URL using Python 2.7.
The target computer that will run this Python script is a RaspberryPi 3 running Raspbian 9 (Raspberry Pi distribution that is based on Debian 9).

I need to read a continously changing set of values from a Solar Inverter (a SAJ Sununo 3K-M solar inverter to be precise) and map it to fixed set of fieldnames.

The order of the expected values is exactly like the order of the fieldnames, but they need to be mapped to each other. The URL is also what it needs to be be

I have tried to read the values and I can succesfully read the values, but I can't actually map the values to variables to do something useful.

An example of the response that I get if I read the csv values is below:

```<code>['1', '4378', '998', '668', '69', '1842', '328', '1226', '336', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '992', '4999', '2364', '421', '65535', '65535', '65535', '65535', '3663', '348', '343', '2']
</code>```

I would very much appreciate it if someone could have a crack at what I'm trying to achieve.

I have copy/pasted the code that I have written sofar below.

```<code>#!/usr/bin/python
# This script reads the output of SAJ Solar Inverters and parses it so that it can be used in a meaningful way
# Import libraries
import csv
import urllib2
import base64

def main():
    global username,password, responselist
username = 'USER-LOGIN'
password = 'USER-PASSWORD'
statusfieldnames = ['Statistics', 'Total_Generated', 'Total_Running Time', 'Today_Generated', 'Today_Running_Time', 'PV1_Voltage', 'PV1_Current', 'PV2_Voltage', 'PV2_Current', 'PV3_Voltage', 'PV3_Current', 'PV1_StrCurr1', 'PV1_StrCurr2', 'PV1_StrCurr3', 'PV1_StrCurr4', 'PV2_StrCurr1', 'PV2_StrCurr2', 'PV2_StrCurr3', 'PV2_StrCurr4', 'PV3_StrCurr1', 'PV3_StrCurr2', 'PV3_StrCurr3', 'PV3_StrCurr4', 'Grid-connected_Power', 'Grid-connected_Frequency', 'Line1_Voltage', 'Line1_Current', 'Line2_Voltage', 'Line2_Current', 'Line3_Voltage', 'Line3_Current', 'Bus_Voltage', 'Device_Temperature', 'CO2emission_Reduction', 'Other_Status']

request = urllib2.Request("http://IP-ADDRESS-OF-RPI3/status/status.php")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
status = csv.reader(response, delimiter=",")
</code>```

答:
Supposing the ordering and lengths are exactly the same you could use this code:</p>

```<code>valDict={}
for f, v in zip(statusfieldnames, response):
    valDict[f] = v
</code>```

Body:
I need to map keys to csv values that I read from an URL using Python 2.7.
The target computer that will run this Python script is a RaspberryPi 3 running Raspbian 9 (Raspberry Pi distribution that is based on Debian 9).

I need to read a continously changing set of values from a Solar Inverter (a SAJ Sununo 3K-M solar inverter to be precise) and map it to fixed set of fieldnames.

The order of the expected values is exactly like the order of the fieldnames, but they need to be mapped to each other. The URL is also what it needs to be be

I have tried to read the values and I can succesfully read the values, but I can't actually map the values to variables to do something useful.

An example of the response that I get if I read the csv values is below:

['1', '4378', '998', '668', '69', '1842', '328', '1226', '336', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '992', '4999', '2364', '421', '65535', '65535', '65535', '65535', '3663', '348', '343', '2']

I would very much appreciate it if someone could have a crack at what I'm trying to achieve.

I have copy/pasted the code that I have written sofar below.

#!/usr/bin/python
# This script reads the output of SAJ Solar Inverters and parses it so that it can be used in a meaningful way
# Import libraries
import csv
import urllib2
import base64

def main():
    global username,password, responselist
username = 'USER-LOGIN'
password = 'USER-PASSWORD'
statusfieldnames = ['Statistics', 'Total_Generated', 'Total_Running Time', 'Today_Generated', 'Today_Running_Time', 'PV1_Voltage', 'PV1_Current', 'PV2_Voltage', 'PV2_Current', 'PV3_Voltage', 'PV3_Current', 'PV1_StrCurr1', 'PV1_StrCurr2', 'PV1_StrCurr3', 'PV1_StrCurr4', 'PV2_StrCurr1', 'PV2_StrCurr2', 'PV2_StrCurr3', 'PV2_StrCurr4', 'PV3_StrCurr1', 'PV3_StrCurr2', 'PV3_StrCurr3', 'PV3_StrCurr4', 'Grid-connected_Power', 'Grid-connected_Frequency', 'Line1_Voltage', 'Line1_Current', 'Line2_Voltage', 'Line2_Current', 'Line3_Voltage', 'Line3_Current', 'Bus_Voltage', 'Device_Temperature', 'CO2emission_Reduction', 'Other_Status']

request = urllib2.Request("http://IP-ADDRESS-OF-RPI3/status/status.php")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
status = csv.reader(response, delimiter=",")

Body:
Supposing the ordering and lengths are exactly the same you could use this code:

valDict={}
for f, v in zip(statusfieldnames, response):
    valDict[f] = v


来源: stackexchange

问:
Bash Check for Git Updates on Login
I am attempting to check my git repo if there are updates.
I need to do this when I login to my Ubuntu server, so I figured I would modify the /etc/update-motd.d/90-updates-available script with the following

It is supposed to cd into my repo once it is found, and then compare it to the remote repo, if remote is newer, print the notice.

```<code>#!/bin/sh

stamp="/var/lib/update-notifier/updates-available"

[ ! -r "$stamp" ] || cat "$stamp"

cd $(find / -wholename '*-Commander*/.git' | xargs -n 1 dirname)

UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
echo "----------------------------------------------------------"
echo ""
if [ $LOCAL = $BASE ]; then
    echo "Repo Need to be Updated"
    MEM=$(free -m | grep -oP '\d+' | head -n 1);
    if [ $MEM -lt 2048 ]; then
        echo "Low Mem Check"
    fi;
fi;
echo ""
echo "----------------------------------------------------------"
</code>```

what I am finding is, no matter what.. on login to the machine, it still shows Repo Need to be Updated, even if it is up to date.

Note, the repo was pulled as a sudoer, logging into the machine does logs in as a normal user at first.

What am I doing wrong?

答:
Single '=' is attribuition.

Use double '==' to compare.

So:

```<code>if [ $LOCAL == $BASE ]; then
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash Check for Git Updates on Login

Body:
I am attempting to check my git repo if there are updates.
I need to do this when I login to my Ubuntu server, so I figured I would modify the /etc/update-motd.d/90-updates-available script with the following

It is supposed to cd into my repo once it is found, and then compare it to the remote repo, if remote is newer, print the notice.

#!/bin/sh

stamp="/var/lib/update-notifier/updates-available"

[ ! -r "$stamp" ] || cat "$stamp"

cd $(find / -wholename '*-Commander*/.git' | xargs -n 1 dirname)

UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
echo "----------------------------------------------------------"
echo ""
if [ $LOCAL = $BASE ]; then
    echo "Repo Need to be Updated"
    MEM=$(free -m | grep -oP '\d+' | head -n 1);
    if [ $MEM -lt 2048 ]; then
        echo "Low Mem Check"
    fi;
fi;
echo ""
echo "----------------------------------------------------------"

what I am finding is, no matter what.. on login to the machine, it still shows Repo Need to be Updated, even if it is up to date.

Note, the repo was pulled as a sudoer, logging into the machine does logs in as a normal user at first.

What am I doing wrong?

Body:
Single '=' is attribuition.

Use double '==' to compare.

So:

if [ $LOCAL == $BASE ]; then


问:
How to create a shift key + mouse click event that would change the color of a black button to a yellow button on click? JavaScript
I am creating a minesweeper game and am trying to create an event where if the user holds down the shift key and left clicks their mouse simultaneously then the button (background-color is black) that I created for the field will turn yellow to indicate a button that is flagged. Here is what I have so far. The attribute ('data-value', 0) means that that button does not have a mine or number label that will indicate how far it is from the mine.

JS:

```<code>$('button').getAttribute('data-value', 0).getAttribute('data-x', j).getAttribute('data-y', i).getAttribute('data-visible', false).getAttribute('data-mine', false).click(function (e) {
    if (e.shiftKey) {
        $('button').addClass('flag');
    }
});
</code>```

CSS:

```<code>table td button {
    background-color: black;
    color: white;
    width: 2em;
    height: 2em;
}

.flag {
    background-color: yellow;
}
</code>```

Thank you for your help.

答:
If you are not able to detect the key combination you can use the following script to do that, see below code try pressing SHIFT+ mouse left click to detect it.

let ShiftOn = false;
$(document).ready(function() {
  $(document).keydown(function(e) {
    let isShiftOn = e.which == "16";

    (isShiftOn) && (ShiftOn = true);
  }).keyup(function() {
    ShiftOn = false;
  });
  $("#detectable-area").on('click', function() {
    (ShiftOn) && console.log('SHIFT +LEFT Click');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#detectable-area {
  width: 100%;
  height: 250px;
  background: #c8c8c8;
  vertical-align: middle;
  text-align: center;
  line-height: 250px;
}</code>```

Press SHIFT + click anywhere in the div to detect.
```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a minesweeper game and am trying to create an event where if the user holds down the shift key and left clicks their mouse simultaneously then the button (background-color is black) that I created for the field will turn yellow to indicate a button that is flagged. Here is what I have so far. The attribute ('data-value', 0) means that that button does not have a mine or number label that will indicate how far it is from the mine.

JS:

$('button').getAttribute('data-value', 0).getAttribute('data-x', j).getAttribute('data-y', i).getAttribute('data-visible', false).getAttribute('data-mine', false).click(function (e) {
    if (e.shiftKey) {
        $('button').addClass('flag');
    }
});

CSS:

table td button {
    background-color: black;
    color: white;
    width: 2em;
    height: 2em;
}

.flag {
    background-color: yellow;
}

Thank you for your help.

Body:
If you are not able to detect the key combination you can use the following script to do that, see below code try pressing SHIFT+ mouse left click to detect it.

let ShiftOn = false;
$(document).ready(function() {
  $(document).keydown(function(e) {
    let isShiftOn = e.which == "16";

    (isShiftOn) && (ShiftOn = true);
  }).keyup(function() {
    ShiftOn = false;
  });
  $("#detectable-area").on('click', function() {
    (ShiftOn) && console.log('SHIFT +LEFT Click');
  });
});

div#detectable-area {
  width: 100%;
  height: 250px;
  background: #c8c8c8;
  vertical-align: middle;
  text-align: center;
  line-height: 250px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="detectable-area">Press SHIFT + click anywhere in the div to detect.</div>


问:
how can check panorama photo android?
I need to show all panorama photo in Gallery android. But it extension is jpg same regular photo.

How can I check a photo in Gallery android is Panorama photo?

Thanks

答:
Ask the mediadatabase through a filter condition

```<code>Where ((height/width > 2) or (width/height >= 2))
</code>```

something like this

```<code>    ContentResolver resolver = context.getContentResolver();
    Cursor query = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      sqlSelectColums, '((height/width > 2) or (width/height >= 2))',
      null, sqlSortOrder);
</code>```

Title: how can check panorama photo android?

Body:
Ask the mediadatabase through a filter condition

Where ((height/width > 2) or (width/height >= 2))

something like this

    ContentResolver resolver = context.getContentResolver();
    Cursor query = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      sqlSelectColums, '((height/width > 2) or (width/height >= 2))',
      null, sqlSortOrder);


问:
{TypeError: unsupported operand type(s) for +: 'int' and 'str'} with input
I am new to python and I was learning with Grok, but I got stuck on this part</p>

```<code>money = input("Enter the expenses: ")
addup = money.split()
total = sum(addup)
print("Total: ", total)
</code>```

答:
What you need to do is:

```<code>money=map(float,input().split()) #could have use int as well if input was a sequence of integers
total=sum(money)
print("Total:",total)
</code>```

You could also do this:

```<code>    Total=sum(map(float,input().split())) #could have use int as well if input was a sequence of integers
    print("Total:",total)
</code>```

In python input is default taken as a string you need to typecast it

```<code>int(input("enter the expenses should work: "))
</code>```

or if it is float

```<code>float(input("enter the expenses should work: "))
</code>```

in general all you need is  to typecast or if your input is a list of numbers do

```<code>map(int,input().split()) #can use float here as well
</code>```

In python 2.x map will create a list and in python 3.x it will create generator.

Body:
I am new to python and I was learning with Grok, but I got stuck on this part

money = input("Enter the expenses: ")
addup = money.split()
total = sum(addup)
print("Total: ", total)

Body:
What you need to do is:

money=map(float,input().split()) #could have use int as well if input was a sequence of integers
total=sum(money)
print("Total:",total)

You could also do this:

    Total=sum(map(float,input().split())) #could have use int as well if input was a sequence of integers
    print("Total:",total)

In python input is default taken as a string you need to typecast it

int(input("enter the expenses should work: "))

or if it is float

float(input("enter the expenses should work: "))

in general all you need is  to typecast or if your input is a list of numbers do

map(int,input().split()) #can use float here as well

In python 2.x map will create a list and in python 3.x it will create generator.


问:
Python, api requests
I have a following question. Is there any possibility to enlarge the speed of sending the single api request. I want to send request and obtain json as a result. When i use requests.get(url) the time is about 150ms.
I would like to make this time lower. My aim is to speed up single request. Is there any possibility to do this?

答:
GLOBAL ANSWER ( Read These methods, beside...you can try a lot of modules that can send/receive your current data to your target server ):

Check your internet connection speed, pause/stop/disable all of your downloading process.

Disable your firewall/antivirus/os_default_defender or any kind of security programs who scan your internet protocols and suspend your net IOs for a while.

Check your vpn/proxy or any kind of tunneler programs! ( because they can check and suspend your connections and make your internet connection slower ).

Check your default DNS ips, choose The fastest DNS server in the world like google = 8.8.8.8 or others ...

Clean your virtual ram buffer and check your os disk IO speed ( close your heavy programs such as converter programs ... )

Change your programming language !!! python is good but it is not fastest language for send/receive data from www. even you can try low level programming ( for your requests pyhton use your os internal services!!this bridge can make your connection slower, you will not have this bridge if you use your os friendly langs ( like .NET langs on windows ).

You can compress your data to make your request faster.

At last it depends on your target server response and your os!! linux has different net IOs handler from windows!!

Good Luck ...

Title: Python, api requests


问:
jQuery var's aren't functioning
I'm trying to build a form that will check (live) to see whether a person has mismatched a string when entered into text fields. The practice is a user entering data into a password form.

HTML Below:

```<code><div class="form-group">
     <input type="password" name="password" id="password" class="form-control" value="" placeholder="Password" onKeyUp="checkPasswordStrength();">
</div>
<div class="form-group">
      <input type="password" name="vPass" id="cpassword" class="form-control" value="" placeholder="Password">
      <span id="output"></span>
</div>
</code>```

And below is the jQuery used:

```<code><script type ="text/javascript">
$("#cpassword").blur(function checkPassMatch(){
    var originEmpt = $("#password").text(""); // Checking if input is empty
    var origin = $("#password").text(); // Password
    var conf = $("#cpassword").text(); // Confirm password
    if (origin != conf){
        $("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
    } else {
        $("#output").html("");
    }
    if (originEmpt){
        $("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
    } else{
        $("#output").html("");
    }
})
</script>
</code>```

Through debugging, if I totally remove the first if else statement from the jQuery, I can receive the $("output").html(); as desired.

I have tried for both input fields:
$("#password").text() / .val(); / .html(); / .innerHTML();

But the code still fails to check whether one input field matches another. Any ideas why?

答:
Cause your second checks output overrides the first one. You need to nest it:</p>

```<code>if (origin != conf){
    $("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else if (!originEmpt){
    $("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
    $("#output").html("");
}
</code>```

Title: jQuery var's aren't functioning

Body:
I'm trying to build a form that will check (live) to see whether a person has mismatched a string when entered into text fields. The practice is a user entering data into a password form.

HTML Below:

     <input type="password" name="password" id="password" class="form-control" value="" placeholder="Password" onKeyUp="checkPasswordStrength();">

      <input type="password" name="vPass" id="cpassword" class="form-control" value="" placeholder="Password">

And below is the jQuery used:

Through debugging, if I totally remove the first if else statement from the jQuery, I can receive the $("output").html(); as desired.

I have tried for both input fields:
$("#password").text() / .val(); / .html(); / .innerHTML();

But the code still fails to check whether one input field matches another. Any ideas why?

Body:
Cause your second checks output overrides the first one. You need to nest it:

if (origin != conf){
    $("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else if (!originEmpt){
    $("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
    $("#output").html("");
}


问:
Background image displays wrong, don't know what to do
i'm pretty new to CSS but I made something in illustrator (web)and wanted to put this as background-image in css. I've put the image in a
 and CSS in I just put background-image: url(berg.jpg), i'm sure the url is correct, but it doesn't display anything. I've put height: 100% in css after that and it showed up but it was all zoomed in and only displays a small corner of the picture because of the zoom. How can I display this correctly? The image size is width: 1366px; height:768px.

Sorry if this is already asked but I couldn't seem to find it. Thx on advance.

答:
Your image is displaying as full size.  If you add the background-size attribute to your css, you can define the size.

See this link for all background-size options:
https://www.w3schools.com/cssref/css3_pr_background-size.asp

You can also define the background-position to have image centered, etc.
https://www.w3schools.com/cssref/pr_background-position.asp

CSS example

```<code>    #problem-image {
      height: 200px;
      width: 200px;
      background-image: url('https://images.unsplash.com/photo-1463852247062-1bbca38f7805?auto=format&fit=crop&w=2255&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D');
    }

    #correct-image {
      height: 200px;
      width: 200px;
      background-image: url('https://images.unsplash.com/photo-1463852247062-1bbca38f7805?auto=format&fit=crop&w=2255&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D');
      background-size: cover;
      background-position: center center;
    }
</code>```

See jsfiddle for full working example:
https://jsfiddle.net/3o8b2e4s/

Body:
Your image is displaying as full size.  If you add the background-size attribute to your css, you can define the size.

See this link for all background-size options:
https://www.w3schools.com/cssref/css3_pr_background-size.asp

You can also define the background-position to have image centered, etc.
https://www.w3schools.com/cssref/pr_background-position.asp

CSS example

    #problem-image {
      height: 200px;
      width: 200px;
      background-image: url('https://images.unsplash.com/photo-1463852247062-1bbca38f7805?auto=format&fit=crop&w=2255&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D');
    }

    #correct-image {
      height: 200px;
      width: 200px;
      background-image: url('https://images.unsplash.com/photo-1463852247062-1bbca38f7805?auto=format&fit=crop&w=2255&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D');
      background-size: cover;
      background-position: center center;
    }

See jsfiddle for full working example:
https://jsfiddle.net/3o8b2e4s/


问:
Replace a part of a file by a part of another file
I have two files containing a lot of floating numbers. I would like to replace one of the floating numbers from file 1 by a floating number from File 2, using lines and characters to find the numbers (and not their values).

A lot of topics on the subject, but I couldn't find anything that uses a second file to copy the values from.

Here are examples of my two files:

File1:

```<code>  14    4
2.64895E-01  4.75834E+02  2.85629E+05  -9.65829E+01
2.76893E-01  8.53749E+02  4.56385E+05  -7.65658E+01
6.25576E-01  5.27841E+02  5.72960E+05  -7.46175E+01
8.56285E-01  4.67285E+02  5.75962E+05  -5.17586E+01
</code>```

File2:

```<code>Some text on the first line
1
Some text on the third line
0
AND01  0.53758275  0.65728944
AND02  0.64889566  0.53386002
AND03  0.65729386  0.64628194
AND04  0.26586960  0.46582925
AND05  0.46480534  0.57415869
</code>```

In this particular example, I would like to replace the first number of the second line of File1 (2.64895E-01) by the second floating number written on line 5 of File2 (0.65728944).

Note: the value of the numbers will change according to which file I consider, so I have to identify the numbers by their positions inside the files.

I am very new to using bash scripts and have only use "sed" command till now to modify my files.

Any help is welcome :)
Thanks a lot for your inputs!

答:
It's not hard to do it in bash, but if that's not a strict requirement, an easier and more concise solution is possible with an actual text-processing tool like awk:

```<code>awk 'NR==5 {val=$2}  NR>FNR {FNR==2 && $1=val; print}' file2 file1
</code>```

Explanation: read file2 first, and store the second field of the 5th record in variable val (the first part: NR==5 {val=$2}). Then, read file1, print every line, but replace the first field of the second record (FNR is current-file record number, and NR is total number of records in all files so far) with value stored in val.

In general, an awk program consists of pattern { actions } sequences. pattern is a condition under which a series of actions will get executed. $1..$NF are variables with field values, and each line (record) is split into fields on the field separator (FS variable, or -F'..' option), which defaults to a space.

The result (output):

```<code>  14    4
0.53758275 4.75834E+02 2.85629E+05 -9.65829E+01
2.76893E-01  8.53749E+02  4.56385E+05  -7.65658E+01
6.25576E-01  5.27841E+02  5.72960E+05  -7.46175E+01
8.56285E-01  4.67285E+02  5.75962E+05  -5.17586E+01
</code>```

Body:
I have two files containing a lot of floating numbers. I would like to replace one of the floating numbers from file 1 by a floating number from File 2, using lines and characters to find the numbers (and not their values).

A lot of topics on the subject, but I couldn't find anything that uses a second file to copy the values from.

Here are examples of my two files:

File1:

  14    4
2.64895E-01  4.75834E+02  2.85629E+05  -9.65829E+01
2.76893E-01  8.53749E+02  4.56385E+05  -7.65658E+01
6.25576E-01  5.27841E+02  5.72960E+05  -7.46175E+01
8.56285E-01  4.67285E+02  5.75962E+05  -5.17586E+01

File2:

Some text on the first line
1
Some text on the third line
0
AND01  0.53758275  0.65728944
AND02  0.64889566  0.53386002
AND03  0.65729386  0.64628194
AND04  0.26586960  0.46582925
AND05  0.46480534  0.57415869

In this particular example, I would like to replace the first number of the second line of File1 (2.64895E-01) by the second floating number written on line 5 of File2 (0.65728944).

Note: the value of the numbers will change according to which file I consider, so I have to identify the numbers by their positions inside the files.

I am very new to using bash scripts and have only use "sed" command till now to modify my files.

Any help is welcome :)
Thanks a lot for your inputs!

Body:
It's not hard to do it in bash, but if that's not a strict requirement, an easier and more concise solution is possible with an actual text-processing tool like awk:

awk 'NR==5 {val=$2}  NR>FNR {FNR==2 && $1=val; print}' file2 file1

Explanation: read file2 first, and store the second field of the 5th record in variable val (the first part: NR==5 {val=$2}). Then, read file1, print every line, but replace the first field of the second record (FNR is current-file record number, and NR is total number of records in all files so far) with value stored in val.

In general, an awk program consists of pattern { actions } sequences. pattern is a condition under which a series of actions will get executed. $1..$NF are variables with field values, and each line (record) is split into fields on the field separator (FS variable, or -F'..' option), which defaults to a space.

The result (output):

  14    4
0.53758275 4.75834E+02 2.85629E+05 -9.65829E+01
2.76893E-01  8.53749E+02  4.56385E+05  -7.65658E+01
6.25576E-01  5.27841E+02  5.72960E+05  -7.46175E+01
8.56285E-01  4.67285E+02  5.75962E+05  -5.17586E+01


问:
Making decimal.Decimal the default numerical type in Python
Is there some way I could make decimal.Decimal the default type for all numerical values in Python? I would like to be able to use Python in a manner similar to the bc and dc programs without having to call decimal.Decimal(...) for every number.

EDIT: For the uninitiated: bc.

EDIT 2: Thank you tokenize module..

答:
You cannot really do what you ask without some serious magic, which I won't try to touch upon in my answer, but there is at least a slightly easier way than doing decimal.Decimal(...)

```<code>from decimal import Decimal as D
num = D("1") + D("2.3")
</code>```

Edit: use the shorter form from the comment.

ContentLicense: CC BY-SA 2.5

Body:
You cannot really do what you ask without some serious magic, which I won't try to touch upon in my answer, but there is at least a slightly easier way than doing decimal.Decimal(...)

from decimal import Decimal as D
num = D("1") + D("2.3")

Edit: use the shorter form from the comment.


问:
Putting an array into a bigger array
I have an array of terms (terms meaning an object with a coefficient and a degree, represented as for example 1.0x^6). The array that I have right now contains 3 terms:

```<code>[1.0x^6, 4.0x^5, 10.0x^0].
</code>```

My goal is to create a bigger array with these terms, but ALSO with terms with a 0 coefficient that are not represented in my array. That probably was not too clear, so here is basically what I want my new array to look like:

```<code>[1.0x^6, 4.0x^5, 0.0x^4, 0.0x^3, 0.0x^2, 0.0x^1, 10.0x^0].
</code>```

Currently, I am iterating through my original array, and if the degree equals the new array.length - 1, I am setting newArray[i] = array[i], if that makes sense. For example, for the first term and i = 0, the degree is 6, and so if 6 = newArray.length - 1 (which is 6), then newArray[i] = array[i].

The problem, however is that array is smaller than newArray, so I am getting an out of bounds error. Any ideas on how to fix this? Sorry for the long post, thanks!

EDIT: Here is my actual code. Sorry if the explanation was unclear.

```<code>int max = 0;
    Term temp;

    for(int i=0; i<array.length; i++) {
        max = i;
        for(int j=i; j< array.length; j++) {
            if(array[j].getDegree() > array[max].getDegree()) {
                max = j;
            }

        }
         temp = array[i];
         array[i] = array[max];
         array[max] = temp;
    }
</code>```

Above, the array is sorted in terms of descending degree. I want to now have the new array contain the old terms, but also 0x^i for all the i that are not used in my set of terms.

```<code>Term[] newArray = new Term[this.degree()+1];
    for (int c = 0; c < newArray.length; c++) {
        if (array[c].getDegree()==newArray.length-1-c) {
            newArray[c] = array[c];
        }
        else {
            newArray[c] = new Term(0, newArray.length-1-c);
        }

    }
</code>```

There are issues in my code above, and I can see that now because in that for loop, array[c] is not defined for any c > 2. Eclipse is telling my that I have an out of bounds error.

答:
Arrays have a fixed size. If you want to create a bigger array, you need to know the size beforehand and define it accordingly. Also, it seems that you are going through both the arrays using the same iteration variable.

I assume you are doing something like this:

```<code>for(i=0;i<newArray.length;i++){
 newArray[i] = array[i]; //size of newArray is bigger than array
}
</code>```

Then you will always get an array index out of bounds exception because "array" is smaller than "newArray" and you go out of bounds when i>=array.length.

You need to fix your code logic.

Title: Putting an array into a bigger array

Body:
I have an array of terms (terms meaning an object with a coefficient and a degree, represented as for example 1.0x^6). The array that I have right now contains 3 terms:

[1.0x^6, 4.0x^5, 10.0x^0].

My goal is to create a bigger array with these terms, but ALSO with terms with a 0 coefficient that are not represented in my array. That probably was not too clear, so here is basically what I want my new array to look like:

[1.0x^6, 4.0x^5, 0.0x^4, 0.0x^3, 0.0x^2, 0.0x^1, 10.0x^0].

Currently, I am iterating through my original array, and if the degree equals the new array.length - 1, I am setting newArray[i] = array[i], if that makes sense. For example, for the first term and i = 0, the degree is 6, and so if 6 = newArray.length - 1 (which is 6), then newArray[i] = array[i].

The problem, however is that array is smaller than newArray, so I am getting an out of bounds error. Any ideas on how to fix this? Sorry for the long post, thanks!

EDIT: Here is my actual code. Sorry if the explanation was unclear.

int max = 0;
    Term temp;

    for(int i=0; i<array.length; i++) {
        max = i;
        for(int j=i; j< array.length; j++) {
            if(array[j].getDegree() > array[max].getDegree()) {
                max = j;
            }

        }
         temp = array[i];
         array[i] = array[max];
         array[max] = temp;
    }

Above, the array is sorted in terms of descending degree. I want to now have the new array contain the old terms, but also 0x^i for all the i that are not used in my set of terms.

Term[] newArray = new Term[this.degree()+1];
    for (int c = 0; c < newArray.length; c++) {
        if (array[c].getDegree()==newArray.length-1-c) {
            newArray[c] = array[c];
        }
        else {
            newArray[c] = new Term(0, newArray.length-1-c);
        }

    }

There are issues in my code above, and I can see that now because in that for loop, array[c] is not defined for any c > 2. Eclipse is telling my that I have an out of bounds error.

Body:
Arrays have a fixed size. If you want to create a bigger array, you need to know the size beforehand and define it accordingly. Also, it seems that you are going through both the arrays using the same iteration variable.

I assume you are doing something like this:

for(i=0;i<newArray.length;i++){
 newArray[i] = array[i]; //size of newArray is bigger than array
}

Then you will always get an array index out of bounds exception because "array" is smaller than "newArray" and you go out of bounds when i>=array.length.

You need to fix your code logic.


问:
Soap Client Complex Type PHP Request
I have a web-service with following link
I'm trying to access the function name with SubmitRequestType but it seems the function is not exist instead submitAnsiSingle this is the correct function name what I tried so far is ,

```<code>$wsdl = 'https://ww3.navicure.com:7000/webservices/NavicureSubmissionService?WSDL';

class SecurityHeaderType {
        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        function SecurityHeaderType() {
            $this->submitterIdentifier = '***';
            $this->originatingIdentifier = '****';
            $this->submitterPassword = '****';
            $this->submissionId = '';

        }
}

class SubmitRequestType {

        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        private $timeout;
        private $transactionType;
        private $submittedAnsiVersion;
        private $resultAnsiVersion;
        private $submitterSubmissionId;
        private $processingOption;
        private $payload;
        private $exceptions;

        function SubmitRequestType() {

        $this->submitterIdentifier = '***';
        $this->originatingIdentifier = '***';
        $this->submitterPassword = '**';
        $this->submissionId = '**';
        $this->timeout = 60 ;
        $this->transactionType = "E";
        $this->submittedAnsiVersion = '5010';
        $this->resultAnsiVersion = '5010';
        $this->submitterSubmissionId = '**';
        $this->processingOption = 'R';
        $this->payload = 'EDI-270-Request';
        $this->exceptions = true;
        }
}

$soapheader = new SecurityHeaderType();

$submitrequest = new SubmitRequestType();

    $service = new \SoapClient($wsdl);
    $result= $service->SubmitAnsiSingle($submitrequest);
    echo "<pre/>";print_r($result);

    $types = $service->__getTypes ();
    $functions = $service->__getFunctions ();
    //echo "<pre/>";print_r($types);
    //echo "<pre/>";print_r($functions);
</code>```

But I'm getting the response like below it seems the request is processing on their end but the SecurityHeaderType is not parsing their end.

```<code>stdClass Object
(
    [transactionTyp] => E
    [submitterSubmissionId] => ****
    [submittedAnsiVersion] => 5010
    [resultAnsiVersion] => 5010
    [statusHeader] => stdClass Object
        (
            [statusCode] => 1150
            [statusMessage] => com.navicure.webservices.core.WSCoreException: Account does not exist for ''
            [requestProcessed] =>
        )

)
</code>```

Any hint will be highly appreciate

Thanks in advance.

答:
You might be running into PHP's slightly less than compatible WSDL2 implementation. You could try the following and cross your fingers;

Headerbody needs to be implemented in the same depth as defined in xml, since I do not have access to navicure's documentation here's example code:

```<code>$headerbody = array('Token' => $someToken,
                    'Version' => $someVersion,
                    'UserCredentials'=>array('UserID'=>$UserID,
                                             'Password'=>$Pwd));

//Create Soap Header.
$header = new SOAPHeader($namespace, 'RequestorCredentials', $headerbody);
</code>```

// In case multiple headers are required, create $headers[] = $header, and append to headers after.

```<code>$options = array(
        'uri'=>'http://schemas.xmlsoap.org/soap/envelope/',
        'style'=>SOAP_RPC,
        'use'=>SOAP_ENCODED,
        'soap_version'=>SOAP_1_1,
        'cache_wsdl'=>WSDL_CACHE_NONE,
        'connection_timeout'=>15,
        'trace'=>true,
        'encoding'=>'UTF-8',
        'exceptions'=>true,
    );
try {
    $soap = new SoapClient($wsdl, $options);
    $soap->__setSoapHeaders($header);
    $data = $soap->SubmitAnsiSingle(array($submitrequest));
}
catch(Exception $e) {
    die($e->getMessage());
}
</code>```

Hope this is of any use - in case WSDL2 is actually used you might be able to get it to work with nusoap which can be found on sourceforge. Although that hasn't been updated in quite a while..

Title: Soap Client Complex Type PHP Request

Body:
I have a web-service with following link
I'm trying to access the function name with SubmitRequestType but it seems the function is not exist instead submitAnsiSingle this is the correct function name what I tried so far is ,

$wsdl = 'https://ww3.navicure.com:7000/webservices/NavicureSubmissionService?WSDL';

class SecurityHeaderType {
        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        function SecurityHeaderType() {
            $this->submitterIdentifier = '***';
            $this->originatingIdentifier = '****';
            $this->submitterPassword = '****';
            $this->submissionId = '';

        }
}

class SubmitRequestType {

        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        private $timeout;
        private $transactionType;
        private $submittedAnsiVersion;
        private $resultAnsiVersion;
        private $submitterSubmissionId;
        private $processingOption;
        private $payload;
        private $exceptions;

        function SubmitRequestType() {

        $this->submitterIdentifier = '***';
        $this->originatingIdentifier = '***';
        $this->submitterPassword = '**';
        $this->submissionId = '**';
        $this->timeout = 60 ;
        $this->transactionType = "E";
        $this->submittedAnsiVersion = '5010';
        $this->resultAnsiVersion = '5010';
        $this->submitterSubmissionId = '**';
        $this->processingOption = 'R';
        $this->payload = 'EDI-270-Request';
        $this->exceptions = true;
        }
}

$soapheader = new SecurityHeaderType();

$submitrequest = new SubmitRequestType();

    $service = new \SoapClient($wsdl);
    $result= $service->SubmitAnsiSingle($submitrequest);
    echo "
";print_r($result);

    $types = $service->__getTypes ();
    $functions = $service->__getFunctions ();
    //echo "
";print_r($types);
    //echo "
";print_r($functions);

But I'm getting the response like below it seems the request is processing on their end but the SecurityHeaderType is not parsing their end.

stdClass Object
(
    [transactionTyp] => E
    [submitterSubmissionId] => ****
    [submittedAnsiVersion] => 5010
    [resultAnsiVersion] => 5010
    [statusHeader] => stdClass Object
        (
            [statusCode] => 1150
            [statusMessage] => com.navicure.webservices.core.WSCoreException: Account does not exist for ''
            [requestProcessed] =>
        )

)

Any hint will be highly appreciate

Thanks in advance.

Body:
You might be running into PHP's slightly less than compatible WSDL2 implementation. You could try the following and cross your fingers;

Headerbody needs to be implemented in the same depth as defined in xml, since I do not have access to navicure's documentation here's example code:

$headerbody = array('Token' => $someToken,
                    'Version' => $someVersion,
                    'UserCredentials'=>array('UserID'=>$UserID,
                                             'Password'=>$Pwd));

//Create Soap Header.
$header = new SOAPHeader($namespace, 'RequestorCredentials', $headerbody);

// In case multiple headers are required, create $headers[] = $header, and append to headers after.

$options = array(
        'uri'=>'http://schemas.xmlsoap.org/soap/envelope/',
        'style'=>SOAP_RPC,
        'use'=>SOAP_ENCODED,
        'soap_version'=>SOAP_1_1,
        'cache_wsdl'=>WSDL_CACHE_NONE,
        'connection_timeout'=>15,
        'trace'=>true,
        'encoding'=>'UTF-8',
        'exceptions'=>true,
    );
try {
    $soap = new SoapClient($wsdl, $options);
    $soap->__setSoapHeaders($header);
    $data = $soap->SubmitAnsiSingle(array($submitrequest));
}
catch(Exception $e) {
    die($e->getMessage());
}

Hope this is of any use - in case WSDL2 is actually used you might be able to get it to work with nusoap which can be found on sourceforge. Although that hasn't been updated in quite a while..


问:
How To Pull Data From the Adwords API and put into a Pandas Dataframe
I'm using Python to pull data from Googles adwords API. I'd like to put that data into a Pandas DataFrame so I can perform analysis on the data. I'm using examples provided by Google here.

Below is my attempt to try to get the output to be read as a pandas dataframe:

```<code>from googleads import adwords
import pandas as pd
import numpy as np

# Initialize appropriate service.

adwords_client = adwords.AdWordsClient.LoadFromStorage()

report_downloader = adwords_client.GetReportDownloader(version='v201710')

# Create report query.
report_query = ('''
select Date, Clicks
from ACCOUNT_PERFORMANCE_REPORT
during LAST_7_DAYS''')

df = pd.read_csv(report_downloader.DownloadReportWithAwql(
    report_query,
    'CSV',
    client_customer_id='xxx-xxx-xxxx', # denotes which adw account to pull from
    skip_report_header=True,
    skip_column_header=False,
    skip_report_summary=True,
    include_zero_impressions=True))
</code>```

The output is the data in what looks like csv format and an error.

```<code>Day,Clicks
2017-11-05,42061
2017-11-07,45792
2017-11-03,36874
2017-11-02,39790
2017-11-06,44934
2017-11-08,45631
2017-11-04,36031
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-cc25e32c9f3a> in <module>()
     25     skip_column_header=False,
     26     skip_report_summary=True,
---> 27     include_zero_impressions=True))

/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654
--> 655         return _read(filepath_or_buffer, kwds)
    656
    657     parser_f.__name__ = name

/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    390     compression = _infer_compression(filepath_or_buffer, compression)
    391     filepath_or_buffer, _, compression = get_filepath_or_buffer(
--> 392         filepath_or_buffer, encoding, compression)
    393     kwds['compression'] = compression
    394

/anaconda/lib/python3.6/site-packages/pandas/io/common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression)
    208     if not is_file_like(filepath_or_buffer):
    209         msg = "Invalid file path or buffer object type: {_type}"
--> 210         raise ValueError(msg.format(_type=type(filepath_or_buffer)))
    211
    212     return filepath_or_buffer, None, compression

ValueError: Invalid file path or buffer object type: <class 'NoneType'>
</code>```

I know I am missing something fundamental and I do not fully understand how to get data into a pandas dataframe. Any help would be greatly appreciated.

答:
So I was able to find out the answer to my own question if anybody is curious or had the same problem I did. I had to import io and wrote the output from the adwords query to a string that I named output. I then used the seek() method to start from the beginning and read that using pandas read_csv.

```<code>from googleads import adwords
import pandas as pd
import numpy as np
import io

# Define output as a string
output = io.StringIO()

# Initialize appropriate service.
adwords_client = adwords.AdWordsClient.LoadFromStorage()

report_downloader = adwords_client.GetReportDownloader(version='v201710')

# Create report query.
report_query = ('''
select Date, HourOfDay, Clicks
from ACCOUNT_PERFORMANCE_REPORT
during LAST_7_DAYS''')

# Write query result to output file
report_downloader.DownloadReportWithAwql(
    report_query,
    'CSV',
    output,
    client_customer_id='xxx-xxx-xxx', # denotes which adw account to pull from
    skip_report_header=True,
    skip_column_header=False,
    skip_report_summary=True,
    include_zero_impressions=False)

output.seek(0)

df = pd.read_csv(output)

df.head()
</code>```

Body:
I'm using Python to pull data from Googles adwords API. I'd like to put that data into a Pandas DataFrame so I can perform analysis on the data. I'm using examples provided by Google here.

Below is my attempt to try to get the output to be read as a pandas dataframe:

from googleads import adwords
import pandas as pd
import numpy as np

# Initialize appropriate service.

adwords_client = adwords.AdWordsClient.LoadFromStorage()

report_downloader = adwords_client.GetReportDownloader(version='v201710')

# Create report query.
report_query = ('''
select Date, Clicks
from ACCOUNT_PERFORMANCE_REPORT
during LAST_7_DAYS''')

df = pd.read_csv(report_downloader.DownloadReportWithAwql(
    report_query,
    'CSV',
    client_customer_id='xxx-xxx-xxxx', # denotes which adw account to pull from
    skip_report_header=True,
    skip_column_header=False,
    skip_report_summary=True,
    include_zero_impressions=True))

The output is the data in what looks like csv format and an error.

Day,Clicks
2017-11-05,42061
2017-11-07,45792
2017-11-03,36874
2017-11-02,39790
2017-11-06,44934
2017-11-08,45631
2017-11-04,36031
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-cc25e32c9f3a> in <module>()
     25     skip_column_header=False,
     26     skip_report_summary=True,
---> 27     include_zero_impressions=True))

/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654
--> 655         return _read(filepath_or_buffer, kwds)
    656
    657     parser_f.__name__ = name

/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    390     compression = _infer_compression(filepath_or_buffer, compression)
    391     filepath_or_buffer, _, compression = get_filepath_or_buffer(
--> 392         filepath_or_buffer, encoding, compression)
    393     kwds['compression'] = compression
    394

/anaconda/lib/python3.6/site-packages/pandas/io/common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression)
    208     if not is_file_like(filepath_or_buffer):
    209         msg = "Invalid file path or buffer object type: {_type}"
--> 210         raise ValueError(msg.format(_type=type(filepath_or_buffer)))
    211
    212     return filepath_or_buffer, None, compression

ValueError: Invalid file path or buffer object type: <class 'NoneType'>

I know I am missing something fundamental and I do not fully understand how to get data into a pandas dataframe. Any help would be greatly appreciated.

Body:
So I was able to find out the answer to my own question if anybody is curious or had the same problem I did. I had to import io and wrote the output from the adwords query to a string that I named output. I then used the seek() method to start from the beginning and read that using pandas read_csv.

from googleads import adwords
import pandas as pd
import numpy as np
import io

# Define output as a string
output = io.StringIO()

# Initialize appropriate service.
adwords_client = adwords.AdWordsClient.LoadFromStorage()

report_downloader = adwords_client.GetReportDownloader(version='v201710')

# Create report query.
report_query = ('''
select Date, HourOfDay, Clicks
from ACCOUNT_PERFORMANCE_REPORT
during LAST_7_DAYS''')

# Write query result to output file
report_downloader.DownloadReportWithAwql(
    report_query,
    'CSV',
    output,
    client_customer_id='xxx-xxx-xxx', # denotes which adw account to pull from
    skip_report_header=True,
    skip_column_header=False,
    skip_report_summary=True,
    include_zero_impressions=False)

output.seek(0)

df = pd.read_csv(output)

df.head()


问:
Best practice tu run code only once and only when you open an app. Swift 4, Xcode 8.
I am trying to run a function only once only when the app is opened.

Background

I have a stored array (we'll call it storedArray) in user defaults that takes its value from an array that can be modified by the user (userArray).

Problem1: Every time I open the app, storedArray has the values of the previous sessions and of course userArray is empty again. So when the storedArray takes values again from the userArray the storedArray looses its previous values.

Solution to problem1: When you open the app the userArray gets filled with the values of the storedArray (from the previous session).

No problem there. Now:

**Problem 2:**This must happen only once every time the app is opened, otherwise the userArray will start appending the storedArray values many times with repeated values. I figured out solutions 1 and 2, number 3 I tried to follow advice from other posts but failed to understand it and implement it.

Possible Solution 1: Declare a global variable

```<code>Struct globalVariables{
static var x = 0
}
</code>```

Create an if statement so that the desired code runs only if globalVariables.x == 0

```<code>if globalVariables.x == 0 {
//code to append values from storedArray to userArray goes here
//Then give a new value to globalVariables.x so that the if never gets accessed again
globalVariables.x == 1
}
</code>```

This works but I don't know if it as a good practice.

Possible Solution 2: Put the code to be run only once inside the application function in the AppDelegate file.

This functions looks like this.

```<code>func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//code to append values from storedArray to userArray goes here
</code>```

}

Again this works but I don't know if it is a good practice.

Possible Solution 3: If I understood correctly, the suggested solution in other posts was to use a singleton. I could never really make this work, (or properly understood what a singleton is).

I made a new .swift file with the following code:

```<code>struct Service {

static let sharedInstance = Service(

func getStoredInfo () {

          //code to append values from storedArray to userArray goes here
    }
  }
}
</code>```

Then call this function in a viewDidLoad with:

```<code>Service.sharedInstance.getStoredInfo()
</code>```

The function still gets called every time the viewDidLoad runs. If the singleton can really help me with this I am totally missing something very basic about what a singleton is and how to implement it. Totally.

Are solutions 1 and 2 good practices? Maybe there are other solutions?

Thanks!

答:
If something need to be done only after launch then 'application didFinishLaunchingWithOptions' is definitely the way to go.

Problem : On iOS you don't control when your app is terminated. You need to store how the app was terminated, so you can restore the session or start a fresh one.

Body:
I am trying to run a function only once only when the app is opened.

Background

I have a stored array (we'll call it storedArray) in user defaults that takes its value from an array that can be modified by the user (userArray).

Problem1: Every time I open the app, storedArray has the values of the previous sessions and of course userArray is empty again. So when the storedArray takes values again from the userArray the storedArray looses its previous values.

Solution to problem1: When you open the app the userArray gets filled with the values of the storedArray (from the previous session).

No problem there. Now:

**Problem 2:**This must happen only once every time the app is opened, otherwise the userArray will start appending the storedArray values many times with repeated values. I figured out solutions 1 and 2, number 3 I tried to follow advice from other posts but failed to understand it and implement it.

Possible Solution 1: Declare a global variable

Struct globalVariables{
static var x = 0
}

Create an if statement so that the desired code runs only if globalVariables.x == 0

if globalVariables.x == 0 {
//code to append values from storedArray to userArray goes here
//Then give a new value to globalVariables.x so that the if never gets accessed again
globalVariables.x == 1
}

This works but I don't know if it as a good practice.

Possible Solution 2: Put the code to be run only once inside the application function in the AppDelegate file.

This functions looks like this.

func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//code to append values from storedArray to userArray goes here

}

Again this works but I don't know if it is a good practice.

Possible Solution 3: If I understood correctly, the suggested solution in other posts was to use a singleton. I could never really make this work, (or properly understood what a singleton is).

I made a new .swift file with the following code:

struct Service {

static let sharedInstance = Service(

func getStoredInfo () {

          //code to append values from storedArray to userArray goes here
    }
  }
}

Then call this function in a viewDidLoad with:

Service.sharedInstance.getStoredInfo()

The function still gets called every time the viewDidLoad runs. If the singleton can really help me with this I am totally missing something very basic about what a singleton is and how to implement it. Totally.

Are solutions 1 and 2 good practices? Maybe there are other solutions?

Thanks!


问:
Input to capture minutes and seconds in the format (mm:ss) in angularjs
I am creating a simple form for an application in angularjs. I need an input field to recieve time data with only minutes and seconds in the format "mm:ss". Anyone who has worked on this, your assistance would be highly appreciated. I already have created time input for my form. Actually, I am working on project created by other programmer. The model for the time input was initialized as follows:

```<code>function initDate(date, indexX, indexY){
      if(date != null && date != ''){
        var dateArray = date.split(":");
        var dt = new Date(1970,1,1,dateArray[0],dateArray[1],dateArray[2]);
        vm.modelDate[indexX][indexY] = dt;
      }
}

<input name="inputExTime{{q.listSubQuestions[contTime].questionId}}{{contTime}}0"
    type="time" class="form-control btn-act btn-act-inputs intime_ex" step="1"
    ng-disabled="disabledfields"
    ng-model="vm.modelDate[0][contTime]"
    min="00:00:00" max="12:59:00"
    ng-change="vm.changeDate(parentIndex,0,contTime);vm.calculateHours(form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+0].$modelValue, form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+2].$modelValue, form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+3], contTime);vm.average();"
    ng-required="$index<vm.numberOfRequiredRows?(q.attributes.required==false?false:isregister):false"
    ng-class="{true: 'inp-f'}[form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+0].$invalid]"
    ng-init="vm.modelDate[0][contTime]=null;vm.initArray(''+q.listSubQuestions[contTime].questionId+contTime+0);vm.initDate(q.listSubQuestions[0].listAnswers[contTime].detail, 0, contTime);"
</code>```

/>

答:
You need to define an input element in your form of the time time:

```<code><input type="time" ng-model="timeModel">
</code>```

The ng-model would be a Date object. Otherwise, AngularJS will throw an error.

var app = angular.module('time', []);

app.controller('MainCtrl', function($scope) {
  // The order of the params is the following:
  // Year, Month, Day, Time, Minutes, Seconds
  $scope.timeModel = new Date(2017, 10, 13, 10, 30, 0);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="time">

<head>
  <meta charset="utf-8" />
  <title>Time Model Example using AngularJS</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="time" ng-model="timeModel">
</body>

</html></code>```

On the official documentation, you can find more information about this.

Keep Rocking!

Body:
I am creating a simple form for an application in angularjs. I need an input field to recieve time data with only minutes and seconds in the format "mm:ss". Anyone who has worked on this, your assistance would be highly appreciated. I already have created time input for my form. Actually, I am working on project created by other programmer. The model for the time input was initialized as follows:

function initDate(date, indexX, indexY){
      if(date != null && date != ''){
        var dateArray = date.split(":");
        var dt = new Date(1970,1,1,dateArray[0],dateArray[1],dateArray[2]);
        vm.modelDate[indexX][indexY] = dt;
      }
}

<input name="inputExTime{{q.listSubQuestions[contTime].questionId}}{{contTime}}0"
    type="time" class="form-control btn-act btn-act-inputs intime_ex" step="1"
    ng-disabled="disabledfields"
    ng-model="vm.modelDate[0][contTime]"
    min="00:00:00" max="12:59:00"
    ng-change="vm.changeDate(parentIndex,0,contTime);vm.calculateHours(form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+0].$modelValue, form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+2].$modelValue, form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+3], contTime);vm.average();"
    ng-required="$index<vm.numberOfRequiredRows?(q.attributes.required==false?false:isregister):false"
    ng-class="{true: 'inp-f'}[form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+0].$invalid]"
    ng-init="vm.modelDate[0][contTime]=null;vm.initArray(''+q.listSubQuestions[contTime].questionId+contTime+0);vm.initDate(q.listSubQuestions[0].listAnswers[contTime].detail, 0, contTime);"

/>

Body:
You need to define an input element in your form of the time time:

<input type="time" ng-model="timeModel">

The ng-model would be a Date object. Otherwise, AngularJS will throw an error.

var app = angular.module('time', []);

app.controller('MainCtrl', function($scope) {
  // The order of the params is the following:
  // Year, Month, Day, Time, Minutes, Seconds
  $scope.timeModel = new Date(2017, 10, 13, 10, 30, 0);
});

<!DOCTYPE html>
<html ng-app="time">

<head>
  <meta charset="utf-8" />
  <title>Time Model Example using AngularJS</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="time" ng-model="timeModel">
</body>

</html>

On the official documentation, you can find more information about this.

Keep Rocking!


问:
ViewModel objects to EF model entities conversion where?
I currently have a repository based on Entity Framework v4 entities (CRUD and GET operations implemented). I'm in the process of creating the corresponding View Models for these entities. Where should I put the conversion/mapping between them? In the controller or modify the repository to perform the mapping in its methods and return back (or accept) the View Model typed objects?

Should I do this

```<code>    public ActionResult Index()
    {
        var person = new PersonRepository().Get();

        var personViewModel = new PersonViewModel();
        personViewModel.InjectFrom(person)
            .InjectFrom<CountryToLookup>(person);

        return View(personViewModel);
    }
</code>```

or this

```<code>     public ActionResult Index()
        {
            var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel

// and move this to repository
//            var personViewModel = new PersonViewModel();
//            personViewModel.InjectFrom(person)
//               .InjectFrom<CountryToLookup>(person);

            return View(personViewModel);
        }
</code>```

答:
I would extract it out into a private method on the controller or put it into a service class if it's going to be reused in other places.

I don't think it's a good idea putting it on the repository unless it's not generic. Which it should be because in my opinion generic repositories rock!

Body:
I currently have a repository based on Entity Framework v4 entities (CRUD and GET operations implemented). I'm in the process of creating the corresponding View Models for these entities. Where should I put the conversion/mapping between them? In the controller or modify the repository to perform the mapping in its methods and return back (or accept) the View Model typed objects?

Should I do this

    public ActionResult Index()
    {
        var person = new PersonRepository().Get();

        var personViewModel = new PersonViewModel();
        personViewModel.InjectFrom(person)
            .InjectFrom<CountryToLookup>(person);

        return View(personViewModel);
    }

or this

     public ActionResult Index()
        {
            var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel

// and move this to repository
//            var personViewModel = new PersonViewModel();
//            personViewModel.InjectFrom(person)
//               .InjectFrom<CountryToLookup>(person);

            return View(personViewModel);
        }


问:
SAP rounding formula - where does rounding occur?
I'm doing some integration with SAP and a custom application. The calculated values for 'Total' and 'Price after Discount' are off half of the time.

Given 'Quantity', 'Unit Price' and 'Discount %', how is their calculations formulated?

This is the formula I've been using to get 'Total' so far and it doesn't always match up:

```<code>Let R = Round to two decimal places away from zero

Total = R(Quantity * Unit Price) - R(R(Quantity* Unit Price) * R(Discount/100))
</code>```

But as you can see, if I plug in the first line of Quantity: 11217, Unit Price 0.3 and Discount: 65, I get a different result of 1177.78

What tweak to my formula then should I make so I consistently match with SAP's ('Total' and 'Price after Discount')?

答:
After a lot of trial and errors, I finally figured out SAP's algorithm to get 'Total':

```<code>Let R = Round to two decimal places away from zero

Total = R(Quantity * Unit Price * (100 - Discount%) / 100)
</code>```

I had to take out rounding on each step and not use 'Original Price - Discount'

Body:
I'm doing some integration with SAP and a custom application. The calculated values for 'Total' and 'Price after Discount' are off half of the time.

Given 'Quantity', 'Unit Price' and 'Discount %', how is their calculations formulated?

This is the formula I've been using to get 'Total' so far and it doesn't always match up:

Let R = Round to two decimal places away from zero

Total = R(Quantity * Unit Price) - R(R(Quantity* Unit Price) * R(Discount/100))

But as you can see, if I plug in the first line of Quantity: 11217, Unit Price 0.3 and Discount: 65, I get a different result of 1177.78

What tweak to my formula then should I make so I consistently match with SAP's ('Total' and 'Price after Discount')?

Body:
After a lot of trial and errors, I finally figured out SAP's algorithm to get 'Total':

Let R = Round to two decimal places away from zero

Total = R(Quantity * Unit Price * (100 - Discount%) / 100)

I had to take out rounding on each step and not use 'Original Price - Discount'


问:
Session timeout warning modal using react
I have a requirement to display timeout warning modal after 13 mins of inactivity and end session after 15 mins if user takes no action. I need to achieve this using reactjs. I checked react-timeout at https://www.npmjs.com/package/react-timeout#react-classic-verbose, but that didn't help.
If anyone knows of a way to do this, please share with me.</p>

答:
You can create a higher order component like this and can pass child component through higher order component

HOC:

`// code

```<code>export default function(ComposedClass) {
  class AutoLogout extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        warningTime: 1000 * 60 * 10,
        signoutTime: 1000 * 60 * 15,
      };
    }

    componentDidMount() {
      this.events = [
        'load',
        'mousemove',
        'mousedown',
        'click',
        'scroll',
        'keypress'
      ];

      for (var i in this.events) {
        window.addEventListener(this.events[i], this.resetTimeout);
      }

      this.setTimeout();
    }

    clearTimeoutFunc = () => {
      if (this.warnTimeout) clearTimeout(this.warnTimeout);

      if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
    };

    setTimeout = () => {
      this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
      this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
    };

    resetTimeout = () => {
      this.clearTimeoutFunc();
      this.setTimeout();
    };

    warn = () => {
      window.alert("You will be logged out automatically in 1 minute")
      console.log('You will be logged out automatically in 1 minute.');
    };

    logout = () => {
      // Send a logout request to the API
      console.log('Sending a logout request to the API...');
      this.destroy();
    };

    destroy = () => {
     //clear the session
      browserHistory.push('/');
      window.location.assign('/');
    };

    render() {

      return (
        <div>
          <ComposedClass {...this.props} />
        </div>
      );
    }
  }
}
</code>```

`

You can wrap this HOC to all those component in which you want to give user warning due to  inactivity, in routing file

<Route path="/test" component={HOC(comonent)} />

in above code component will be the page where you want to add this functionality.

Body:
You can create a higher order component like this and can pass child component through higher order component

HOC:

`// code

export default function(ComposedClass) {
  class AutoLogout extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        warningTime: 1000 * 60 * 10,
        signoutTime: 1000 * 60 * 15,
      };
    }

    componentDidMount() {
      this.events = [
        'load',
        'mousemove',
        'mousedown',
        'click',
        'scroll',
        'keypress'
      ];

      for (var i in this.events) {
        window.addEventListener(this.events[i], this.resetTimeout);
      }

      this.setTimeout();
    }

    clearTimeoutFunc = () => {
      if (this.warnTimeout) clearTimeout(this.warnTimeout);

      if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
    };

    setTimeout = () => {
      this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
      this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
    };

    resetTimeout = () => {
      this.clearTimeoutFunc();
      this.setTimeout();
    };

    warn = () => {
      window.alert("You will be logged out automatically in 1 minute")
      console.log('You will be logged out automatically in 1 minute.');
    };

    logout = () => {
      // Send a logout request to the API
      console.log('Sending a logout request to the API...');
      this.destroy();
    };

    destroy = () => {
     //clear the session
      browserHistory.push('/');
      window.location.assign('/');
    };

    render() {

      return (
        <div>
          <ComposedClass {...this.props} />
        </div>
      );
    }
  }
}

`

You can wrap this HOC to all those component in which you want to give user warning due to  inactivity, in routing file

<Route path="/test" component={HOC(comonent)} />

in above code component will be the page where you want to add this functionality.


问:
Create a distributable Eclipse bundle on MacOS
our company uses the Eclipse IDE with some plugins that are required to start our platform. I want to create a bundle for our Java developers that contains the latest Eclipse Java (Oxygen) with the plugins already installed.

So far I've installed Eclipse with

```<code>sudo cask brew install eclipse-java
</code>```

which created an /Application/Eclipse Java.app.

After installing the plugins within Eclipse with Help->Install New Software the ~/.eclipse/ was created in my home directory.

Is there some way to zip these folders to create an distributable package of eclipse or am I missing other files/directories?

Is it possible to move the plugins in the installation directory as well?

Thanks for your help!

答:
It is not advisable to use any Eclipse distribution that's produced by packaging tools. It's best to download directly from eclipse.org, for various reasons.

As for customizing an Eclipse "package" for distribution yourself, have a look at the Oomph project, which is designed for that exact purpose (and others). Oomph is what produces both the installer and the downloadable packages of Eclipse IDE releases. You can read specifically about Oomph authoring here.

Body:
our company uses the Eclipse IDE with some plugins that are required to start our platform. I want to create a bundle for our Java developers that contains the latest Eclipse Java (Oxygen) with the plugins already installed.

So far I've installed Eclipse with

sudo cask brew install eclipse-java

which created an /Application/Eclipse Java.app.

After installing the plugins within Eclipse with Help->Install New Software the ~/.eclipse/ was created in my home directory.

Is there some way to zip these folders to create an distributable package of eclipse or am I missing other files/directories?

Is it possible to move the plugins in the installation directory as well?

Thanks for your help!


问:
Moving navigator in Highcharts
I would like to fetch data for example from this website: https://www.highcharts.com/stock/demo/lazy-loading

To get the data with high resolution, I have to set the min max to small value and then I have to go over the complete diagram.

It is possible to get data from the website with "Highcharts.charts[0].series[0]"

But I didn't find a possibility to programable changing the navigators, to get other data ranges.

Is it possible to move the navigator to a specific position?

答:
Thank you for your answear. Here is my code if somebody needs:

I saw, that the redraw event will be called 5 times till the diagram is finishd redrawn

```<code>counter = 1
// Get chart
chart = $('#highcharts-graph').highcharts()
// add event
Highcharts.addEvent(chart, 'redraw', function (e) {
console.log(counter);
counter = counter+1;
if(counter>5){
    console.log('finish loaded')
    function2()
}
})
var newSelectedMin = 0
var newSelectedMax = 10
chart.xAxis[0].setExtremes(newSelectedMin, newSelectedMax);
</code>```

Title: Moving navigator in Highcharts

Body:
Thank you for your answear. Here is my code if somebody needs:

I saw, that the redraw event will be called 5 times till the diagram is finishd redrawn

counter = 1
// Get chart
chart = $('#highcharts-graph').highcharts()
// add event
Highcharts.addEvent(chart, 'redraw', function (e) {
console.log(counter);
counter = counter+1;
if(counter>5){
    console.log('finish loaded')
    function2()
}
})
var newSelectedMin = 0
var newSelectedMax = 10
chart.xAxis[0].setExtremes(newSelectedMin, newSelectedMax);


问:
Tableau isNull then 0 calculated field
I have my tableau workbook and I'm currently counting by a field called ID - COUNT([Id]) - while this is great, on days with no activity my dashboard doesn't show ANYTHING and I want it to show zero if there was no activity - so I do I change this to count but also replace null with 0 (zero)?</p>

答:
First make sure you understand what Count([ID]) does. It returns the number records in the data source that have a non-null value in the column [ID].

Count() never evaluates to null. But if you have no rows at all in your data after filtering, then you'll get an empty result set -- i.e. view data will not have any summary data to show at all - whether null or zero.

Wrapping COUNT() in a call to ISNULL() or ZN() won't help in that case.

The solution is to make sure you have at least one data row per day, even if all other fields besides the date are null. Aggregation functions ignore nulls so padding your data like this should not disturb your results. The simplest way is to make a calendar table that has one row per day with nulls in most columns. Then use a Union to combine the calendar with your original data source. Then Count(ID) will return zero on days where there are no other records besides the calendar entry.

You can also get similar results using data blending, although with a bit more complexity.

Title: Tableau isNull then 0 calculated field


问:
Workbook Protection stopped working with Excel Online
Until a few weeks ago, the workbook protection API was working in Excel Online. Now it gives error as invalid parameter.

I'm setting allowInsertColumns: false and allowFormatCells: false.

My code looks like this:

Excel.run(function (ctx) {
    var sheet = ctx.workbook.worksheets.getItem("Sheet1");
    var range = sheet.getRange("A1:B3").format.protection.locked = false;

    sheet.protection.protect({
        allowInsertColumns: false,
        allowFormatCells: false
    });

    $('#mytestlabel1').text("Execution of protect api call is complete");

    return ctx.sync().then(function () {
        $('#mytestlabel').text("Sync operation is complete");
    });

}).catch(function (error) {

    $('#mytestlabel').text(error.message);
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }

});
```

I get exception when ctx.sync is done

Does anybody know what has changed, and how to fix this?

答:
The product team is aware of this issue and is working on a fix. </p>

<p>See https://github.com/OfficeDev/office-js-docs/issues/1185 for details. </p>

Body:
Until a few weeks ago, the workbook protection API was working in Excel Online. Now it gives error as invalid parameter.

I'm setting allowInsertColumns: false and allowFormatCells: false.

My code looks like this:

Excel.run(function (ctx) {
    var sheet = ctx.workbook.worksheets.getItem("Sheet1");
    var range = sheet.getRange("A1:B3").format.protection.locked = false;

    sheet.protection.protect({
        allowInsertColumns: false,
        allowFormatCells: false
    });

    $('#mytestlabel1').text("Execution of protect api call is complete");

    return ctx.sync().then(function () {
        $('#mytestlabel').text("Sync operation is complete");
    });

}).catch(function (error) {

    $('#mytestlabel').text(error.message);
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }

});

I get exception when ctx.sync is done

Does anybody know what has changed, and how to fix this?

Body:
The product team is aware of this issue and is working on a fix.

See https://github.com/OfficeDev/office-js-docs/issues/1185 for details.


问:
Error in source() unexpected numeric constant
when I write an R script in a test.R file

```<code>nb <- 22

paste("Etudions le nombre: ",nb)
paste("Le logarithme népérien de ce nombre est: ", log(nb))
paste("La racine carrée de ce nombre est: ", sqrt(nb))
paste("Le cosinus de ce nombre est: ", cos(nb))
paste("Si on ajoute 3 au nombre ", nb, " on obtient: ", nb + 3)

q("ask")
</code>```

I executed using :

```<code>source("/Users/shous/Desktop/Master2.0/LanguageR/test.R")
</code>```

error  message :

```<code>Error in source("/Users/shous/Desktop/Master2.0/LanguageR/test.R") :
/Users/shous/Desktop/Master2.0/LanguageR/test.R:1:9: unexpected numeric constant
1: nbÂ <-Â 22
</code>```

答:
It can be encoding problem: unexpected numeric constant 1: nbÂ <-Â 22

I guess you don't want to have this character Â.Try to change file encoding or rewrite problematic line (not copy paste).

Body:
when I write an R script in a test.R file

nb <- 22

paste("Etudions le nombre: ",nb)
paste("Le logarithme népérien de ce nombre est: ", log(nb))
paste("La racine carrée de ce nombre est: ", sqrt(nb))
paste("Le cosinus de ce nombre est: ", cos(nb))
paste("Si on ajoute 3 au nombre ", nb, " on obtient: ", nb + 3)

q("ask")

I executed using :

source("/Users/shous/Desktop/Master2.0/LanguageR/test.R")

error  message :

Error in source("/Users/shous/Desktop/Master2.0/LanguageR/test.R") :
/Users/shous/Desktop/Master2.0/LanguageR/test.R:1:9: unexpected numeric constant
1: nbÂ <-Â 22


问:
Conditional statement syntax help
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

```<code>return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;
</code>```

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks

答:
It's nothing but a conditional operator from C#. Syntax is like following
Condition ? Statement1 (if true) : Statement2 (if false)
If your condition returns true, Statement1 is run and if turns out be false, Statement2 is run.

In your case if (minFontSize + count + increment) > maxFontSize , maxFontSize is evaluated else  (minFontSize + count + increment)

Title: Conditional statement syntax help

Body:
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks


问:
Reliable way to get Windows Version from registry
I'm checking the windows version in an installer (made with NSIS) by checking the following registry key:

```<code>HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "CurrentVersion"
</code>```

According to this post and this page from MSDN, the currentVersion number for Windows 10 should be 10.0.

I just installed the Windows 10 Pro Insider Preview and the version number given in the registry is still 6.3, instead of 10.10 as it should.

Is there another reliable way in registry to detect Windows 10?

答:
Try

```<code>HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId
</code>```

Which gives me 10 and 1709.

Body:
I'm checking the windows version in an installer (made with NSIS) by checking the following registry key:

HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "CurrentVersion"

According to this post and this page from MSDN, the currentVersion number for Windows 10 should be 10.0.

I just installed the Windows 10 Pro Insider Preview and the version number given in the registry is still 6.3, instead of 10.10 as it should.

Is there another reliable way in registry to detect Windows 10?

Body:
Try

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId

Which gives me 10 and 1709.


问:
How to join DataFrames and take the newest row by timestamp?
I have two PySpark DataFrames. I join both DataFrames as follows:

```<code>df = df1.join(df2,['col1', 'col2'], 'inner')
</code>```

The DataFrame df2 has a column timestamp, while df1 does not have it:

```<code>df1 =
col1   col2
AA     11
BB     22

df2 =
timestamp    col1   col2  col3
1510586134   AA     11    3
1510586140   AA     11    2
1510586200   AA     11    5
1510586134   BB     22    3
</code>```

How can I join DataFrames by the newest row of df2 according to timestamp?

The result should be the following:

```<code>col1   col2   col3
AA     11     5
BB     22     3
</code>```

答:
from pyspark.sql.functions import col, rank
from pyspark.sql.window import Window

#sample data
df1 = sc.parallelize([
    ['AA', 11],
    ['BB', 22]
]).toDF(('col1', 'col2'))
df2 = sc.parallelize([
    [1510586134, 'AA', 11, 3],
    [1510586140, 'AA', 11, 2],
    [1510586200, 'AA', 11, 5],
    [1510586134, 'BB', 22, 3]
]).toDF(('timestamp', 'col1', 'col2', 'col3'))

#select latest row of df2 according to timestamp
df2_temp = df2.withColumn('timestamp_format_col', col('timestamp').cast("timestamp"))
window = Window.partitionBy('col1','col2').\
    orderBy(col('timestamp_format_col').desc())
df2_temp = df2_temp.\
    select('*', rank().over(window).alias('rank')).\
    filter(col('rank')==1).\
    drop('rank','timestamp','timestamp_format_col')

#final result
df = df1.join(df2_temp, ['col1', 'col2'], 'inner')
df.show()
```
<p>Output is:</p>
```+----+----+----+
|col1|col2|col3|
+----+----+----+
|  BB|  22|   3|
|  AA|  11|   5|
+----+----+----+
```

Body:
I have two PySpark DataFrames. I join both DataFrames as follows:

df = df1.join(df2,['col1', 'col2'], 'inner')

The DataFrame df2 has a column timestamp, while df1 does not have it:

df1 =
col1   col2
AA     11
BB     22

df2 =
timestamp    col1   col2  col3
1510586134   AA     11    3
1510586140   AA     11    2
1510586200   AA     11    5
1510586134   BB     22    3

How can I join DataFrames by the newest row of df2 according to timestamp?

The result should be the following:

col1   col2   col3
AA     11     5
BB     22     3

Body:
from pyspark.sql.functions import col, rank
from pyspark.sql.window import Window

#sample data
df1 = sc.parallelize([
    ['AA', 11],
    ['BB', 22]
]).toDF(('col1', 'col2'))
df2 = sc.parallelize([
    [1510586134, 'AA', 11, 3],
    [1510586140, 'AA', 11, 2],
    [1510586200, 'AA', 11, 5],
    [1510586134, 'BB', 22, 3]
]).toDF(('timestamp', 'col1', 'col2', 'col3'))

#select latest row of df2 according to timestamp
df2_temp = df2.withColumn('timestamp_format_col', col('timestamp').cast("timestamp"))
window = Window.partitionBy('col1','col2').\
    orderBy(col('timestamp_format_col').desc())
df2_temp = df2_temp.\
    select('*', rank().over(window).alias('rank')).\
    filter(col('rank')==1).\
    drop('rank','timestamp','timestamp_format_col')

#final result
df = df1.join(df2_temp, ['col1', 'col2'], 'inner')
df.show()

Output is:

+----+----+----+
|col1|col2|col3|
+----+----+----+
|  BB|  22|   3|
|  AA|  11|   5|
+----+----+----+


问:
Split sequence dataframe in R
I have a dataframe of sequences like this

```<code>dput(df)
structure(list(val = structure(c(3L, 2L, 4L, 1L, 5L, 6L), .Label = c("{36415},{36415}",
                           "{36415},{85610}", "{36415},{9904}", "{85025,36415}", "{85610},{36415}",
                           "{8872},{36415}"), class = "factor")), .Names = "val", row.names = c(NA,
                                                                                -6L), class = "data.frame")

df
              val
1  {36415},{9904}
2 {36415},{85610}
3   {85025,36415}
4 {36415},{36415}
5 {85610},{36415}
6  {8872},{36415}
</code>```

Notice the 3rd row above. The first row says there is a sequence item 1 followed by item 2 in different rows. The 3rd row says item1 and 2 belong to same row in the sequence

I want to break this data frame into columns like this

```<code>col1        col2
36415       9904
36415       85610
85025,36415 NA
36415       36415
...
</code>```

Notice how the 3rd row of the data frame is.

Is there any way to achieve this?

答:
A solution from dplyr and tidyr. We can separate the column and then remove any { or }.

```<code>library(dplyr)
library(tidyr)
df2 <- df %>%
  separate(val, into = c("col1", "col2"), sep = "\\},\\{", fill = "right") %>%
  mutate_all(funs(gsub("\\{|\\}", "", .)))
df2
#          col1  col2
# 1       36415  9904
# 2       36415 85610
# 3 85025,36415  <NA>
# 4       36415 36415
# 5       85610 36415
# 6        8872 36415
</code>```

Title: Split sequence dataframe in R

Body:
I have a dataframe of sequences like this

dput(df)
structure(list(val = structure(c(3L, 2L, 4L, 1L, 5L, 6L), .Label = c("{36415},{36415}",
                           "{36415},{85610}", "{36415},{9904}", "{85025,36415}", "{85610},{36415}",
                           "{8872},{36415}"), class = "factor")), .Names = "val", row.names = c(NA,
                                                                                -6L), class = "data.frame")

df
              val
1  {36415},{9904}
2 {36415},{85610}
3   {85025,36415}
4 {36415},{36415}
5 {85610},{36415}
6  {8872},{36415}

Notice the 3rd row above. The first row says there is a sequence item 1 followed by item 2 in different rows. The 3rd row says item1 and 2 belong to same row in the sequence

I want to break this data frame into columns like this

col1        col2
36415       9904
36415       85610
85025,36415 NA
36415       36415
...

Notice how the 3rd row of the data frame is.

Is there any way to achieve this?

Body:
A solution from dplyr and tidyr. We can separate the column and then remove any { or }.

library(dplyr)
library(tidyr)
df2 <- df %>%
  separate(val, into = c("col1", "col2"), sep = "\\},\\{", fill = "right") %>%
  mutate_all(funs(gsub("\\{|\\}", "", .)))
df2
#          col1  col2
# 1       36415  9904
# 2       36415 85610
# 3 85025,36415  <NA>
# 4       36415 36415
# 5       85610 36415
# 6        8872 36415


问:
Javafx audit logging
I have an assignment in Javafx to take a basic login application and have it produce an audit log that includes the entries the user put in the text boxes and the buttons pressed along with the date and time. I have searched high and low and I cannot find an example that I can make work with my application. Can someone provide me a basic example of how to implement the audit log or point me in the right direction?</p>

答:
For a professional application, many people use java.util.logging, or Apache Log4J. However, since this is an assignment, I assume your instructor wishes you to keep a log using your own File I/O.

I would suggest implementing a method called log(String message) which opens your audit file and appends a line to the end with the current timestamp and given message. Then, everywhere in your application you need to log something, you simply call your own log(message) function.

For more help with File IO, try reading through this tutorial, or searching google for a good one.

Title: Javafx audit logging


问:
Break out a loop from within a (yielded) block inside the loop
```<code>jobs.each do |job|
  msg job.name do
    break if stop_all_jobs?
    job.run!
  end
end

def msg(msg, &block)
  puts 'START ' + msg
  yield
  puts 'END ' + msg
end
</code>```

In the above example break does not break out of the loop as expected. It only breaks out of the msg code block.

This seems a little odd, but I guess it is based on context, that said, how do I break out of the loop from code which is within a yielded code block?

答:
One way is to use throw/catch. No, not exceptions, Ruby has a separate control-of-flow feature that works a bit like exceptions, without all the overhead (although I must admit I'm not sure that there isn't any overhead in using it):

```<code>catch :stop_all_jobs do
  msg job.name do
    throw :stop_all_jobs if stop_all_jobs?
    job.run!
  end
end
</code>```

You can even pass a value as the second argument to throw which will be the result of the catch block.

A potentially more readable solution would, of course, be to pack the code up in a method and use return in place of break. But that wouldn't be as fun.

Body:
jobs.each do |job|
  msg job.name do
    break if stop_all_jobs?
    job.run!
  end
end

def msg(msg, &block)
  puts 'START ' + msg
  yield
  puts 'END ' + msg
end

In the above example break does not break out of the loop as expected. It only breaks out of the msg code block.

This seems a little odd, but I guess it is based on context, that said, how do I break out of the loop from code which is within a yielded code block?

Body:
One way is to use throw/catch. No, not exceptions, Ruby has a separate control-of-flow feature that works a bit like exceptions, without all the overhead (although I must admit I'm not sure that there isn't any overhead in using it):

catch :stop_all_jobs do
  msg job.name do
    throw :stop_all_jobs if stop_all_jobs?
    job.run!
  end
end

You can even pass a value as the second argument to throw which will be the result of the catch block.

A potentially more readable solution would, of course, be to pack the code up in a method and use return in place of break. But that wouldn't be as fun.


问:
What happens when async code attempts to resume on a thread that is already executing?
I feel that the answer to this is due to me having an incorrect concept of how threads work, but here goes.

```<code>private void button1_Click(object sender, EventArgs e)
{
  this.TestMethodAsync();   // No await, i.e. fire and forget

  // ** Some code here to perform long running calculation (1) **
}

private async Task TestMethodAsync()
{
  // Some synchronous stuff

  await Task.Delay(1000);

  // ** Some code here to perform long running calculation (2) **
}
</code>```

First of all, I would not "fire and forget" an asynchronous method like this (I would use Task.Run) but I've come across code that does, and I'm trying to understand what the effect is.

In a WinForms application, which uses a WindowsFormsSynchronizationContext, my understanding of async and await tells me that when I click button1, the method will start synchronously on the UI thread. It will call TestMethodAsync and run synchronously until it reaches the await. It will then capture the context, start the Task.Delay task, and yield control to the caller. Since we are not awaiting this call, button1_Click will continue on the UI thread and start performing calculation (1).

At some point, Task.Delay(1000) will complete. A continuation will then run the remainder of the TestMethodAsync method using the captured context, which in this case means that the continuation will be run on the  UI thread. This will now start performing calculation (2).

We now have two separate sections of code wanting to run on the same thread (the UI thread) at the same time. My investigations into this seem to suggest that the thread switches back and forth between the two sections of code in order to perform them both.

QUESTION:

I'm confused about exactly what is going on here. How is it possible to resume on a thread that is already running other code? What forces the thread to switch between the two sections of code that want to run? In general, what happens when you attempt to resume on a thread that is already running some other code?

(I suppose this isn't any different to how my click event runs on the UI thread in the first place, in as much as I know it runs on the UI thread, and I know the UI thread is also doing other stuff, but I've not really thought about it like this before.)

答:
How is it possible to resume on a thread that is already running other code?

It needs to be specifically designed to support it.  There needs to be some framework in place that allows the thread to take in work and to then execute that work at some later point in time.

This is how your UI thread works.  It has a queue, and whenever you schedule work to be done in the UI thread you add an item to the end of the queue.  The UI thread then takes the first item from the queue, executes it, and then when it's done, goes on to the next item, and so on, until you end your application.

What forces the thread to switch between the two sections of code that want to run?

Nothing, because it doesn't do that.  It runs one, then when it finishes, it runs the other.

In general, what happens when you attempt to resume on a thread that is already running some other code?

Either someone wrote some custom code to specifically do just that, in which case, it does whatever that code specifically told it to do, or else you can't.

Body:
I feel that the answer to this is due to me having an incorrect concept of how threads work, but here goes.

private void button1_Click(object sender, EventArgs e)
{
  this.TestMethodAsync();   // No await, i.e. fire and forget

  // ** Some code here to perform long running calculation (1) **
}

private async Task TestMethodAsync()
{
  // Some synchronous stuff

  await Task.Delay(1000);

  // ** Some code here to perform long running calculation (2) **
}

First of all, I would not "fire and forget" an asynchronous method like this (I would use Task.Run) but I've come across code that does, and I'm trying to understand what the effect is.

In a WinForms application, which uses a WindowsFormsSynchronizationContext, my understanding of async and await tells me that when I click button1, the method will start synchronously on the UI thread. It will call TestMethodAsync and run synchronously until it reaches the await. It will then capture the context, start the Task.Delay task, and yield control to the caller. Since we are not awaiting this call, button1_Click will continue on the UI thread and start performing calculation (1).

At some point, Task.Delay(1000) will complete. A continuation will then run the remainder of the TestMethodAsync method using the captured context, which in this case means that the continuation will be run on the  UI thread. This will now start performing calculation (2).

We now have two separate sections of code wanting to run on the same thread (the UI thread) at the same time. My investigations into this seem to suggest that the thread switches back and forth between the two sections of code in order to perform them both.

QUESTION:

I'm confused about exactly what is going on here. How is it possible to resume on a thread that is already running other code? What forces the thread to switch between the two sections of code that want to run? In general, what happens when you attempt to resume on a thread that is already running some other code?

(I suppose this isn't any different to how my click event runs on the UI thread in the first place, in as much as I know it runs on the UI thread, and I know the UI thread is also doing other stuff, but I've not really thought about it like this before.)