问:
Join two integers into one double
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

```<code>double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);
</code>```

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

答:
I need to transfer a double value (-47.1235648, for example) using sockets.

If the platforms have potentially different codings for double, then sending a bit pattern of the double is a problem.  If code wants portability, a less than "just copy the bits" approach is needed.  An alternative is below.

If platforms always have the same double format, just copy the n bits.  Example:@Rishikesh Raje

In detail, OP's problem is only loosely defined.  On many platforms, a double is a binary64 yet this is not required by C.  That double can represent about 264 different values exactly.  Neither -47.1235648 nor -47.848945 are one of those.  So it is possible OP does not have a strong precision concern.

"using the minimum computation as possible" implies minimal code, usually to have minimal time.  For speed, any solution should be rated on order of complexity  and with code profiling.

A portable method is to send via a string.  This approach addresses correctness and best possible precision first and performance second.  It removes endian issues as data is sent via a string and there is no precision/range loss in sending the data.  The receiving side, if the using the same double format will re-formed the double exactly.  With different double machines, it has a good string representation to do the best it can.

```<code>// some ample sized buffer
#define N (sizeof(double)*CHAR_BIT)

double x = foo();
char buf[N];
#if FLT_RADIX == 10
  // Rare based 10 platforms
  // If macro DBL_DECIMAL_DIG not available, use (DBL_DIG+3)
  sprintf(buf, "%.*e", DBL_DECIMAL_DIG-1, x);
#else
  // print mantissa in hexadecimal notation with power-of-2 exponent
  sprintf(buf, "%a", x);
#endif

bar_send_string(buf);
</code>```

To reconstitute the double

```<code>char *s = foo_get_string();

double y;
// %f decode strings in decimal(f), exponential(e) or hexadecimal/exponential notation(a)
if (sscanf(s, "%f", &y) != 1) Handle_Error(s);
else use(y);
</code>```

Title: Join two integers into one double

Body:
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

Body:
I need to transfer a double value (-47.1235648, for example) using sockets.

If the platforms have potentially different codings for double, then sending a bit pattern of the double is a problem.  If code wants portability, a less than "just copy the bits" approach is needed.  An alternative is below.

If platforms always have the same double format, just copy the n bits.  Example:@Rishikesh Raje

In detail, OP's problem is only loosely defined.  On many platforms, a double is a binary64 yet this is not required by C.  That double can represent about 264 different values exactly.  Neither -47.1235648 nor -47.848945 are one of those.  So it is possible OP does not have a strong precision concern.

"using the minimum computation as possible" implies minimal code, usually to have minimal time.  For speed, any solution should be rated on order of complexity  and with code profiling.

A portable method is to send via a string.  This approach addresses correctness and best possible precision first and performance second.  It removes endian issues as data is sent via a string and there is no precision/range loss in sending the data.  The receiving side, if the using the same double format will re-formed the double exactly.  With different double machines, it has a good string representation to do the best it can.

// some ample sized buffer
#define N (sizeof(double)*CHAR_BIT)

double x = foo();
char buf[N];
#if FLT_RADIX == 10
  // Rare based 10 platforms
  // If macro DBL_DECIMAL_DIG not available, use (DBL_DIG+3)
  sprintf(buf, "%.*e", DBL_DECIMAL_DIG-1, x);
#else
  // print mantissa in hexadecimal notation with power-of-2 exponent
  sprintf(buf, "%a", x);
#endif

bar_send_string(buf);

To reconstitute the double

char *s = foo_get_string();

double y;
// %f decode strings in decimal(f), exponential(e) or hexadecimal/exponential notation(a)
if (sscanf(s, "%f", &y) != 1) Handle_Error(s);
else use(y);


来源: stackexchange

问:
Method call from string variable
I want to replace the below (non DRY) code:

```<code>dir = value > node.data ? "right" : "left"

if value > node.data
  if node.right.nil?
    node.right = Node.new(value)
  else
    insert(value, node.right)
  end
else
  if node.left.nil?
    node.left = Node.new(value)
  else
    insert(value, node.left)
  end
end
</code>```

with something like this:

```<code>dir = value > node.data ? "right" : "left"
if node.dir.nil?
  node.dir = Node.new(value)
else
  insert(value, node.dir)
end
</code>```

Node is a struct defined like so:

```<code>Node = Struct.new(:data, :left, :right)
</code>```

How can I do this?

答:
Since it's a struct, you can use [:left] or [:right] instead of .left and .right.

Therefore, you can

```<code>dir = value > node.data ? :right : :left
if node[dir].nil?
  node[dir] = Node.new(value)
else
  insert(value, node[dir])
end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Method call from string variable

Body:
I want to replace the below (non DRY) code:

dir = value > node.data ? "right" : "left"

if value > node.data
  if node.right.nil?
    node.right = Node.new(value)
  else
    insert(value, node.right)
  end
else
  if node.left.nil?
    node.left = Node.new(value)
  else
    insert(value, node.left)
  end
end

with something like this:

dir = value > node.data ? "right" : "left"
if node.dir.nil?
  node.dir = Node.new(value)
else
  insert(value, node.dir)
end

Node is a struct defined like so:

Node = Struct.new(:data, :left, :right)

How can I do this?

Body:
Since it's a struct, you can use [:left] or [:right] instead of .left and .right.

Therefore, you can

dir = value > node.data ? :right : :left
if node[dir].nil?
  node[dir] = Node.new(value)
else
  insert(value, node[dir])
end


问:
ASP.NET Core 1.0 on IIS error 502.5 - Error Code 0x80004005
I just updated my server (Windows 2012R2) to .NET Core 1.0 RTM Windows Hosting pack from the previous .NET Core 1.0 RC2. My app works on my PC without any issues but the server keeps showing:

```<code>HTTP Error 502.5 - Process Failure

Common causes of this issue:

The application process failed to start
The application process started but then stopped
The application process started but failed to listen on the configured port
</code>```

It previously worked with the RC2 version. Don't know what could go wrong.

This is all event viewer says:

Failed to start process with the commandline 'dotnet .\MyWebApp.dll'. Error code = '0x80004005'.

the worst part is that app logs are empty! I mean those stdout_xxxxxxxxx.log files are completely empty and all have 0 byte size.

What should I do?? How can I know the cause of error when it's not logged??

答:
I had this problem aswell (The error occurred both on VS 15 and 17). However on VS15 it returned a CONNECTION_REFUSED error and on VS17 it returned ASP.NET Core 1.0 on IIS error 502.5.

FIX

Navigate to your project directory and locate the hidden folder .vs (it's located in the projects folder dir). (Remember to show hidden files/folders)

Close VS

Delete .vs-folder

Start VS as admin (.vs-folder will be recreated by VS)

ContentLicense: CC BY-SA 4.0

Body:
I just updated my server (Windows 2012R2) to .NET Core 1.0 RTM Windows Hosting pack from the previous .NET Core 1.0 RC2. My app works on my PC without any issues but the server keeps showing:

HTTP Error 502.5 - Process Failure

Common causes of this issue:

The application process failed to start
The application process started but then stopped
The application process started but failed to listen on the configured port

It previously worked with the RC2 version. Don't know what could go wrong.

This is all event viewer says:

Failed to start process with the commandline 'dotnet .\MyWebApp.dll'. Error code = '0x80004005'.

the worst part is that app logs are empty! I mean those stdout_xxxxxxxxx.log files are completely empty and all have 0 byte size.

What should I do?? How can I know the cause of error when it's not logged??


问:
Specflow and Angular JS Unit Testing
I have been a fan of BDD type testcases..Is it possible to combine Specflow with Angular JS Unit Testing (Jasmine?)

Has anyone ever tried it?

答:
Specflow is a .Net version of Cucumber, you can use protractor, the e2e test tool for angular with cucumber though here is the git library for it.

https://github.com/andrewkeig/protractor-cucumber

Title: Specflow and Angular JS Unit Testing


问:
Formula Field Not growing when in the same page footer as a sub-report
Basically, I have a formula that runs while printing records, that can print 0-3 rows using chr(13) and global stringvars to form a final string (tried with chr(10) and chr(13)), in the same page footer as a sub report that can have anywhere from 0 rows to above 3. Both are set to "Can grow" however the formula field never grows past the sub-report.

I'm using Crystal Reports 9.

I also tried using a box around the formula leading from the previous page footer to another page footer.

Here's my formula

```<code>WHILEPRINTINGRECORDS;
global stringvar WD;
global stringvar ADV;
global stringvar NASC;
stringvar final :="";

IF WD <> "" AND ADV <> "" AND NASC <> "" THEN final := WD  + Chr(13) + chr(10) +  NASC + Chr(13) + chr(10) + ADV
ELSE IF WD = "" AND ADV <> "" AND NASC <> "" THEN final := NASC + Chr(13) + chr(10) + ADV
ELSE IF WD <> "" AND ADV = "" AND NASC <> "" THEN final := WD + Chr(13) + chr(10) + NASC
ELSE IF WD <> "" AND ADV <> "" AND NASC = "" THEN final := WD + Chr(13) + chr(10) + ADV
ELSE IF WD = "" AND ADV = "" AND NASC = "" THEN final := "";
final
</code>```

And here's a sample of one of one of the formulas that set the stringvars, they all follow the same method.

```<code>WHILEPRINTINGRECORDS;
global Stringvar ADV;
global Stringvar Status;

if({COLUMN1}="EX"
  OR {COLUMN1}="ADV"
  OR {COLUMN1}="CR"
  OR {COLUMN1} = "DES" )
 THEN ( ADV := "#     - EXEMPT";  Status := "Status"; "#") ELSE ""
</code>```

答:
Each Subreport has it's own details section and if your fields are set there, it shows results for all of your rows, even if you put it in footer. Conversely, a formula that is set in a footer (page or report) works in an aggregate form, because footer is supposed to be used only for aggregate result (max,min,sum etc). If you put a formula in footer and you edit it to return a field value or something that it has to do with a field's value, then it will return result only for the first row of your select (like TOP 1 in SQL), I think.

Of course I am not completely sure because you have not displayed any results or your schema, but your case seems much like it

Body:
Basically, I have a formula that runs while printing records, that can print 0-3 rows using chr(13) and global stringvars to form a final string (tried with chr(10) and chr(13)), in the same page footer as a sub report that can have anywhere from 0 rows to above 3. Both are set to "Can grow" however the formula field never grows past the sub-report.

I'm using Crystal Reports 9.

I also tried using a box around the formula leading from the previous page footer to another page footer.

Here's my formula

WHILEPRINTINGRECORDS;
global stringvar WD;
global stringvar ADV;
global stringvar NASC;
stringvar final :="";

IF WD <> "" AND ADV <> "" AND NASC <> "" THEN final := WD  + Chr(13) + chr(10) +  NASC + Chr(13) + chr(10) + ADV
ELSE IF WD = "" AND ADV <> "" AND NASC <> "" THEN final := NASC + Chr(13) + chr(10) + ADV
ELSE IF WD <> "" AND ADV = "" AND NASC <> "" THEN final := WD + Chr(13) + chr(10) + NASC
ELSE IF WD <> "" AND ADV <> "" AND NASC = "" THEN final := WD + Chr(13) + chr(10) + ADV
ELSE IF WD = "" AND ADV = "" AND NASC = "" THEN final := "";
final

And here's a sample of one of one of the formulas that set the stringvars, they all follow the same method.

WHILEPRINTINGRECORDS;
global Stringvar ADV;
global Stringvar Status;

if({COLUMN1}="EX"
  OR {COLUMN1}="ADV"
  OR {COLUMN1}="CR"
  OR {COLUMN1} = "DES" )
 THEN ( ADV := "#     - EXEMPT";  Status := "Status"; "#") ELSE ""


问:
Having problems selecting items from mySQL database
Tables:

```<code>User:
ID
gender
looking_for_gender

User_Status:
User_ID1
User_ID2
Status
</code>```

While this select works, I also want to select users that has no status. In other words I want to select everyone that has no status or != FRIENDS. Somehow AND & OR does not do the trick.

Currently working query:

```<code>SELECT u.* FROM User u
JOIN User_Status us ON u.ID = us.User_ID1
WHERE us.Status != "FRIENDS"
AND us.User_ID2 =4 AND gender ="f"
</code>```

Sample Data User_Status:

User_ID1 ----- User_ID2 ----- Status

---- 1 ---------------- 4 ------------ has_send_request

---- 2 ---------------- 4 ------------ friends

---- 3 ---------------- 4 ------------ friends

Sample Data User:

ID

0

1

2

3

4

5

答:
you have to add the condition "has no Status" with or

```<code>WHERE (us.Status != "FRIENDS" or us.status is null) AND us.User_ID2 =4 AND gender ="f"
</code>```

UPDATE after clarification:

```<code>select u.* from user u left join user_status us on u.id = User_ID1 and us.User_ID2 =4  where gender ="f" and (us.Status != "FRIENDS" or us.status is null)
</code>```

Body:
Tables:

User:
ID
gender
looking_for_gender

User_Status:
User_ID1
User_ID2
Status

While this select works, I also want to select users that has no status. In other words I want to select everyone that has no status or != FRIENDS. Somehow AND & OR does not do the trick.

Currently working query:

SELECT u.* FROM User u
JOIN User_Status us ON u.ID = us.User_ID1
WHERE us.Status != "FRIENDS"
AND us.User_ID2 =4 AND gender ="f"

Sample Data User_Status:

User_ID1 ----- User_ID2 ----- Status

---- 1 ---------------- 4 ------------ has_send_request

---- 2 ---------------- 4 ------------ friends

---- 3 ---------------- 4 ------------ friends

Sample Data User:

ID

0

1

2

3

4

5

Body:
you have to add the condition "has no Status" with or

WHERE (us.Status != "FRIENDS" or us.status is null) AND us.User_ID2 =4 AND gender ="f"

UPDATE after clarification:

select u.* from user u left join user_status us on u.id = User_ID1 and us.User_ID2 =4  where gender ="f" and (us.Status != "FRIENDS" or us.status is null)


问:
PHP $_POST self: defaults for checkboxes
OK I am sending data with $_POST to itself.

I have some checkboxes that I have checked by default. (1 & 2 in this example)

When the form is sumbitted I want to override these default's with the $_POST value.

```<code><?php
    $syndication_check_1 = 'checked="checked"';
    $syndication_check_2 = 'checked="checked"';
    $syndication_check_3 = '';
    if (isset($_POST['syndication'])) {
        //
    }
?>

<form name="form" method="post" action="">
    <!-- this is what I use for radiobuttons -->
    <legend>Sex:</legend>
    <input type="radio" name="sex" id="sex-1" value="M" <?php echo (!isset($_POST['sex']) || $_POST['sex'] == "M") ? 'checked="checked"': ''; ?> />
    <label for="sex-1"><?= _("Male"); ?></label>
    <input type="radio" name="sex" id="sex-2" value="F" <?php echo (isset($_POST['sex']) && $_POST['sex'] == "F") ? 'checked="checked"': ''; ?> />
    <label for="sex-2"><?= _("Female"); ?></label>

    <!-- now something similar for checkboxes -->
    <legend>Syndication:</legend>
    <input type="checkbox" name="syndication[]" id="syndication-1" value="yahoo" <?= $syndication_check_1; ?> /> <!-- checked -->
    <label for="syndication-1">Yahoo Real Estate</label>
    <input type="checkbox" name="syndication[]" id="syndication-2" value="trulia" <?= $syndication_check_2; ?> /> <!-- checked -->
    <label for="syndication-2">Trulia.com</label>
    <input type="checkbox" name="syndication[]" id="syndication-3" value="zillow" <?= $syndication_check_3; ?> />
    <label for="syndication-3">Zillow.com</label>
</form>
</code>```

答:
Often names like $variable1, $variable2, $variable3 are hints that it should be $variable[0], $variable[1], $variable[2].  What I have below is only slightly more convenient now, but you'll really appreciate this if you extend to more checkboxes.

$syndication_checkboxes will holds the names and check/unchecked status of each checkbox.  The initial assignment represents "default" status which may or may not be overridden by $_POST.

```<code><?php
    $syndication_checkboxes = array(array('name' => 'Yahoo Real Estate',  'checked' => 1),
                                    array('name' => 'Trulia.com',  'checked' => 1),
                                    array('name' => 'Zillow.com',  'checked' => 0));

    if isset($_POST['syndication'])
    {
         $arr = array_fill(0, count($syndication_checkboxes), 0)
         foreach($_POST['syndication'] as $k=>$v)  //unfortunately in this case, merges on numeric arrays dont overwrite.  This could probably be written nicer as an array_walk or map
              $arr[$k] = $v;
         foreach($arr as $k=>$v)
              $syndication_checkboxes[$k]['checked'] = $v;
    }

    //Everything up to and including <legend>Syndication...

    foreach($syndication_checkboxes as $k=>$v)
    {
        $checkString = $v['checked'] ? "checked='checked'" : '';
        echo "<input type='checkbox' name='syndication[$k]' id='syndication-$k' value='1' $checkString />";
        echo "<label for='syndication-$k' >".$v['name']."</label>";
    }
    echo "</form>"
?>
</code>```

Now if you want to add new checkboxes all you have to do is add it to $syndication_checkboxes assignment up top.  This could even come from a database with tables for 'name' and 'default-checked' instead of being hardcoded which will be nice if it gets really big or you want to change it with an admin tool or something.

ContentLicense: CC BY-SA 2.5

Body:
OK I am sending data with $_POST to itself.

I have some checkboxes that I have checked by default. (1 & 2 in this example)

When the form is sumbitted I want to override these default's with the $_POST value.

<?php
    $syndication_check_1 = 'checked="checked"';
    $syndication_check_2 = 'checked="checked"';
    $syndication_check_3 = '';
    if (isset($_POST['syndication'])) {
        //
    }
?>

<form name="form" method="post" action="">

    <legend>Sex:</legend>
    <input type="radio" name="sex" id="sex-1" value="M" <?php echo (!isset($_POST['sex']) || $_POST['sex'] == "M") ? 'checked="checked"': ''; ?> />
    <?= _("Male"); ?>
    <input type="radio" name="sex" id="sex-2" value="F" <?php echo (isset($_POST['sex']) && $_POST['sex'] == "F") ? 'checked="checked"': ''; ?> />
    <?= _("Female"); ?>

    <legend>Syndication:</legend>
    <input type="checkbox" name="syndication[]" id="syndication-1" value="yahoo" <?= $syndication_check_1; ?> />
    Yahoo Real Estate
    <input type="checkbox" name="syndication[]" id="syndication-2" value="trulia" <?= $syndication_check_2; ?> />
    Trulia.com
    <input type="checkbox" name="syndication[]" id="syndication-3" value="zillow" <?= $syndication_check_3; ?> />
    Zillow.com
</form>

Body:
Often names like $variable1, $variable2, $variable3 are hints that it should be $variable[0], $variable[1], $variable[2].  What I have below is only slightly more convenient now, but you'll really appreciate this if you extend to more checkboxes.

$syndication_checkboxes will holds the names and check/unchecked status of each checkbox.  The initial assignment represents "default" status which may or may not be overridden by $_POST.

<?php
    $syndication_checkboxes = array(array('name' => 'Yahoo Real Estate',  'checked' => 1),
                                    array('name' => 'Trulia.com',  'checked' => 1),
                                    array('name' => 'Zillow.com',  'checked' => 0));

    if isset($_POST['syndication'])
    {
         $arr = array_fill(0, count($syndication_checkboxes), 0)
         foreach($_POST['syndication'] as $k=>$v)  //unfortunately in this case, merges on numeric arrays dont overwrite.  This could probably be written nicer as an array_walk or map
              $arr[$k] = $v;
         foreach($arr as $k=>$v)
              $syndication_checkboxes[$k]['checked'] = $v;
    }

    //Everything up to and including <legend>Syndication...

    foreach($syndication_checkboxes as $k=>$v)
    {
        $checkString = $v['checked'] ? "checked='checked'" : '';
        echo "<input type='checkbox' name='syndication[$k]' id='syndication-$k' value='1' $checkString />";
        echo "<label for='syndication-$k' >".$v['name']."</label>";
    }
    echo "</form>"
?>

Now if you want to add new checkboxes all you have to do is add it to $syndication_checkboxes assignment up top.  This could even come from a database with tables for 'name' and 'default-checked' instead of being hardcoded which will be nice if it gets really big or you want to change it with an admin tool or something.


答:
Seems you are finding the NOT clause:

https://www.techonthenet.com/sql/not.php

You can make something like:

```<code> SELECT u.* FROM User u JOIN User_Status us ON u.ID = us.User_ID1 WHERE status IS NOT NULL
</code>```

Title: Having problems selecting items from mySQL database

Body:
Seems you are finding the NOT clause:

https://www.techonthenet.com/sql/not.php

You can make something like:

 SELECT u.* FROM User u JOIN User_Status us ON u.ID = us.User_ID1 WHERE status IS NOT NULL


问:
Install Kite plugin in Portable Sublime Text 3
My question is essentially a copy of (Install Kite plugin in GitHub's Atom Editor) for Sublime Text 3, specifically the portable no-install version (I'm on Windows 10, but this possibly applies cross platform).

How do I install the plugin for this please?

I tried the "Add Repository" option in Sublime Text 3, with URL: https://github.com/kiteco/plugins

but this doesn't seem to have added any functionality or add Kite to my package list.

Thanks

答:
The structure they use is not natively supported by Sublime Text, because it does not load plugins from subfolders. However you can

Clone/download the repository.

In Sublime Text select Preferences > Browse Packages.... This should open a folder.

In that folder create a subfolder Kite and copy the files from the kite sublime-text folder into it.
As an alternative you can also create a symlink.


问:
python to remove space between Chinese unicode strings but not between English words
need help on python regex, I have a string contains Chinese and English,  I would like to remove white space between Chinese characters but not between English words.

from -- "u'\u5c0f \u5973 \u4eca \u5e74 \u4fc2 dse \u8003 \u751f \u5979 \u559c \u6b61 filmtv \u524d \u5e7e \u65e5 in \u5de6 buasso-filmtv and digital media studies \u5df2 \u7d93 condition offer \u4f46 \u60f3 \u554f \u5982 \u679c through jupas openu \u6536 \u5979 \u8b80 bachelor of arts with honours In creative writing and filmarts"

to -- "u'\u5c0f\u5973\u4eca\u5e74\u4fc2 dse \u8003\u751f\u5979\u559c\u6b61 filmtv \u524d\u5e7e\u65e5 in \u5de6 buasso-filmtv and digital media studies \u5df2\u7d93 condition offer \u4f46\u60f3\u554f\u5982\u679c through jupas openu \u6536\u5979\u8b80 bachelor of arts with honours In creative writing and filmarts"

only remove white space when it's between two unicode characters

答:
If you're fine with defining "unicode characters" as "non-ASCII" characters then you can do this with negative lookahead/lookbehind:

```<code>re.sub("(?<![ -~]) (?![ -~])", "", text)
</code>```

If you don't like the ranges used ([ -~]) then this question has some alternatives. Additionally there are a variety of unicode categories that might serve your purpose better, but as far as I can tell you'll still have to manually define the character range as they're unsupported in the re module.

Body:
If you're fine with defining "unicode characters" as "non-ASCII" characters then you can do this with negative lookahead/lookbehind:

re.sub("(?<![ -~]) (?![ -~])", "", text)

If you don't like the ranges used ([ -~]) then this question has some alternatives. Additionally there are a variety of unicode categories that might serve your purpose better, but as far as I can tell you'll still have to manually define the character range as they're unsupported in the re module.


问:
Loop zip, append in Python
I am strugling with something in python...

I have a function that when I input a date, it gives me back a column with 30 prices (one in each line) and in index 30 names.

```<code>[in] getPrice('14/07/2015')

[out]
apple   10
pear    20
orange  12
banana  23
etc...
</code>```

The number of fruit are the same.
What I am trying to do is, to loop this function to obtain a big file with the price of these fruits for all the days I have in a list.
with the ZIP function I dont really understand how it could work and with the append function it is not 'zipping' the price, meaning it recreate everytime the index, etc..
Any idea?
I have a list with all my dates already and the index is the same all along, no other fruit apprear or disapear.

It could look like something

```<code>Def Alltogether():
    Alltogether = []
    x = HistoricalDates
    For _ in Historicaldates :
        k = getPrice....
</code>```

and then I block...

I ultimately want something like

```<code>print Alltogether

[out]
apple   10 40 60 20 ...
pear    20 20 20 20 ...
orange  12 13 14 29 ...
banana  23 14 41 54 ...
etc...
</code>```

I am using panda dataframe.

Thank you very much!

答:
Is THIS what are you have problem with? Just use '*' to pass a list of lists to zip(). Here an example:

```<code>L1=['L1-i1','L1-i2', 'L1-i3', 'L1-i4']
L2=['L2-i1','L2-i2', 'L2-i3', 'L2-i4']
L3=['L3-i1','L3-i2', 'L3-i3', 'L3-i4']

Lalltogether = [L1, L2, L3]

# in Python 3 you should use list() for zip():
print( list(zip( *Lalltogether )) )
print( list(zip(  L1, L2, L3   )) )
</code>```

gives:

```<code>[('L1-i1', 'L2-i1', 'L3-i1'), ('L1-i2', 'L2-i2', 'L3-i2'), ('L1-i3', 'L2-i3', 'L3-i3'), ('L1-i4', 'L2-i4', 'L3-i4')]
</code>```

For more about '*' see
Python - use list as function parameters

Title: Loop zip, append in Python

Body:
I am strugling with something in python...

I have a function that when I input a date, it gives me back a column with 30 prices (one in each line) and in index 30 names.

[in] getPrice('14/07/2015')

[out]
apple   10
pear    20
orange  12
banana  23
etc...

The number of fruit are the same.
What I am trying to do is, to loop this function to obtain a big file with the price of these fruits for all the days I have in a list.
with the ZIP function I dont really understand how it could work and with the append function it is not 'zipping' the price, meaning it recreate everytime the index, etc..
Any idea?
I have a list with all my dates already and the index is the same all along, no other fruit apprear or disapear.

It could look like something

Def Alltogether():
    Alltogether = []
    x = HistoricalDates
    For _ in Historicaldates :
        k = getPrice....

and then I block...

I ultimately want something like

print Alltogether

[out]
apple   10 40 60 20 ...
pear    20 20 20 20 ...
orange  12 13 14 29 ...
banana  23 14 41 54 ...
etc...

I am using panda dataframe.

Thank you very much!

Body:
Is THIS what are you have problem with? Just use '*' to pass a list of lists to zip(). Here an example:

L1=['L1-i1','L1-i2', 'L1-i3', 'L1-i4']
L2=['L2-i1','L2-i2', 'L2-i3', 'L2-i4']
L3=['L3-i1','L3-i2', 'L3-i3', 'L3-i4']

Lalltogether = [L1, L2, L3]

# in Python 3 you should use list() for zip():
print( list(zip( *Lalltogether )) )
print( list(zip(  L1, L2, L3   )) )

gives:

[('L1-i1', 'L2-i1', 'L3-i1'), ('L1-i2', 'L2-i2', 'L3-i2'), ('L1-i3', 'L2-i3', 'L3-i3'), ('L1-i4', 'L2-i4', 'L3-i4')]

For more about '*' see
Python - use list as function parameters


问:
Send media action on android
I'm looking for a way to send global media action (Play/pause, Next, Previous) to the phone, much like it can take it froma bluetooth paired radio/speaker.

I have found the MediaController class (http://developer.android.com/reference/android/widget/MediaController.html) but it seem more to be to implement the receiver of those action and i'm looking for a sender.

However, I can't seam to find any reference to this anywhere in the android doc...

Anyone already stumble on this ?

答: You can easily send broadcast actions for media (and many other events) with ActivityManager via adb  e.g. adb shell am broadcast -a android.intent.action.MEDIA_MOUNTED will mount your media. See many more here: https://developer.android.com/reference/android/content/Intent.html

Title: Send media action on android


问:
WPF PRISM event subcriptions not dying
I have a PRISM RegionManager with a couple of region - a Ribbon region on the top, and a main content region for my view underneath it - fairly basic.

The app starts with a "home" view in the main content area. When I click a button on the Ribbon, I inject a second view into the content area and navigate to it in the region manager. When I click a button on this view, it should be removed and the original view should be shown.

I'm currently doing this using the RegionManager.Add() method to manually add the second view. When I want to remove it, I publish an event which is consumed by a manager class that gets the current active remove, calls Remove() on the Region Manager for it, and then navigates back to the original view.

This all works great, except that when the second view is left alive after I call Remove(), and keeps a handle onto any subscriptions that it made during its lifetime! I've tried calling Subscribe explicitly with false for weak event references, but this is the default anyway, and it didn't help. I've tried both types of creating the view (discovery and injection) and removing the view via Remove and Deactivate. None of them helped. This is a real problem as when I want to create the same view in the future (a new instance of that view), I'm left with several instances of them, all subscribing to the same events, even though some of those instances were removed ages ago from the Region Manager.

Do I need to manually unsubscribe from every event that I subscribe to in my views (highly undesirable)? Or is there some way that I can dispose of the control / mark it as deactivated so that its subscriptions get removed?

I get the feeling that I'm doing something silly here but it's got me completely stumped.

Thanks

答:
This is a known issue. There is a bug in the eventAggregator code. Take a look at the following blog and the suggested hack to overcome it
http://greenicicleblog.com/2010/04/28/prism-event-aggregator-more-leaky-than-it-seems/

Hope this helps

Title: WPF PRISM event subcriptions not dying


问:
Add more nodes to Kubernetes cluster on ACS
I think that this command should have helped me scale up my single agent k8s cluster on Azure Container Service:

```<code>az acs scale --name krish_acs_cluster_west --new-agent-count 2 --resource-group krish_res_grp_west --debug --output json
</code>```

However, it doesn't work as expected, and I get an error log as:

```<code>requests.packages.urllib3.connectionpool : Starting new HTTPS connection (1): management.azure.com
requests.packages.urllib3.connectionpool : https://management.azure.com:443 "GET /subscriptions/1225d95b-e76d-4d21-90a0-2f137dee9c84/resourceGroups/krish_res_grp_west/providers/Microsoft.ContainerService/containerServices/krish_acs_cluster_west?api-version=2017-01-31 HTTP/1.1" 200 None
msrest.http_logger : Response status: 200
msrest.http_logger : Response headers:
msrest.http_logger :     'Cache-Control': 'no-cache'
msrest.http_logger :     'Pragma': 'no-cache'
msrest.http_logger :     'Transfer-Encoding': 'chunked'
msrest.http_logger :     'Content-Type': 'application/json; charset=utf-8'
msrest.http_logger :     'Content-Encoding': 'gzip'
msrest.http_logger :     'Expires': '-1'
msrest.http_logger :     'Vary': 'Accept-Encoding'
msrest.http_logger :     'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
msrest.http_logger :     'x-ms-served-by': '1b39334a-f523-4de8-b14d-738ab830ba48_131305327966325140'
msrest.http_logger :     'x-ms-request-id': '5fc2db3e-a70c-4403-b761-60872cb099f9'
msrest.http_logger :     'Server': 'Microsoft-HTTPAPI/2.0, Microsoft-HTTPAPI/2.0'
msrest.http_logger :     'x-ms-ratelimit-remaining-subscription-reads': '14581'
msrest.http_logger :     'x-ms-correlation-request-id': 'f1048446-30b4-42f5-968d-08004a0472c6'
msrest.http_logger :     'x-ms-routing-request-id': 'WESTEUROPE:20170309T214442Z:f1048446-30b4-42f5-968d-08004a0472c6'
msrest.http_logger :     'Date': 'Thu, 09 Mar 2017 21:44:42 GMT'
msrest.http_logger : Response content:
msrest.http_logger : Body contains chunked data.
msrest.exceptions : Parameter 'ContainerServiceServicePrincipalProfile.secret' can not be None.
Parameter 'ContainerServiceServicePrincipalProfile.secret' can not be None.
</code>```

答: Any ACS Kubernetes clusters created before the GA version (Feb 22, 2017) will not be able to scale up/down.</p>

Body:
I think that this command should have helped me scale up my single agent k8s cluster on Azure Container Service:

az acs scale --name krish_acs_cluster_west --new-agent-count 2 --resource-group krish_res_grp_west --debug --output json

However, it doesn't work as expected, and I get an error log as:

requests.packages.urllib3.connectionpool : Starting new HTTPS connection (1): management.azure.com
requests.packages.urllib3.connectionpool : https://management.azure.com:443 "GET /subscriptions/1225d95b-e76d-4d21-90a0-2f137dee9c84/resourceGroups/krish_res_grp_west/providers/Microsoft.ContainerService/containerServices/krish_acs_cluster_west?api-version=2017-01-31 HTTP/1.1" 200 None
msrest.http_logger : Response status: 200
msrest.http_logger : Response headers:
msrest.http_logger :     'Cache-Control': 'no-cache'
msrest.http_logger :     'Pragma': 'no-cache'
msrest.http_logger :     'Transfer-Encoding': 'chunked'
msrest.http_logger :     'Content-Type': 'application/json; charset=utf-8'
msrest.http_logger :     'Content-Encoding': 'gzip'
msrest.http_logger :     'Expires': '-1'
msrest.http_logger :     'Vary': 'Accept-Encoding'
msrest.http_logger :     'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
msrest.http_logger :     'x-ms-served-by': '1b39334a-f523-4de8-b14d-738ab830ba48_131305327966325140'
msrest.http_logger :     'x-ms-request-id': '5fc2db3e-a70c-4403-b761-60872cb099f9'
msrest.http_logger :     'Server': 'Microsoft-HTTPAPI/2.0, Microsoft-HTTPAPI/2.0'
msrest.http_logger :     'x-ms-ratelimit-remaining-subscription-reads': '14581'
msrest.http_logger :     'x-ms-correlation-request-id': 'f1048446-30b4-42f5-968d-08004a0472c6'
msrest.http_logger :     'x-ms-routing-request-id': 'WESTEUROPE:20170309T214442Z:f1048446-30b4-42f5-968d-08004a0472c6'
msrest.http_logger :     'Date': 'Thu, 09 Mar 2017 21:44:42 GMT'
msrest.http_logger : Response content:
msrest.http_logger : Body contains chunked data.
msrest.exceptions : Parameter 'ContainerServiceServicePrincipalProfile.secret' can not be None.
Parameter 'ContainerServiceServicePrincipalProfile.secret' can not be None.


问:
Global Variable and list assignment in R, getting unexpected result
I'm programming in R and I am placing lists inside lists. Consider the following vector:

```<code>> a = c(1,2,3)
> a
[1] 1 2 3
</code>```

Then define a global list:

```<code>> foo <<- list()
> foo[[1]] <- a
> foo
[[1]]
[1] 1 2 3
</code>```

and all is fine. Trying to modify this list inside a function/subroutine leads to

```<code>> foo <<- list()
> foo
list()
test <- function(){ foo[[1]] <- "a" }
> test()
> foo
list()
</code>```

I'm finding that outside the subroutine that foo[[1]] is

```<code>> foo[[1]]
Error in foo[[1]] : subscript out of bounds
</code>```

Lets say however that I want foo to be global, then

```<code>> foo <<- list()
> foo[[1]] <<- a
Error in foo[[1]] <<- a : object 'foo' not found
</code>```

gives a error - why? Additionally

```<code>> foo <<- list()
> foo
list()
test <- function(){ foo[[1]] <<- "a" }
> test()
> foo
list()
> foo[[1]]
Error in foo[[1]] : subscript out of bounds
</code>```

Finally trying

```<code>function(){ foo[[1]] <<-list(); foo[[1]] <<- "a" }
</code>```

also doesn't result in anything fruitful. What am I doing wrong?

答:
You make an understandible but important mistake: The <<- operator is used to assign something in the global environment from within a function, whereas you use it in the global environment.

To do what you want to do, try the following:

```<code>foo <- list()
myfun <- function(){
  foo[[1]] <<- 1
}
myfun()
foo
</code>```

edited per @MrFlicks comment:

To be 100% correct, <<- actually looks for an object with the name foo in all parent environments. If it finds one, it will change that foo to the new value. If it doesn't, it assigns in the global environment. You can have more control over the exact environment where the assignment takes place by using the function assign, but with that one you can't set elements of a list. So the code would become:

```<code>foo <- list()
myfun <- function(){
  tmp <- get('foo',.GlobalEnv)
  tmp[[1]] <- 1
  assign("foo",tmp, .GlobalEnv)
}
myfun()
foo
</code>```

Still, this is not a good idea in R.

Globals in R are not globals

R doesn't have "globals" that work the same as globals in eg Java. Actually, the entire idea of R goes against the logic of globals. So while you might think <<- defines a global, all it does is create an empty list in the global environment. But this is not what we understand under a global variable, because it can easily be deleted again from the global environment:

```<code>rm(foo)
myfun()
#> Error in foo[[1]] <<- 1 : object 'foo' not found
</code>```

R functions are expected to have no side effects apart from a few obvious exceptions, so there are few mechanisms to actually define global variables.

How to do globals in R

If you really need a global variable that functions more like one would expect from a global, you can do a few different things. The best idea imho is using the options mechanism. R allows you to define your own option:

```<code>options(foo = list())
myfun <- function(){
  tmp <- getOption("foo")
  tmp[[1]] <- 1
  options(foo = tmp)
}
myfun()
getOption("foo")
</code>```

To remove the option foo, just set it to NULL

```<code>options(foo = NULL)
</code>```

On a sidenote: If you're developing a package, you can also define an object in the namespace of the package, just like you do with the functions. But I haven't found a good use case for this construct yet. My packages use the option mechanism, and that's what the user of a package will expect.

Body:
I'm programming in R and I am placing lists inside lists. Consider the following vector:

> a = c(1,2,3)
> a
[1] 1 2 3

Then define a global list:

> foo <<- list()
> foo[[1]] <- a
> foo
[[1]]
[1] 1 2 3

and all is fine. Trying to modify this list inside a function/subroutine leads to

> foo <<- list()
> foo
list()
test <- function(){ foo[[1]] <- "a" }
> test()
> foo
list()

I'm finding that outside the subroutine that foo[[1]] is

> foo[[1]]
Error in foo[[1]] : subscript out of bounds

Lets say however that I want foo to be global, then

> foo <<- list()
> foo[[1]] <<- a
Error in foo[[1]] <<- a : object 'foo' not found

gives a error - why? Additionally

> foo <<- list()
> foo
list()
test <- function(){ foo[[1]] <<- "a" }
> test()
> foo
list()
> foo[[1]]
Error in foo[[1]] : subscript out of bounds

Finally trying

function(){ foo[[1]] <<-list(); foo[[1]] <<- "a" }

also doesn't result in anything fruitful. What am I doing wrong?

Body:
You make an understandible but important mistake: The <<- operator is used to assign something in the global environment from within a function, whereas you use it in the global environment.

To do what you want to do, try the following:

foo <- list()
myfun <- function(){
  foo[[1]] <<- 1
}
myfun()
foo

edited per @MrFlicks comment:

To be 100% correct, <<- actually looks for an object with the name foo in all parent environments. If it finds one, it will change that foo to the new value. If it doesn't, it assigns in the global environment. You can have more control over the exact environment where the assignment takes place by using the function assign, but with that one you can't set elements of a list. So the code would become:

foo <- list()
myfun <- function(){
  tmp <- get('foo',.GlobalEnv)
  tmp[[1]] <- 1
  assign("foo",tmp, .GlobalEnv)
}
myfun()
foo

Still, this is not a good idea in R.

Globals in R are not globals

R doesn't have "globals" that work the same as globals in eg Java. Actually, the entire idea of R goes against the logic of globals. So while you might think <<- defines a global, all it does is create an empty list in the global environment. But this is not what we understand under a global variable, because it can easily be deleted again from the global environment:

rm(foo)
myfun()
#> Error in foo[[1]] <<- 1 : object 'foo' not found

R functions are expected to have no side effects apart from a few obvious exceptions, so there are few mechanisms to actually define global variables.

How to do globals in R

If you really need a global variable that functions more like one would expect from a global, you can do a few different things. The best idea imho is using the options mechanism. R allows you to define your own option:

options(foo = list())
myfun <- function(){
  tmp <- getOption("foo")
  tmp[[1]] <- 1
  options(foo = tmp)
}
myfun()
getOption("foo")

To remove the option foo, just set it to NULL

options(foo = NULL)

On a sidenote: If you're developing a package, you can also define an object in the namespace of the package, just like you do with the functions. But I haven't found a good use case for this construct yet. My packages use the option mechanism, and that's what the user of a package will expect.


问:
How to convert xts object in JSON in R?
I would like to convert an xts object which has the class Date into JSON with jsonlite::toJSON but it returns an error saying No method asJSON S3 class: zoo.

My objective is to have a JSON file that can be handled by highcharts.js library, so I'm trying to have severals arrays [unixtime, value], something like this :

```<code>[[1489363200, -0.01766174], [1489968000, 0.00000021], [1490572800, 0.00000098]]
</code>```

This is my xts object :

```<code>> obj
             values
2017-03-13 -0.01766174
2017-03-20  0.00000021
2017-03-27  0.00000098
</code>```

The documentation of toJSON mention a Date option that is used
to encode Date objects: must be one of 'ISO8601' or 'epoch', but for some reason there is the same error.

```<code>> data <- toJSON(obj, dataframe = "values", Date="epoch")
Error: No method asJSON S3 class: zoo
</code>```

If I convert the xts into a dataframe or a matrix I can export in JSON but the format is no appropriate for highcharts.js :

```<code>[-0.0177,"2017-03-13"],[0,"2017-03-20"],[0,"2017-03-27"]]
</code>```

Is there a possibility to export an xts object in a JSON by keeping the time serie ?

Thank you,

答:
One way to do it would be do it manually. The main steps are:

Transform the xts to a data frame object

Then transform the date object to numeric using the datetime_to_timestamp from the highcharter package.

The use toJSON,

library(xts)
library(highcharter)
library(jsonlite)
data(sample_matrix)

obj <- as.xts(head(sample_matrix[, 1], 3), descr = "my new xts object")
obj
#>                [,1]
#> 2007-01-02 50.03978
#> 2007-01-03 50.23050
#> 2007-01-04 50.42096

df <- data.frame(time = time(obj), values = as.vector(obj))
df
#>         time   values
#> 1 2007-01-02 50.03978
#> 2 2007-01-03 50.23050
#> 3 2007-01-04 50.42096

df$time <- datetime_to_timestamp(df$time)
df
#>           time   values
#> 1 1.167707e+12 50.03978
#> 2 1.167793e+12 50.23050
#> 3 1.167880e+12 50.42096

toJSON(as.matrix(df))
#> [[1167706800000,50.0398],[1167793200000,50.2305],[1167879600000,50.421]]
```

Title: How to convert xts object in JSON in R?

Body:
I would like to convert an xts object which has the class Date into JSON with jsonlite::toJSON but it returns an error saying No method asJSON S3 class: zoo.

My objective is to have a JSON file that can be handled by highcharts.js library, so I'm trying to have severals arrays [unixtime, value], something like this :

[[1489363200, -0.01766174], [1489968000, 0.00000021], [1490572800, 0.00000098]]

This is my xts object :

> obj
             values
2017-03-13 -0.01766174
2017-03-20  0.00000021
2017-03-27  0.00000098

The documentation of toJSON mention a Date option that is used
to encode Date objects: must be one of 'ISO8601' or 'epoch', but for some reason there is the same error.

> data <- toJSON(obj, dataframe = "values", Date="epoch")
Error: No method asJSON S3 class: zoo

If I convert the xts into a dataframe or a matrix I can export in JSON but the format is no appropriate for highcharts.js :

[-0.0177,"2017-03-13"],[0,"2017-03-20"],[0,"2017-03-27"]]

Is there a possibility to export an xts object in a JSON by keeping the time serie ?

Thank you,


问:
How to convert a DICOM from Monochrome 1 to Monochrome 2?
I am working on a project with DICOM images where I need to compare two DICOM images. The problem is, one is in monochrome 1 and the other is in monochrome 2 (zero means white and black, respectively). How can I convert these pixel intensities to compare them? I am using the "pydicom" toolkit.</p>

答:
Your major problem is not the Photometric Interpretation (MONO1/2).

You cannot compare pixel intensities of two DICOM images unless they refer to the same scale (e.g. Hounsfield Units).

If you have

```<code>(0028,1052) RescaleIntercept - present with any value
(0028,1053) RescaleSlope - present with any value
(0028,1054) RescaleType - present with value "OD" or "HU"
</code>```

Then it is pretty easy: Apply the linear transformation:

```<code><measured value> = <pixel value> * RescaleSlope + RescaleIntercept
</code>```

The measured values can be compared.

The same is true if you have a non-linear Modality LUT stored as a lookup table in the header, but the same restrictions apply for Rescale Type.

Otherwise I would refrain from comparing pixel values. Of course, it appears to be easy to just invert one of the two images, but the fact that they have different Photometric Interpretation tells me that they have been acquired by different devices or techniques. This means, that the pixel data is visually correct and comparable but not mathematically related.

Body:
Your major problem is not the Photometric Interpretation (MONO1/2).

You cannot compare pixel intensities of two DICOM images unless they refer to the same scale (e.g. Hounsfield Units).

If you have

(0028,1052) RescaleIntercept - present with any value
(0028,1053) RescaleSlope - present with any value
(0028,1054) RescaleType - present with value "OD" or "HU"

Then it is pretty easy: Apply the linear transformation:

<measured value> = <pixel value> * RescaleSlope + RescaleIntercept

The measured values can be compared.

The same is true if you have a non-linear Modality LUT stored as a lookup table in the header, but the same restrictions apply for Rescale Type.

Otherwise I would refrain from comparing pixel values. Of course, it appears to be easy to just invert one of the two images, but the fact that they have different Photometric Interpretation tells me that they have been acquired by different devices or techniques. This means, that the pixel data is visually correct and comparable but not mathematically related.


问:
PHP Script for Mobile Application with 2 Left Joins
I'm currently working on an Android app that needs to get and send data via PHP to a server with a MySQL database.

I'm relatively new to PHP and I couldn't find any specific help for my problem.

Here is my code

```<code><?php
    $db_name = "testwz";
    $mysql_user = "root";
    $mysql_pass = "";
    $server_name = "localhost";
    $con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);

    $sql = "SELECT verbrauchsstelle.ID, adressen.Ort, adressen.Ortsteil,
                adressen.PLZ, adressen.Strasse, adressen.Hausnummer, zaehler.Nummer
            FROM verbrauchsstelle
            LEFT JOIN adressen ON verbrauchsstelle.adressen_id = adressen.ID
            LEFT JOIN zaehler ON zaehler.Verbrauchsstelle_id = verbrauchsstelle.ID;
    ";

    $result = mysqli_query($con, $sql);
    $response = array();

    while($row = mysqli_fetch_array($result))
    {
        array_push($response, array(
            "vID" => $row[0],
            "Ort" => $row[1],
            "Ortsteil" => $row[2],
            "PLZ" => $row[3],
            "Strasse" => $row[4],
            "Hausnummer" => $row[5],
            "zNr" => $row[6]
        ));
    }

    echo json_encode(array("server_response" => $response));
    mysqli_close($con);
?>
</code>```

The SQL itself is doing fine when used with SQLyog; when I delete one of the LEFT JOINs I get an output but using both of them, I get a blank white screen in the browser.
I tried LEFT JOIN and INNER JOIN with the same result.

Maybe someone with way better PHP knowledge can help me find the error.

Thanks in advance.

答:
You can try this:

```<code><?php
$db_name = "testwz";
$mysql_user = "root";
$mysql_pass = "";
$server_name = "localhost";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);

$sql = "SELECT verbrauchsstelle.ID, adressen.Ort, adressen.Ortsteil,
            adressen.PLZ, adressen.Strasse, adressen.Hausnummer, zaehler.Nummer
        FROM verbrauchsstelle
        LEFT JOIN adressen ON verbrauchsstelle.adressen_id = adressen.ID
        LEFT JOIN zaehler ON zaehler.Verbrauchsstelle_id = verbrauchsstelle.ID
";

$result = mysqli_query($con, $sql);
if (!mysqli_error($con)) {
   echo json_encode(array("server_response" => mysqli_error($con)));
   mysqli_close($con);
   exit;
}

$response = array();

while($row = mysqli_fetch_array($result))
{
    array_push($response, array(
        "vID" => $row[0],
        "Ort" => $row[1],
        "Ortsteil" => $row[2],
        "PLZ" => $row[3],
        "Strasse" => $row[4],
        "Hausnummer" => $row[5],
        "zNr" => $row[6]
    ));
}

echo json_encode(array("server_response" => $response));
mysqli_close($con);
</code>```

This  will show you the exact error if any else it will give you the desired output what you want.

Body:
I'm currently working on an Android app that needs to get and send data via PHP to a server with a MySQL database.

I'm relatively new to PHP and I couldn't find any specific help for my problem.

Here is my code

<?php
    $db_name = "testwz";
    $mysql_user = "root";
    $mysql_pass = "";
    $server_name = "localhost";
    $con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);

    $sql = "SELECT verbrauchsstelle.ID, adressen.Ort, adressen.Ortsteil,
                adressen.PLZ, adressen.Strasse, adressen.Hausnummer, zaehler.Nummer
            FROM verbrauchsstelle
            LEFT JOIN adressen ON verbrauchsstelle.adressen_id = adressen.ID
            LEFT JOIN zaehler ON zaehler.Verbrauchsstelle_id = verbrauchsstelle.ID;
    ";

    $result = mysqli_query($con, $sql);
    $response = array();

    while($row = mysqli_fetch_array($result))
    {
        array_push($response, array(
            "vID" => $row[0],
            "Ort" => $row[1],
            "Ortsteil" => $row[2],
            "PLZ" => $row[3],
            "Strasse" => $row[4],
            "Hausnummer" => $row[5],
            "zNr" => $row[6]
        ));
    }

    echo json_encode(array("server_response" => $response));
    mysqli_close($con);
?>

The SQL itself is doing fine when used with SQLyog; when I delete one of the LEFT JOINs I get an output but using both of them, I get a blank white screen in the browser.
I tried LEFT JOIN and INNER JOIN with the same result.

Maybe someone with way better PHP knowledge can help me find the error.

Thanks in advance.

Body:
You can try this:

<?php
$db_name = "testwz";
$mysql_user = "root";
$mysql_pass = "";
$server_name = "localhost";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);

$sql = "SELECT verbrauchsstelle.ID, adressen.Ort, adressen.Ortsteil,
            adressen.PLZ, adressen.Strasse, adressen.Hausnummer, zaehler.Nummer
        FROM verbrauchsstelle
        LEFT JOIN adressen ON verbrauchsstelle.adressen_id = adressen.ID
        LEFT JOIN zaehler ON zaehler.Verbrauchsstelle_id = verbrauchsstelle.ID
";

$result = mysqli_query($con, $sql);
if (!mysqli_error($con)) {
   echo json_encode(array("server_response" => mysqli_error($con)));
   mysqli_close($con);
   exit;
}

$response = array();

while($row = mysqli_fetch_array($result))
{
    array_push($response, array(
        "vID" => $row[0],
        "Ort" => $row[1],
        "Ortsteil" => $row[2],
        "PLZ" => $row[3],
        "Strasse" => $row[4],
        "Hausnummer" => $row[5],
        "zNr" => $row[6]
    ));
}

echo json_encode(array("server_response" => $response));
mysqli_close($con);

This  will show you the exact error if any else it will give you the desired output what you want.


问:
Automator Javascript - "Choose From List" return values
I'am trying to create a Service which allow user to choose a folder, then show a list with options where he can choose from and based on the selected items, automator should create a folder for each chosen item in the list.

What I got so far:

1) Asked for Finder item => this allows user to choose a folder

2) JS where I create the options for the list

```<code>function run(input, parameters) {

 var array = ["PDF", "LINKS", "PERSMAP", "SCHUIMKARTON", "INSPIRATIE"];
 var arrayLength = array.length;

 return array;
}
</code>```

This gives me the following output when already when I run:

3) Added another JS-script Where I return the input (this returns only the selected items)

4) ... This is where I'am stuck. How do I create a folder now for each selected option from within the list?

Complete overview in next atachment

答:
You can use the chooseFromList command in your JavaScript instead of the "Choose from List" action and another "Run JavaScript" action.

You an use .map() to loop from the selected items.

Here's the script:

```<code>function run(input, parameters) {
    thisApp = Application.currentApplication()
    thisApp.includeStandardAdditions = true
    var destFolder = input[0];// the destination folder
    var array = ["PDF", "LINKS", "PERSMAP", "SCHUIMKARTON", "INSPIRATIE"];

    theseNames = thisApp.chooseFromList(array, {withPrompt: 'Which folders to create?', multipleSelectionsAllowed:true});
    if (theseNames == false) {return}; // exit this script because user cancelled

    // (for each selected name then create the folder if this name does not already exists in the destination folder), return path of these sub-folders to the next action
    return theseNames.map(function(thisName) {
        newFolder = destFolder + "/" + thisName + "/";// concatenation of the destination folder and an item in theseNames
        $.NSFileManager.defaultManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder,false,$(), $());
        return newFolder;
    });
 }
</code>```

Update

To create some subfolders within the new folder, use conditions (if name equal some name), like this:

```<code>function run(input, parameters) {
    thisApp = Application.currentApplication()
    thisApp.includeStandardAdditions = true
    var destFolder = input[0];// the destination folder
    var array = ["PDF", "LINKS", "PERSMAP", "SCHUIMKARTON", "INSPIRATIE"];

    theseNames = thisApp.chooseFromList(array, {withPrompt: 'Which folders to create?', multipleSelectionsAllowed:true});
    if (theseNames == false) {return}; // exit this script because user cancelled

    f_m = $.NSFileManager.defaultManager;
    // (for each selected name then create the folder if this name does not already exists in the destination folder), return path of these sub-folders to the next action
    return theseNames.map(function(thisName) {
        newFolder = destFolder + "/" + thisName + "/";// concatenation of the destination folder and an item in theseNames
        f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder,false,$(), $());
        if (thisName == "PDF") { // create folder1 and folder2 in the PDF folder
            f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder + "folder1",false,$(), $());
            f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder + "folder2",false,$(), $());
        }
        if (thisName == "INSPIRATIE") { // create folderX in the INSPIRATIE folder
            f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder + "folderX",false,$(), $());
        }
        return newFolder;
    });
 }
</code>```

Body:
I'am trying to create a Service which allow user to choose a folder, then show a list with options where he can choose from and based on the selected items, automator should create a folder for each chosen item in the list.

What I got so far:

1) Asked for Finder item => this allows user to choose a folder

2) JS where I create the options for the list

function run(input, parameters) {

 var array = ["PDF", "LINKS", "PERSMAP", "SCHUIMKARTON", "INSPIRATIE"];
 var arrayLength = array.length;

 return array;
}

This gives me the following output when already when I run:

3) Added another JS-script Where I return the input (this returns only the selected items)

4) ... This is where I'am stuck. How do I create a folder now for each selected option from within the list?

Complete overview in next atachment

Body:
You can use the chooseFromList command in your JavaScript instead of the "Choose from List" action and another "Run JavaScript" action.

You an use .map() to loop from the selected items.

Here's the script:

function run(input, parameters) {
    thisApp = Application.currentApplication()
    thisApp.includeStandardAdditions = true
    var destFolder = input[0];// the destination folder
    var array = ["PDF", "LINKS", "PERSMAP", "SCHUIMKARTON", "INSPIRATIE"];

    theseNames = thisApp.chooseFromList(array, {withPrompt: 'Which folders to create?', multipleSelectionsAllowed:true});
    if (theseNames == false) {return}; // exit this script because user cancelled

    // (for each selected name then create the folder if this name does not already exists in the destination folder), return path of these sub-folders to the next action
    return theseNames.map(function(thisName) {
        newFolder = destFolder + "/" + thisName + "/";// concatenation of the destination folder and an item in theseNames
        $.NSFileManager.defaultManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder,false,$(), $());
        return newFolder;
    });
 }

Update

To create some subfolders within the new folder, use conditions (if name equal some name), like this:

function run(input, parameters) {
    thisApp = Application.currentApplication()
    thisApp.includeStandardAdditions = true
    var destFolder = input[0];// the destination folder
    var array = ["PDF", "LINKS", "PERSMAP", "SCHUIMKARTON", "INSPIRATIE"];

    theseNames = thisApp.chooseFromList(array, {withPrompt: 'Which folders to create?', multipleSelectionsAllowed:true});
    if (theseNames == false) {return}; // exit this script because user cancelled

    f_m = $.NSFileManager.defaultManager;
    // (for each selected name then create the folder if this name does not already exists in the destination folder), return path of these sub-folders to the next action
    return theseNames.map(function(thisName) {
        newFolder = destFolder + "/" + thisName + "/";// concatenation of the destination folder and an item in theseNames
        f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder,false,$(), $());
        if (thisName == "PDF") { // create folder1 and folder2 in the PDF folder
            f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder + "folder1",false,$(), $());
            f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder + "folder2",false,$(), $());
        }
        if (thisName == "INSPIRATIE") { // create folderX in the INSPIRATIE folder
            f_m.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(newFolder + "folderX",false,$(), $());
        }
        return newFolder;
    });
 }


问:
Addressing localhost from a VirtualBox virtual machine
I have a local test/development server (HTTP, of course), listening to port 8000.

I'm working on Linux, so to test the page on Internet Explorer 6, 7, 8, etc. I run a virtual machine using VirtualBox; I also need to see how it look on Firefox in a windows environment (fonts for instance are different).

In my real machine, I open the website simply using the URL http://localhost:8000, how do I address this localhost from the virtual machine?

Right now my workaround is to use the IP address. Any better ideas?

答:
MacOS

If you want to set up a windows environment with Virtualbox on a mac,
just use the default NAT settings on the adapter,
and in your windows VM, go to hosts file and add the following:

```<code>10.0.2.2       localhost
10.0.2.2       127.0.0.1
</code>```

Differently from the answers above, it's important to include both lines, otherwise it won't work.

Body:
MacOS

If you want to set up a windows environment with Virtualbox on a mac,
just use the default NAT settings on the adapter,
and in your windows VM, go to hosts file and add the following:

10.0.2.2       localhost
10.0.2.2       127.0.0.1

Differently from the answers above, it's important to include both lines, otherwise it won't work.


问:
Converting date to worded date in c#
I have a date in this format "MM/dd/yyyy".

```<code>string date = "03/30/2017"
</code>```

I want to convert this string to this format- Thursday, March 30, 2017.

How can I do this ?

Thank you

答:
You can parse string to DateTime object and then use DateTime.ToLongDateString() to get string in required format:

```<code>var str = "03/30/2017";
var date = DateTime.ParseExact(str, "MM/dd/yyyy", CultureInfo.InvariantCulture);
var formatted = date.ToLongDateString();
</code>```

Note that formatted string is culture sensitive. For en-US culture formatted string will be exactly in format which you want:

```<code>"Thursday, March 30, 2017"
</code>```

You can also specify exact format manually, just as with parsing part:

```<code>var formatted = date.ToString("dddd, MMMM d, yyyy");
</code>```

Check Custom Date and Time Format Strings for reference.

Title: Converting date to worded date in c#

Body:
I have a date in this format "MM/dd/yyyy".

string date = "03/30/2017"

I want to convert this string to this format- Thursday, March 30, 2017.

How can I do this ?

Thank you

Body:
You can parse string to DateTime object and then use DateTime.ToLongDateString() to get string in required format:

var str = "03/30/2017";
var date = DateTime.ParseExact(str, "MM/dd/yyyy", CultureInfo.InvariantCulture);
var formatted = date.ToLongDateString();

Note that formatted string is culture sensitive. For en-US culture formatted string will be exactly in format which you want:

"Thursday, March 30, 2017"

You can also specify exact format manually, just as with parsing part:

var formatted = date.ToString("dddd, MMMM d, yyyy");

Check Custom Date and Time Format Strings for reference.


问:
Get primary key of a deserialized object in Django
I have a list of objects stored in session (to pass the list from one view to another) [okay, there has to be a better way of doing this but this is a question for another time!]

I access the list from the session by doing:

```<code>object_list = request.session.get('object_list', None)
</code>```

But this object_list is actually a serialized django object.

What i need is to now get all the pk of this object_list (to then rebuild a clean queryset...)

I tried this (deserializing then getting pk)

```<code>object_list_id=[]
for obj in serializers.deserialize("json", object_list):
            object_list_id.append(obj.pk)
</code>```

but it doesn't seem to work.. any ideas ?

```<code>'DeserializedObject' object has no attribute 'pk'
</code>```

PS: if i debug the obj from the loop, this is the object type:

```<code>{<DeserializedObject: riskass.Rating(pk=7)>}
</code>```

答:
Got it, it doesn't say anything on this aspect in the documentation !

How to get the pk of a serialized object in django:

```<code># filtered_ratings : list of serialized objects (serialized through django's serializer)

from django.core import serializers

for obj in serializers.deserialize("json", filtered_ratings):
    pk = obj.object.pk
</code>```

Hope this helps someone someday !

Body:
I have a list of objects stored in session (to pass the list from one view to another) [okay, there has to be a better way of doing this but this is a question for another time!]

I access the list from the session by doing:

object_list = request.session.get('object_list', None)

But this object_list is actually a serialized django object.

What i need is to now get all the pk of this object_list (to then rebuild a clean queryset...)

I tried this (deserializing then getting pk)

object_list_id=[]
for obj in serializers.deserialize("json", object_list):
            object_list_id.append(obj.pk)

but it doesn't seem to work.. any ideas ?

'DeserializedObject' object has no attribute 'pk'

PS: if i debug the obj from the loop, this is the object type:

{<DeserializedObject: riskass.Rating(pk=7)>}

Body:
Got it, it doesn't say anything on this aspect in the documentation !

How to get the pk of a serialized object in django:

# filtered_ratings : list of serialized objects (serialized through django's serializer)

from django.core import serializers

for obj in serializers.deserialize("json", filtered_ratings):
    pk = obj.object.pk

Hope this helps someone someday !


问:
Font-Awesome Icons are not centering on page
I have a div that is a page on my site, and I am trying to center these font-awesome icons on it. But for some reason they wont center. I have searched for a solution but none have worked so far.

Click the "about" button to see what I am talking about.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 2.5em;
    padding: .5em;
    border: 3px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover{
    color: #e84d4d;
    cursor: pointer;
}

#home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button id="home">Home</button>
    <button id="fadeContent" class="about">About</button>
    <button id="projects">Projects</button>
    <button id="contact">Contact</button>

```

答:
Try this:

```<code>#bodyContent {
    text-align: center;
}
</code>```

$(function() {

  $('#fadeContent').click(function() {
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
}

#bodyContent {
  display: none;
  position: absolute;
  color: white;
  width: 100%;
  height: 100%;
  background: #454545;
  z-index: 100;
  text-align: center;
}

.fa-times {
  position: absolute;
  top: 0px;
  right: 0px;
  font-size: 3em;
  margin-right: 2%;
  margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
  display: inline-block;
  position: relative;
  text-align: center;
  font-size: 2.5em;
  padding: .5em;
  border: 3px solid white;
  margin-top: 20%;
  margin-left: 1.5%;
  margin-right: 1.5%;
}

.fa-times:hover {
  color: #e84d4d;
  cursor: pointer;
}

#home {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 20%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

.about {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 37%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

#projects {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 54%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

#contact {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 71%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

#home:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

.about:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

#projects:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

#contact:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadein {
  /* Safari and Chrome */
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Home</title>

  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
  <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

  <link rel="stylesheet" type="text/css" href="css/style.css">

  <button id="home">Home</button>
  <button id="fadeContent" class="about">About</button>
  <button id="projects">Projects</button>
  <button id="contact">Contact</button>

```

Body:
I have a div that is a page on my site, and I am trying to center these font-awesome icons on it. But for some reason they wont center. I have searched for a solution but none have worked so far.

Click the "about" button to see what I am talking about.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 2.5em;
    padding: .5em;
    border: 3px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover{
    color: #e84d4d;
    cursor: pointer;
}

#home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button id="home">Home</button>
    <button id="fadeContent" class="about">About</button>
    <button id="projects">Projects</button>
    <button id="contact">Contact</button>

Body:
Try this:

#bodyContent {
    text-align: center;
}

$(function() {

  $('#fadeContent').click(function() {
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
}

#bodyContent {
  display: none;
  position: absolute;
  color: white;
  width: 100%;
  height: 100%;
  background: #454545;
  z-index: 100;
  text-align: center;
}

.fa-times {
  position: absolute;
  top: 0px;
  right: 0px;
  font-size: 3em;
  margin-right: 2%;
  margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
  display: inline-block;
  position: relative;
  text-align: center;
  font-size: 2.5em;
  padding: .5em;
  border: 3px solid white;
  margin-top: 20%;
  margin-left: 1.5%;
  margin-right: 1.5%;
}

.fa-times:hover {
  color: #e84d4d;
  cursor: pointer;
}

#home {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 20%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

.about {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 37%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

#projects {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 54%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

#contact {
  position: absolute;
  width: 16%;
  background-color: transparent;
  border: 2px solid #FFF;
  margin-top: 12%;
  margin-left: 71%;
  height: 3em;
  color: #FFF;
  font-size: 1em;
  cursor: pointer;
  text-transform: uppercase;
  border-radius: 4px;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  /* Firefox */
  -webkit-animation: fadein 2s;
  /* Safari and Chrome */
}

#home:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

.about:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

#projects:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

#contact:hover {
  color: #1dd2e2;
  border: 3px solid #18bdef;
  font-weight: bold;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadein {
  /* Safari and Chrome */
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

<!DOCTYPE html>

<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Home</title>

  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
  <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>

  <button id="home">Home</button>
  <button id="fadeContent" class="about">About</button>
  <button id="projects">Projects</button>
  <button id="contact">Contact</button>

  <div id="bodyContent">
    <i class="fa fa-times" aria-hidden="true"></i>
    <i class="fa fa-twitter" aria-hidden="true"></i>
    <i class="fa fa-github" aria-hidden="true"></i>
    <i class="fa fa-steam" aria-hidden="true"></i>
  </div>

  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
  <script type="text/javascript" src="js/elegant.js"></script>

  <script type="text/javascript" src="js/transition.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
  <script type="text/javascript" src="js/background.js"></script>
</body>

</html>


问:
Reason behind CIFAR dataset fixed image size
What is the reason behind having the size of the CIFAR dataset images fixed at 32X32? Is it just that the size is small enough to enable training to be completed in decent time?</p>

答: They're a subset of "80 million tiny images: a large dataset for non-parametric object and scene recognition (A. Torralba, R. Fergus, W. T. Freeman)". That set is already approximately 300 Gb at its current resolution.</p>


问:
Does the order of fields in C# matter?
This question is inspired by Jon Skeet's answer:
Is there a c# equivalent to c++'s access-modifier regions

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

答: Yeah, it does matter when interfacing with unmanaged code.</p>

OwnerDisplayName: Josh

Title: Does the order of fields in C# matter?

LastEditorDisplayName: Mehrdad Afshari

OwnerDisplayName: Mehrdad Afshari


问:
none latin names of variables in c#
I have named my button object (WinForms) with all hebrew letters and then added click event... and it worked.

Is this some new lang feature I've missed?

```<code>this.כפתור = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// כפתור
//
this.כפתור.Location = new System.Drawing.Point(58, 48);
this.כפתור.Name = "כפתור";
this.כפתור.Size = new System.Drawing.Size(75, 23);
this.כפתור.TabIndex = 0;
this.כפתור.Text = "button1";
this.כפתור.UseVisualStyleBackColor = true;
this.כפתור.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
כפתור.Text = "BLAH BLAH";
}
</code>```

答:
C# (also other popular languages like Java) uses unicode character set for its source code. It is not anything new.

I would suggest you not only stick to English letters but also stick to English names for identifiers. It keeps the program naming consistent with the framework and the source code can be maintained by programmers who don't understand your language.

Title: none latin names of variables in c#

Body:
I have named my button object (WinForms) with all hebrew letters and then added click event... and it worked.

Is this some new lang feature I've missed?

this.כפתור = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// כפתור
//
this.כפתור.Location = new System.Drawing.Point(58, 48);
this.כפתור.Name = "כפתור";
this.כפתור.Size = new System.Drawing.Size(75, 23);
this.כפתור.TabIndex = 0;
this.כפתור.Text = "button1";
this.כפתור.UseVisualStyleBackColor = true;
this.כפתור.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
כפתור.Text = "BLAH BLAH";
}


问:
@SuppressWarnings vs @SuppressLint
Can anyone explain to me the differences between @SuppressWarnings and @SuppressLint? When we should use one over another?

I've read the documentation, but still don't get the differences. Explain using an example/sample code will be much appreciated. Thanks.

答:
There are actually two lints: one belongs to the compiler, so is Java-specific, and one belongs to Google and is Android-specific.

If your warning is about something in Java that isn't specific to Android, it's suppressed with @SuppressWarnings, and if it's Android-specific, it's suppressed with @SuppressLint.

Android Lint Warnings

Lint warnings are listed here: http://tools.android.com/tips/lint-checks

So let's say you have a warning about missing permissions, and the warning description starts off "This check scans through your code and libraries and looks at the APIs being used, and checks this against the set of permissions required to access those APIs."  In the lint warnings page linked above, we find this:

MissingPermission

Summary: Missing Permissions

Priority: 9 / 10
  Severity: Error
  Category: Correctness

This check scans through your code and libraries and looks at the APIs being used, and checks this against the set of permissions required to access those APIs. If the code using those APIs is called at runtime, then the program will crash.

Furthermore, for permissions that are revocable (with targetSdkVersion 23), client code must also be prepared to handle the calls throwing an exception if the user rejects the request for permission at runtime.

So to suppress this, we put this annotation on the code:

```<code>@SuppressLint("MissingPermission")
</code>```

Compiler Warnings

Let's say we find this warning:

"Unchecked cast: 'java.lang.Object' to 'java.lang.Integer' ..."

If you are reading this in hover popup in Android Studio, there is a More... link at the end.  When you click the More... link, the text expands and you find this at the bottom:

"Hint: Pass -Xlint:unchecked to javac to get more details."

This tells you that you would use "unchecked" in the annotation like this:

```<code>@SuppressWarnings("unchecked")
</code>```

For a list of compiler warnings, run javac -X:

```<code>C:\>javac -X
  -Xlint                     Enable recommended warnings
  -Xlint:{all,auxiliaryclass,cast,classfile,deprecation,dep-ann,divzero,empty,fallthrough,finally,options,overloads,overrides,path,processing,rawtypes,serial,static,try,unchecked,varargs,-auxiliaryclass,-cast,-classfile,-deprecation,-dep-ann,-divzero,-empty,-fallthrough,-finally,-options,-overloads,-overrides,-path,-processing,-rawtypes,-serial,-static,-try,-unchecked,-varargs,none} Enable or disable specific warnings
  .
  .
  .
</code>```

Those are the values that you can use in @SuppressWarnings.

Title: @SuppressWarnings vs @SuppressLint

Body:
There are actually two lints: one belongs to the compiler, so is Java-specific, and one belongs to Google and is Android-specific.

If your warning is about something in Java that isn't specific to Android, it's suppressed with @SuppressWarnings, and if it's Android-specific, it's suppressed with @SuppressLint.

Android Lint Warnings

Lint warnings are listed here: http://tools.android.com/tips/lint-checks

So let's say you have a warning about missing permissions, and the warning description starts off "This check scans through your code and libraries and looks at the APIs being used, and checks this against the set of permissions required to access those APIs."  In the lint warnings page linked above, we find this:

MissingPermission

Summary: Missing Permissions

Priority: 9 / 10
  Severity: Error
  Category: Correctness

This check scans through your code and libraries and looks at the APIs being used, and checks this against the set of permissions required to access those APIs. If the code using those APIs is called at runtime, then the program will crash.

Furthermore, for permissions that are revocable (with targetSdkVersion 23), client code must also be prepared to handle the calls throwing an exception if the user rejects the request for permission at runtime.

So to suppress this, we put this annotation on the code:

@SuppressLint("MissingPermission")

Compiler Warnings

Let's say we find this warning:

"Unchecked cast: 'java.lang.Object' to 'java.lang.Integer' ..."

If you are reading this in hover popup in Android Studio, there is a More... link at the end.  When you click the More... link, the text expands and you find this at the bottom:

"Hint: Pass -Xlint:unchecked to javac to get more details."

This tells you that you would use "unchecked" in the annotation like this:

@SuppressWarnings("unchecked")

For a list of compiler warnings, run javac -X:

C:\>javac -X
  -Xlint                     Enable recommended warnings
  -Xlint:{all,auxiliaryclass,cast,classfile,deprecation,dep-ann,divzero,empty,fallthrough,finally,options,overloads,overrides,path,processing,rawtypes,serial,static,try,unchecked,varargs,-auxiliaryclass,-cast,-classfile,-deprecation,-dep-ann,-divzero,-empty,-fallthrough,-finally,-options,-overloads,-overrides,-path,-processing,-rawtypes,-serial,-static,-try,-unchecked,-varargs,none} Enable or disable specific warnings
  .
  .
  .

Those are the values that you can use in @SuppressWarnings.


问:
Attempting to capture multiple groups but only the last group is captured
I am trying to use regex to help to convert the following string into a Dictionary:

```<code>{TheKey|TheValue}{AnotherKey|AnotherValue}
</code>```

Like such:

```<code>["TheKey"] = "TheValue"
["AnotherKey"] = "AnotherValue"
</code>```

To parse the string for the dictionary, I am using the regex expression:

```<code> ^(\{(.+?)\|(.+?)\})*?$
</code>```

But it will only capture the last group of {AnotherKey|AnotherValue}.

How do I get it to capture all of the groups?

I am using C#.

Alternatively, is there a more straightforward way to approach this rather than using Regex?

Code (Properties["PromptedValues"] contains the string to be parsed):

```<code>var regex = Regex.Matches(Properties["PromptedValues"], @"^(\{(.+?)\|(.+?)\})*?$");

foreach(Match match in regex) {

    if(match.Groups.Count == 4) {

        var key = match.Groups[2].Value.ToLower();
        var value = match.Groups[3].Value;

        values.Add(key, new StringPromptedFieldHandler(key, value));
     }

}
</code>```

This is coded to work for the single value, I would be looking to update it once I can get it to capture multiple values.

答:
Alternatively, you can use the Captures property of your groups to get all of the times they matched.

```<code>if (regex.Success)
{
    for (var i = 0; i < regex.Groups[1].Captures.Count; i++)
    {
        var key = regex.Groups[2].Captures[i].Value.ToLower();
        var value = regex.Groups[3].Captures[i].Value;
    }
}
</code>```

This has the advantage of still checking that your entire string was made up of matches. Solutions suggesting you remove the anchors will find things that look like matches in a longer string, but will not fail for you if anything was malformed.

Body:
I am trying to use regex to help to convert the following string into a Dictionary:

{TheKey|TheValue}{AnotherKey|AnotherValue}

Like such:

["TheKey"] = "TheValue"
["AnotherKey"] = "AnotherValue"

To parse the string for the dictionary, I am using the regex expression:

 ^(\{(.+?)\|(.+?)\})*?$

But it will only capture the last group of {AnotherKey|AnotherValue}.

How do I get it to capture all of the groups?

I am using C#.

Alternatively, is there a more straightforward way to approach this rather than using Regex?

Code (Properties["PromptedValues"] contains the string to be parsed):

var regex = Regex.Matches(Properties["PromptedValues"], @"^(\{(.+?)\|(.+?)\})*?$");

foreach(Match match in regex) {

    if(match.Groups.Count == 4) {

        var key = match.Groups[2].Value.ToLower();
        var value = match.Groups[3].Value;

        values.Add(key, new StringPromptedFieldHandler(key, value));
     }

}

This is coded to work for the single value, I would be looking to update it once I can get it to capture multiple values.

Body:
Alternatively, you can use the Captures property of your groups to get all of the times they matched.

if (regex.Success)
{
    for (var i = 0; i < regex.Groups[1].Captures.Count; i++)
    {
        var key = regex.Groups[2].Captures[i].Value.ToLower();
        var value = regex.Groups[3].Captures[i].Value;
    }
}

This has the advantage of still checking that your entire string was made up of matches. Solutions suggesting you remove the anchors will find things that look like matches in a longer string, but will not fail for you if anything was malformed.


问:
Flow declaration files - getting started
Suppose I have this in a file named "math.js".

```<code>function double(n) {
  return n * 2;
}

exports.double = double;
</code>```

If I want to declare the parameter and return type of the "double" function in a separate file named "math.js.flow", what would I put in that file?

答:
.js.flow files are treated just like source files. So for your example you could do something like this:

```<code>function double(n: number): number {
  return n * 2;
}

exports.double = double;
</code>```

Again though, if I knew exactly what you are trying to achieve I might be able to give better advice. Usually you want to just properly annotate your source files.

Body:
Suppose I have this in a file named "math.js".

function double(n) {
  return n * 2;
}

exports.double = double;

If I want to declare the parameter and return type of the "double" function in a separate file named "math.js.flow", what would I put in that file?

Body:
.js.flow files are treated just like source files. So for your example you could do something like this:

function double(n: number): number {
  return n * 2;
}

exports.double = double;

Again though, if I knew exactly what you are trying to achieve I might be able to give better advice. Usually you want to just properly annotate your source files.