问:
Is Excel VBA's Rnd() really this bad?
I need a pseudo random number generator for 2D Monte Carlo simulation that doesn't have the characteristic hyperplanes that you get with simple LCGs. I tested the random number generator Rnd() in Excel 2013 using the following code (takes about 5 secs to run):

```<code>Sub ZoomRNG()

Randomize
For i = 1 To 1000
    Found = False
    Do
        x = Rnd()   ' 2 random numbers between 0.0 and 1.0
        y = Rnd()
        If ((x > 0.5) And (x < 0.51)) Then
            If ((y > 0.5) And (y < 0.51)) Then
                ' Write if both x & y in a narrow range
                Cells(i, 1) = i
                Cells(i, 2) = x
                Cells(i, 3) = y
                Found = True
            End If
        End If
    Loop While (Not Found)
Next i

End Sub
</code>```

Here is a simple plot of x vs y from running the above code

Not only is it not very random-looking, it has more obvious hyperplanes than the infamous RANDU algorithm does in 2D. Basically, am I using the function incorrectly or is the Rnd() function in VBA actually not the least bit usable?

For comparison, here's what I get for the Mersenne Twister MT19937 in C++.

答:
As a balance between speed and goodness, I was thinking of combining them  like

```<code>for...
  z = [rand()] ' good but slow.
  for .. ' just a few
     t = z + rnd()
     t = t - int(t)
     ...
</code>```

Remember that good entropy + bad entropy = better entropy.

That said, only 0.05ms per [rand()].

Title: Is Excel VBA's Rnd() really this bad?

Body:
I need a pseudo random number generator for 2D Monte Carlo simulation that doesn't have the characteristic hyperplanes that you get with simple LCGs. I tested the random number generator Rnd() in Excel 2013 using the following code (takes about 5 secs to run):

Sub ZoomRNG()

Randomize
For i = 1 To 1000
    Found = False
    Do
        x = Rnd()   ' 2 random numbers between 0.0 and 1.0
        y = Rnd()
        If ((x > 0.5) And (x < 0.51)) Then
            If ((y > 0.5) And (y < 0.51)) Then
                ' Write if both x & y in a narrow range
                Cells(i, 1) = i
                Cells(i, 2) = x
                Cells(i, 3) = y
                Found = True
            End If
        End If
    Loop While (Not Found)
Next i

End Sub

Here is a simple plot of x vs y from running the above code

Not only is it not very random-looking, it has more obvious hyperplanes than the infamous RANDU algorithm does in 2D. Basically, am I using the function incorrectly or is the Rnd() function in VBA actually not the least bit usable?

For comparison, here's what I get for the Mersenne Twister MT19937 in C++.

Body:
As a balance between speed and goodness, I was thinking of combining them  like

for...
  z = [rand()] ' good but slow.
  for .. ' just a few
     t = z + rnd()
     t = t - int(t)
     ...

Remember that good entropy + bad entropy = better entropy.

That said, only 0.05ms per [rand()].


来源: stackexchange

问:
awk to extract lines in file that contain matching pattern and variable digit
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa
</code>```

desired output tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa
</code>```

awk

```<code> awk '$2 ~ /^exon [0-9][0-9] sequence$/' file
</code>```

答:
```<code>awk -F'\t' '$2 ~ /exon [1-9][0-9]? sequence/' file
</code>```

Note that the regexp for 1-99 is [1-9][0-9]?, not [0-9][0-9]? as that latter would include 0 (as well as 00, 01, etc.).

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa

desired output tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa

awk

 awk '$2 ~ /^exon [0-9][0-9] sequence$/' file

Body:
awk -F'\t' '$2 ~ /exon [1-9][0-9]? sequence/' file

Note that the regexp for 1-99 is [1-9][0-9]?, not [0-9][0-9]? as that latter would include 0 (as well as 00, 01, etc.).


问:
google image search: search similar images
I want to write a mobile app which takes a picture and searches google images for similar pictures and then displays the results.

However, with google image search I can only search for text strings, and with the search API it seems there's no possibility to search for similar pictures; this feature seems to be available only through the web interface.

Any idea how I can solve this problem?

thanks,
Christoph

答:
The Google Vision API.

https://cloud.google.com/vision/

This is very simple and easy and powerful.

ContentLicense: CC BY-SA 2.5


问:
SQL query for full outer join
I have 3 tables a, b, and c.
Table a contains the ids of the stores, their earning date, and count of sale (flight tickets).

Table b contains the id, sale date, and count of clothing orders.

Table c contains the id, date and total count.

```<code>SQL> select * from a;

STOREID          EARNINGDATE COUNT_FLIGHT_TICKETS
-------------------- ----------- ----------------
store01         14980000           10
store01         14980001           32
store02         14980000          134

SQL> select * from b;

STOREID          EARNINGDATE CLOTHES_SALE_COUNT
-------------------- ----------- ---------------
store01         14980000           6
store02         14980000           6

SQL> select * from c;

STOREID          EARNINGDATE TOTAL_SALE_COUNT
-------------------- ----------- -------------
store01         14980001        32
store01         14980000        16
store02         14980000       134
</code>```

Given above the tables, I have to print all the stores ids, with their date of earning for total sale, flight sale, and clothing sale.

```<code>|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |
</code>```

I have used below query, but failing to get the above.

```<code>select b.storeId , sum(a.COUNT_FLIGHT_TICKETS),
  sum(b.CLOTHES_SALE_COUNT), sum (c.TOTAL_SALE_COUNT)
from a
full outer join b on a.storeId = b.storeId
  and a.EarningDate = b.earningdate
full outer join c on a.storeId = c.storeId
  and a.earningDate = b.earningDate group by a.storeId;
</code>```

This query does not give all the rows and having some bug.

```<code>STOREID          flight clothing        total
------       --------- --------- --------------------
store02           134        6           134
store01           52             12           48
</code>```

Can someone help me to correct this query to get the expected output?

答:
One option would be to take the UNION of the thee tables and then aggregate by store:

```<code>SELECT
    t.STOREID,
    t.EARNINGDATE,
    SUM(t.COUNT_FLIGHT_TICKETS) AS FlightCount,
    SUM(t.CLOTHES_SALE_COUNT)   AS ClothingCount,
    SUM(t.TOTAL_SALE_COUNT)     AS TotalCount
FROM
(
    SELECT
        STOREID,
        EARNINGDATE,
        COUNT_FLIGHT_TICKETS,
        0 AS CLOTHES_SALE_COUNT,
        0 AS TOTAL_SALE_COUNT
    FROM a
    UNION ALL
    SELECT STOREID, EARNINGDATE, 0, CLOTHES_SALE_COUNT, 0
    FROM b
    UNION ALL
    SELECT STOREID, EARNINGDATE, 0, 0, TOTAL_SALE_COUNT
    FROM c
) t
GROUP BY
    t.STOREID,
    t.EARNINGDATE
</code>```

This gets around the join problem you correctly pointed out, which might require a full outer join.  Full outer join in MySQL is a hassle, and in any case it usually should not be necessary with good design.

Demo here:

Rextester

Title: SQL query for full outer join

Body:
I have 3 tables a, b, and c.
Table a contains the ids of the stores, their earning date, and count of sale (flight tickets).

Table b contains the id, sale date, and count of clothing orders.

Table c contains the id, date and total count.

SQL> select * from a;

STOREID          EARNINGDATE COUNT_FLIGHT_TICKETS
-------------------- ----------- ----------------
store01         14980000           10
store01         14980001           32
store02         14980000          134

SQL> select * from b;

STOREID          EARNINGDATE CLOTHES_SALE_COUNT
-------------------- ----------- ---------------
store01         14980000           6
store02         14980000           6

SQL> select * from c;

STOREID          EARNINGDATE TOTAL_SALE_COUNT
-------------------- ----------- -------------
store01         14980001        32
store01         14980000        16
store02         14980000       134

Given above the tables, I have to print all the stores ids, with their date of earning for total sale, flight sale, and clothing sale.

|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |

I have used below query, but failing to get the above.

select b.storeId , sum(a.COUNT_FLIGHT_TICKETS),
  sum(b.CLOTHES_SALE_COUNT), sum (c.TOTAL_SALE_COUNT)
from a
full outer join b on a.storeId = b.storeId
  and a.EarningDate = b.earningdate
full outer join c on a.storeId = c.storeId
  and a.earningDate = b.earningDate group by a.storeId;

This query does not give all the rows and having some bug.

STOREID          flight clothing        total
------       --------- --------- --------------------
store02           134        6           134
store01           52             12           48

Can someone help me to correct this query to get the expected output?

Body:
One option would be to take the UNION of the thee tables and then aggregate by store:

SELECT
    t.STOREID,
    t.EARNINGDATE,
    SUM(t.COUNT_FLIGHT_TICKETS) AS FlightCount,
    SUM(t.CLOTHES_SALE_COUNT)   AS ClothingCount,
    SUM(t.TOTAL_SALE_COUNT)     AS TotalCount
FROM
(
    SELECT
        STOREID,
        EARNINGDATE,
        COUNT_FLIGHT_TICKETS,
        0 AS CLOTHES_SALE_COUNT,
        0 AS TOTAL_SALE_COUNT
    FROM a
    UNION ALL
    SELECT STOREID, EARNINGDATE, 0, CLOTHES_SALE_COUNT, 0
    FROM b
    UNION ALL
    SELECT STOREID, EARNINGDATE, 0, 0, TOTAL_SALE_COUNT
    FROM c
) t
GROUP BY
    t.STOREID,
    t.EARNINGDATE

This gets around the join problem you correctly pointed out, which might require a full outer join.  Full outer join in MySQL is a hassle, and in any case it usually should not be necessary with good design.

Demo here:

Rextester


问:
ImportError: No module named requests
I tried importing requests:

```<code>import requests
</code>```

But I get an error:

ImportError: No module named requests

答:
I have installed python2.7 and python3.6

Open Command Line to ~/.bash_profile  I find that #Setting PATH for Python 3.6 , So
I change the path to PATH="/usr/local/Cellar/python/2.7.13/bin:${PATH}" ,
(please make sure your python2.7's path) ,then save.
It works for me.

ContentLicense: CC BY-SA 4.0

Title: ImportError: No module named requests

Body:
I tried importing requests:

import requests

But I get an error:

ImportError: No module named requests


问:
Unable to share data between functions in Javascript after AJAX call
First I declare an array to store my returned data and a variable to hold the raw JSON data for testing purposes.

```<code><script>
  var XMLdataResult;
  var arrayOfShelters = [];
</code>```

I have successfully called in an array of objects from mySQL using a php page using an AJAX request.  During the AJAX request I am able to display my data via alert() and validate that my data is indeed reaching its destination.

```<code>//RETRIEVE MARKER DATA
    //Import JSON data into a variable.
    var dataXMLhttp = new XMLHttpRequest();
    dataXMLhttp.open("GET", "./js/returnData.php", true);
    dataXMLhttp.send();
    dataXMLhttp.onreadystatechange=function(){

      if(dataXMLhttp.readyState == 4 && dataXMLhttp.status == 200){
      //the response is stored in a variable
        var XMLdataResult = dataXMLhttp.responseText;

        var arrayOfShelters = eval(XMLdataResult);

    //Data successfully output here
        window.alert("Inside AJAX Call" + arrayOfShelters);
    //function called
        setShelters();
      }
    }
</code>```

At this point I have tried to directly output my array and my raw data again with no success.

```<code>        window.alert(arrayOfShelters);
</code>```

Appears to return an empty string.

```<code>        window.alert("setShelters()" + XMLdataResult);
</code>```

returns undefined.

It follows reason that my following functions are also unable to access any data.

```<code>function setShelters(){
    if(arrayOfShelters){
      //the response is stored in a variable
      for(i=0; i < arrayOfShelters.length; i++){
        var myLatLng = new google.maps.LatLng(arrayOfShelters[i].lat, arrayOfShelters[i].lng);
        var shelterOptions = {
          position : myLatLng,
          map : mapCanvas,
          description : arrayOfShelters[i].title,
          icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
        };
      //create marker
        this ['shelter' + i] = new google.maps.Marker(shelterOptions);
      }
      window.alert("setShelters()" + XMLdataResult);
      window.alert("setShelters()" + arrayOfShelters);
    }
  }
</script>
</code>```

I am probably missing something very basic being as Im still a green horn.  Possible conflicts I hypothesize, a previous ajax call further up the script could be causing problems?  My understanding of data flow and functions could be the issue.

Thanks for reading.

答:
Really simple mistake:

When you say var arrayOfShelters = eval(XMLdataResult);, you are creating a new local variable.

You have to say arrayOfShelters = eval(XMLdataResult);

The window.alert("Inside AJAX Call" + arrayOfShelters); is getting the array for the local variable, so that's why it's working there, but not anywhere else.

Body:
First I declare an array to store my returned data and a variable to hold the raw JSON data for testing purposes.

I am probably missing something very basic being as Im still a green horn.  Possible conflicts I hypothesize, a previous ajax call further up the script could be causing problems?  My understanding of data flow and functions could be the issue.

Thanks for reading.


问:
Assigning a value to a variable which is stored in another variable
I am looking for some direction in this code.

What I have is 2 variables:

1) CalcTimeDown - a string variable in a for loop which takes various values which correspond to another string variable for each value in the for loop

Initial value is a string - "CalculationTimeDown".  This gets suffixed by 000, 001, 002 and 003 and 004 giving me CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc

2) CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc are "id" in an XML Layout.  And should get values of 00:00, 00:30, 01:00... etc.

What I am trying to do is:

Loop in the for loop from 0 to 4.

Set values to the variable CalcTimeDown to CalculationTimeDown000,
CalculationTimeDown001, ..... etc.

Load variable CalculationTimeDown000 with "00:00"

Load variable CalculationTimeDown001 with "00:30"

Load variable CalculationTimeDown002 with "01:00"

Load variable CalculationTimeDown003 with "00:30"

Load variable CalculationTimeDown004 with "02:00"

The Bold step above is what I am unable to accomplish - can someone guide me?

```<code>        // Assemble the variable name
        this.CalcTimeDownInitial = "CalculationTimeDown";

        for (int i = 0; i <= 4; i++)
        {
            // Assemble the variable name
            this.CalcTimeDown = this.CalcTimeDownInitial + i.ToString("000");

            var TimeSlotVariable = new StringtoVariable(CalcTimeDown);

            this.iSlot = (i) * 30;
            //

            // Get the time to be pumped
            DateTime TimeSlotValue = DateTime.Now.AddMinutes(this.iSlot);
            //

            // CalcTimeDown contains the variable name where I want to pump the value of TimeSlotValue
            // TimeSlotValue contains 00:00, 00:30, 01:00 etc.
</code>```

//INCORRECT SYNTAX - HELP HERE PLEASE.

```<code>            TimeSlotVariable = TimeSlotValue;
</code>```

Thank you in advance.

Uttam

PS: I could not find an example using Reflection which I could adapt for my use in the example above - hence this posting.

-------Edit added to explain difference------

This edit to explain how my question is different from the possible duplicate:

That question was about Accessing the value - the value is already loaded in that case.

My question is about loading a value - loading the value is what I am trying to accomplish.

Could you please remove the vote down, if my explanation is reasonable?  Thanks!

答:
There's no point in creating variable names dynamically to store values in - if you can even get such a thing to work in C#. I've seen others try to do the same thing, but all they usually need is a collection.

Store each value in a List<T> where T is just the type of your data.

```<code>var timeSlotValues = new List<DateTime>();

for (int i = 0; i <= 4; i++)
{
    timeSlotValues.Add(DateTime.Now.AddMinutes(i * 30));
}
</code>```

I assume you'll eventually use this in a dropdown or something - you can just assign the list to the control as its data source.

And because I'm a LINQ enthusiast, I'll throw this in as an alternative solution:

```<code>var timeSlotValues = Enumerable.Range(0,5)
                               .Select(i => DateTime.Now.AddMinutes(i * 30))
                               .ToList();
</code>```

Body:
I am looking for some direction in this code.

What I have is 2 variables:

1) CalcTimeDown - a string variable in a for loop which takes various values which correspond to another string variable for each value in the for loop

Initial value is a string - "CalculationTimeDown".  This gets suffixed by 000, 001, 002 and 003 and 004 giving me CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc

2) CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc are "id" in an XML Layout.  And should get values of 00:00, 00:30, 01:00... etc.

What I am trying to do is:

Loop in the for loop from 0 to 4.

Set values to the variable CalcTimeDown to CalculationTimeDown000,
CalculationTimeDown001, ..... etc.

Load variable CalculationTimeDown000 with "00:00"

Load variable CalculationTimeDown001 with "00:30"

Load variable CalculationTimeDown002 with "01:00"

Load variable CalculationTimeDown003 with "00:30"

Load variable CalculationTimeDown004 with "02:00"

The Bold step above is what I am unable to accomplish - can someone guide me?

        // Assemble the variable name
        this.CalcTimeDownInitial = "CalculationTimeDown";

        for (int i = 0; i <= 4; i++)
        {
            // Assemble the variable name
            this.CalcTimeDown = this.CalcTimeDownInitial + i.ToString("000");

            var TimeSlotVariable = new StringtoVariable(CalcTimeDown);

            this.iSlot = (i) * 30;
            //

            // Get the time to be pumped
            DateTime TimeSlotValue = DateTime.Now.AddMinutes(this.iSlot);
            //

            // CalcTimeDown contains the variable name where I want to pump the value of TimeSlotValue
            // TimeSlotValue contains 00:00, 00:30, 01:00 etc.

//INCORRECT SYNTAX - HELP HERE PLEASE.

            TimeSlotVariable = TimeSlotValue;

Thank you in advance.

Uttam

PS: I could not find an example using Reflection which I could adapt for my use in the example above - hence this posting.

-------Edit added to explain difference------

This edit to explain how my question is different from the possible duplicate:

That question was about Accessing the value - the value is already loaded in that case.

My question is about loading a value - loading the value is what I am trying to accomplish.

Could you please remove the vote down, if my explanation is reasonable?  Thanks!

Body:
There's no point in creating variable names dynamically to store values in - if you can even get such a thing to work in C#. I've seen others try to do the same thing, but all they usually need is a collection.

Store each value in a List<T> where T is just the type of your data.

var timeSlotValues = new List<DateTime>();

for (int i = 0; i <= 4; i++)
{
    timeSlotValues.Add(DateTime.Now.AddMinutes(i * 30));
}

I assume you'll eventually use this in a dropdown or something - you can just assign the list to the control as its data source.

And because I'm a LINQ enthusiast, I'll throw this in as an alternative solution:

var timeSlotValues = Enumerable.Range(0,5)
                               .Select(i => DateTime.Now.AddMinutes(i * 30))
                               .ToList();


问:
Regenerate Web API key of Google Firebase
How do I regnerate my Web API key for Google Firebase? I deleted the autogenerated one due to misguided reasons.

If it's not deletable, do I need to create a just a new App or a new Project?

答:
Go to your API account, select a project at the "Select a project" dropdown in the upper left, and "Create Credentials" of the API Key variety.

Firebase will link to your key automatically.


问:
How to post on Facebook wall without opening Dialog?
I am trying to integrate facebook in my app. I had done code for login and trying to post on my wall but I don't need the facebook dialog. I want my own. after googling I found some code but its not working. It is not giving any error but not posting any thing...

Here I am using is :

```<code>NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               @"Facebook developer Test Message",@"message",
                               @"Test it!",@"name",
                               nil];
 Facebook *fb = [[Facebook alloc] init];
    [fb requestWithGraphPath:@"me/feed"   // or use page ID instead of 'me'
                      andParams:params
                  andHttpMethod:@"POST"
                    andDelegate:self];
</code>```

Its not working..

```<code> FBStreamDialog *dialog = [[[FBStreamDialog alloc] init]
     autorelease];
 dialog.userMessagePrompt = @"Enter your message:";
 dialog.attachment = [NSString
   stringWithFormat:@"{\"name\":\"Facebook Connect for iPhone\",\"href\":\"http://developers.facebook.com/connect.phptab=iphone\",\"caption\":\"Caption\", \"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}"];

 [dialog show];
</code>```

This opens a dialog and ask me to type message and when I clicks It post the Data on my wall.

I Had refferes following links for this

http://forum.developers.facebook.net/viewtopic.php?id=79466

Please tell me where I am doing mistake.

Thanks

答:
hi i think you can do this and can solve your problem</p>

```<code>NSString *str=@"Your String to post";

NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   str,@"message",
                                   @"Test it!",@"name",
                                   nil];
Facebook *fb = [[Facebook alloc] init];
    [fb requestWithGraphPath:@"me/feed"   // or use page ID instead of 'me'
                          andParams:params
                      andHttpMethod:@"POST"
                        andDelegate:self];
</code>```

Body:
I am trying to integrate facebook in my app. I had done code for login and trying to post on my wall but I don't need the facebook dialog. I want my own. after googling I found some code but its not working. It is not giving any error but not posting any thing...

Here I am using is :

NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               @"Facebook developer Test Message",@"message",
                               @"Test it!",@"name",
                               nil];
 Facebook *fb = [[Facebook alloc] init];
    [fb requestWithGraphPath:@"me/feed"   // or use page ID instead of 'me'
                      andParams:params
                  andHttpMethod:@"POST"
                    andDelegate:self];

Its not working..

 FBStreamDialog *dialog = [[[FBStreamDialog alloc] init]
     autorelease];
 dialog.userMessagePrompt = @"Enter your message:";
 dialog.attachment = [NSString
   stringWithFormat:@"{\"name\":\"Facebook Connect for iPhone\",\"href\":\"http://developers.facebook.com/connect.phptab=iphone\",\"caption\":\"Caption\", \"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}"];

 [dialog show];

This opens a dialog and ask me to type message and when I clicks It post the Data on my wall.

I Had refferes following links for this

http://forum.developers.facebook.net/viewtopic.php?id=79466

Please tell me where I am doing mistake.

Thanks

Body:
hi i think you can do this and can solve your problem

NSString *str=@"Your String to post";

NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   str,@"message",
                                   @"Test it!",@"name",
                                   nil];
Facebook *fb = [[Facebook alloc] init];
    [fb requestWithGraphPath:@"me/feed"   // or use page ID instead of 'me'
                          andParams:params
                      andHttpMethod:@"POST"
                        andDelegate:self];


问:
Foreign Key with wordpress
I have a table (multisite network) where I use blog_id as one of the columns which is also needed on some of my custom php functions. Until now, I haven't used FK which should be appropriate for my tables.

So, can I FK to wordpress wp_blogs table? if yes, if ever I delete that blog will it also delete the entries on my other tables that references wp_blogs?

答:
```<code>CREATE TABLE wp_blogs (blog_id INT NOT NULL...)
    FOREIGN KEY (blog_id)
    REFERENCES wp_options(blog_id)
    ON DELETE CASCADE;
</code>```

If you created a table like above then every time when blog_id will remove from wp_options then all rows from wp_blogs will remove too.

When you remove rows from wp_blogs then no rows won't remove from wp_options

Read about ON DELETE CASCADE in MySQL documentation.

Title: Foreign Key with wordpress

Body:
CREATE TABLE wp_blogs (blog_id INT NOT NULL...)
    FOREIGN KEY (blog_id)
    REFERENCES wp_options(blog_id)
    ON DELETE CASCADE;

If you created a table like above then every time when blog_id will remove from wp_options then all rows from wp_blogs will remove too.

When you remove rows from wp_blogs then no rows won't remove from wp_options

Read about ON DELETE CASCADE in MySQL documentation.


问:
Variable undefined inside the self-invoking function
I wonder why its undefined if I declare like so:

```<code>var mainBtn = $('.main-button'),
    cloneFund = (function(mainBtn) {
        console.log(mainBtn); // undefined
        return arguments.callee;
    })();
</code>```

or even:

```<code>var btn = $('.main-button'),
    cloneFund = (function(btn) {
        console.log(btn); // undefined
        return arguments.callee;
    })();
</code>```

答:
You have to pass mainBtn to function.

var mainBtn = $('.main-button'),
    cloneFund = (function(mainBtn) {
        console.log(mainBtn); // available
        return arguments.callee;
    })(mainBtn); // here you have to pass```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="main-button">Main Button</button></code>```

Body:
I wonder why its undefined if I declare like so:

var mainBtn = $('.main-button'),
    cloneFund = (function(mainBtn) {
        console.log(mainBtn); // undefined
        return arguments.callee;
    })();

or even:

var btn = $('.main-button'),
    cloneFund = (function(btn) {
        console.log(btn); // undefined
        return arguments.callee;
    })();

Body:
You have to pass mainBtn to function.

var mainBtn = $('.main-button'),
    cloneFund = (function(mainBtn) {
        console.log(mainBtn); // available
        return arguments.callee;
    })(mainBtn); // here you have to pass

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="main-button">Main Button</button>


问:
rails devise after_sign_up_path_for undefined method `subdomain'
I am attempting to redirect user after successfully signing up to their respective subdomain. I have input the following code within the application_controller.

application_controller.rb

```<code>protected

def after_sign_in_path_for(resource)
  redirect_to root_url(subdomain: @users.subdomain)
end
</code>```

I am receiving the following error

```<code>NoMethodError in Devise::SessionsController#create
undefined method `subdomain' for nil:NilClass

Extracted source (around line #10):

def after_sign_up_path_for(subdomain)
  redirect_to root_url(subdomain: @users.subdomain)
end
</code>```

答:
NoMethodError in Devise::SessionsController#create undefined method
  `subdomain' for nil:NilClass

@users is nil, so Rails spits out with that error. As you are using Devise, the Devise model(User) instance can be accessed with resource.

```<code>def after_sign_in_path_for(resource)
  redirect_to root_url(subdomain: resource.subdomain)
end
</code>```

You can also use current_user

```<code>def after_sign_in_path_for(resource)
  redirect_to root_url(subdomain: current_user.subdomain)
end
</code>```

Body:
I am attempting to redirect user after successfully signing up to their respective subdomain. I have input the following code within the application_controller.

application_controller.rb

protected

def after_sign_in_path_for(resource)
  redirect_to root_url(subdomain: @users.subdomain)
end

I am receiving the following error

NoMethodError in Devise::SessionsController#create
undefined method `subdomain' for nil:NilClass

Extracted source (around line #10):

def after_sign_up_path_for(subdomain)
  redirect_to root_url(subdomain: @users.subdomain)
end

Body:
NoMethodError in Devise::SessionsController#create undefined method
  `subdomain' for nil:NilClass

@users is nil, so Rails spits out with that error. As you are using Devise, the Devise model(User) instance can be accessed with resource.

def after_sign_in_path_for(resource)
  redirect_to root_url(subdomain: resource.subdomain)
end

You can also use current_user

def after_sign_in_path_for(resource)
  redirect_to root_url(subdomain: current_user.subdomain)
end


问:
Issue with :last-child on a list item Menu
Here's my updated JSFIDDLE: https://jsfiddle.net/axosonns/2/

HTML:

```<code><ul class="whatever">
  <li><a href="#">Menu1</a></li>
  <li><a href="#">Menu2</a></li>
  <li><a href="#">Menu3</a></li>
  <li><a href="#">Menu4</a></li>
</ul>
</code>```

CSS:

```<code>.whatever li {
  display: inline-block;
}
.whatever li>a {
  background: grey;
  padding: 10px 15px;
}
.whatever li>a:last-child {
  padding: 10px 0 10px 15px;
  background-color: red;
}
</code>```

The last-child css code isn't working. I want only the last menu to have padding: 0px;

What am I doing wrong?

答:
you selected last element of a in each li ,
you have to select last li element and target a in that

.whatever li>a:last-child   to this .whatever li:last-child a

.whatever li {
  display: inline-block;
}
.whatever li>a {
  background: grey;
  padding: 10px 15px;
}
.whatever li:last-child a{
  padding: 10px 15px 10px 15px;
  /* padding: 0px; */
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="whatever">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul></code>```

Body:
Here's my updated JSFIDDLE: https://jsfiddle.net/axosonns/2/

HTML:

Menu1

Menu2

Menu3

Menu4

CSS:

.whatever li {
  display: inline-block;
}
.whatever li>a {
  background: grey;
  padding: 10px 15px;
}
.whatever li>a:last-child {
  padding: 10px 0 10px 15px;
  background-color: red;
}

The last-child css code isn't working. I want only the last menu to have padding: 0px;

What am I doing wrong?

Body:
you selected last element of a in each li ,
you have to select last li element and target a in that

.whatever li>a:last-child   to this .whatever li:last-child a

.whatever li {
  display: inline-block;
}
.whatever li>a {
  background: grey;
  padding: 10px 15px;
}
.whatever li:last-child a{
  padding: 10px 15px 10px 15px;
  /* padding: 0px; */
  background-color: red;
}

<ul class="whatever">
  <li><a href="#">Menu1</a></li>
  <li><a href="#">Menu2</a></li>
  <li><a href="#">Menu3</a></li>
  <li><a href="#">Menu4</a></li>
</ul>


问:
How to use links in php mvc?
First problem:

Main url: site-test

1. I clicked on the link tasks -> url: site-test/tasks

2. i click next link next page (Where "tasks" - contoller, "page" - action, "2" - action value) -> url: site-test/tasks/page/2

3. i pressed again tasks and url -> site-test/tasks/page/tasks instead site-test/tasks/ what i need.

tasks is located in template view.

Second problem:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

My route:

```<code>static function start()
    {
        $controller_name = 'add_task';
        $action_name = 'index';

        $routes = explode('/', $_SERVER['REQUEST_URI']);

        if ( !empty($routes[1]) )
        {
            $controller_name = $routes[1];
        }

        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }

        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;

        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }

        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }

        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
            if ( !empty($routes[3]) )
            {
                $controller->$action($routes[3]);
            }
            else{
                $controller->$action();
            }
        }

    }
</code>```

My controller:

```<code>class Controller_tasks extends Controller
{
    function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

    function action_index()
    {
        $data = $this->model->get_data_from_server();
        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }

    function action_page($page = 1)
    {
        var_dump($page);
        $data = $this->model->get_data_from_server($page);

        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }
}
</code>```

Thx for any help, coz im rly confused.

答:
First question:

The first problem happens because you are loading and rendering the view files IN the action context/scope of the controller. That's why your url in the point 3. is "incorrect", e.g. site-test/tasks/page/tasks, e.g '///`. So, other said, because you are actually seeing the rendered html content from inside the controller folder, where it was the view file rendered.

In order to resolve this you have to options:

Option 1) Use absolute paths in all the anchors in your view/template files, like for example:

```<code><a href="http://site-test/tasks/">tasks</a>
<a href="http://site-test/tasks/page/2">next page</a>
</code>```

Here you can of course use a variable in your view/template files instead, like:

```<code><a href="<?php echo $host; ?>/tasks/">tasks</a>
<a href="<?php echo $host; ?>/tasks/page/2">next page</a>
</code>```

I showed you just pure php code, but you can use syntaxes provided by a diversity of template engines, if you decide to use one, one then PHP engine.

Option 2) Use relative paths in all the anchors in your view/template files, like for example:

```<code><a href="/tasks/">tasks</a>
<a href="/tasks/page/2">next page</a>
</code>```

The key is of course the slash (/) at the beginning of each anchor's href attribute. It ensures that all the links are "joined" to the host http://site-test of your MVC website.

Personally I use the second option in my own MVC framework and it works smooth and is... pretty.

Second question:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

Well, here is the need of a discussion:

When url is site-test, then the default action of the default controller is called, e.g. Controller_add_task::action_index(). You didn't show the code for that controller, so I can't say nothing about from where and how are the asset files (css, images, js) loaded in the views.

Same goes for the url site-test/tasks/page/...: you showed the code for the controller, but I can't say nothing about how and where are the asset files (css, images, js) loaded in the views. Are the asset paths loaded from inside the Controller (parent class) methods? Are they written - as normal - in the view/template files (using

Title: How to use links in php mvc?

Body:
First problem:

Main url: site-test

1. I clicked on the link tasks -> url: site-test/tasks

2. i click next link next page (Where "tasks" - contoller, "page" - action, "2" - action value) -> url: site-test/tasks/page/2

3. i pressed again tasks and url -> site-test/tasks/page/tasks instead site-test/tasks/ what i need.

tasks is located in template view.

Second problem:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

My route:

static function start()
    {
        $controller_name = 'add_task';
        $action_name = 'index';

        $routes = explode('/', $_SERVER['REQUEST_URI']);

        if ( !empty($routes[1]) )
        {
            $controller_name = $routes[1];
        }

        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }

        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;

        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }

        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }

        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
            if ( !empty($routes[3]) )
            {
                $controller->$action($routes[3]);
            }
            else{
                $controller->$action();
            }
        }

    }

My controller:

class Controller_tasks extends Controller
{
    function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

    function action_index()
    {
        $data = $this->model->get_data_from_server();
        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }

    function action_page($page = 1)
    {
        var_dump($page);
        $data = $this->model->get_data_from_server($page);

        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }
}

Thx for any help, coz im rly confused.

Body:
First question:

The first problem happens because you are loading and rendering the view files IN the action context/scope of the controller. That's why your url in the point 3. is "incorrect", e.g. site-test/tasks/page/tasks, e.g '///`. So, other said, because you are actually seeing the rendered html content from inside the controller folder, where it was the view file rendered.

In order to resolve this you have to options:

Option 1) Use absolute paths in all the anchors in your view/template files, like for example:

<a href="http://site-test/tasks/">tasks</a>
<a href="http://site-test/tasks/page/2">next page</a>

Here you can of course use a variable in your view/template files instead, like:

<a href="<?php echo $host; ?>/tasks/">tasks</a>
<a href="<?php echo $host; ?>/tasks/page/2">next page</a>

I showed you just pure php code, but you can use syntaxes provided by a diversity of template engines, if you decide to use one, one then PHP engine.

Option 2) Use relative paths in all the anchors in your view/template files, like for example:

<a href="/tasks/">tasks</a>
<a href="/tasks/page/2">next page</a>

The key is of course the slash (/) at the beginning of each anchor's href attribute. It ensures that all the links are "joined" to the host http://site-test of your MVC website.

Personally I use the second option in my own MVC framework and it works smooth and is... pretty.

Second question:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

Well, here is the need of a discussion:

When url is site-test, then the default action of the default controller is called, e.g. Controller_add_task::action_index(). You didn't show the code for that controller, so I can't say nothing about from where and how are the asset files (css, images, js) loaded in the views.

Same goes for the url site-test/tasks/page/...: you showed the code for the controller, but I can't say nothing about how and where are the asset files (css, images, js) loaded in the views. Are the asset paths loaded from inside the Controller (parent class) methods? Are they written - as normal - in the view/template files (using <script src=...>, <link href=...>, <img src=...>)? Are they loaded from inside the View::generate?

In principle, they can be passed to the view/template files as variables, or they can be written - as normal - in the view/template files.

The context/scope theory of the first question applies here too. And the key here is the same as in the first question: the asset paths should be passed/written as absolute paths or relative paths as shown above in the options 1) and 2).

Recommendations:

Note: Seeing that you want to learn clean MVC, I thought you would allow me to give you some tips:

*) Don't use any static classes/functions, singletons or so called service locators. Trust me, you don't need them at all if you are writing a clean, good testable MVC.

*) Use a dependency injection container like Auryn, which you will implement only on the entry point of your app, e.g. bootstrap.php or index.php. The next point tells you why.

*) Inject your dependencies, don't create them in the places where they are needed. So not like this:

function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

but like this:

function __construct(Model_tasks $model, View $view)
    {
        $this->model = $model;
        $this->view = $view;
    }

Read:

The Clean Code Talks - Don't Look For Things!

PHPNW15: James Mallison - Dependency Injection and Dependency Inversion in PHP

*) Use namespaces! Read PSR-4: Autoloader (yes, it's correct).

*) Read all the first 8 recommendations in PHP Standards Recommendations. They are very important if you want to correctly learn how to develop a PHP MVC.

*) Learn the five SOLID principles in OOP (just search for "solid principles" in web).

*) Use a corresponding view class for each controller class (1:1). For example: if you have TasksController, then also create a class TasksView. And what you are using there as view files - tasks_view.php, template_view.php, etc - are actually template files. And you should implement a Template class, which is to be injected in the corresponding view class. The template class is actually responsible for rendering/loading the template files. The view class should be responsible to output the rendered content (or to pass it to a Response class to be outputed).

Read: Understanding MVC Views in PHP

*) Don't use names like Controller_tasks for the class names. Use the syntax like this - I forgot the name: TasksController, TasksModel, TasksView.

*) Don't use names like action_index for the class methods or members. Use the camelCase syntax. And don't use action in the controller methods, because you already know that. So write the methods just like this: index(), page(), listBooks. If you use ajax you can name them like ajaxGetUsers(), etc. Just make sure that your routing system make the correct syntax-mapping between the controller/action names in url and the actual controller/action names.

Resources:

How should a model be structured in MVC?

Design Patterns: How to create database object/connection only when needed?

MVC In PHP series

Model-View-Confusion Series

Good luck.


问:
VueJS - Props are not updated in child component by changes in parent
Props are not updated when I change them in parent component

Parent component:

I have controlData value as defaul value for child component prop control which is equal 2 and I can see that value when I run my app first time

```<code>data() {
  return {
    controlData: 2
  }
}
</code>```

In ready() I need to load data from back-end and to set that value to child component prop control equal to the data from back-end.

But lets say that now I just want to change control (value in child) when parent component is ready. So I made this in parent component:

```<code>ready() {
  this.controlData = 55;
}
</code>```

Then I use v-bind to send that value in child when controlData is changed

```<code><child-component :control="controlData"></child-componenet>
</code>```

Child component:

I have this in my child component

```<code>    export default Bar.extend({
    props: ["control"],
    ready() {
      console.log(this.control); // I see only default value "2" not "55" - but I expect to see "55" because I changed that value in ready() of parent
    }
})
</code>```

I added also watch: {} to look for changes of props but I can't see the changes

```<code>watch: {
  control() {
    console.log("Control is changed"); // I don't see this message when I change controlData value in parent and then by v-bind:control="controlData" i send that data in child component
  }
}
</code>```

答:
The code you have posted should update the child prop if correctly implemented.

One thing to note, the child's ready() hook will be executed BEFORE the parent ready() hook. So you should see the console log the following:

```<code>2
Control is changed
</code>```

This is working for me using Vue 1.0.28:

https://codepen.io/camaulay/pen/wejpPa?editors=1011

JS:

```<code>var child = Vue.extend({
  template: '<div>Child data: {{ control }}</div>',
  props: ['control'],
  ready () {
      console.log(this.control);
  },
  watch: {
    control () {
      console.log("Control is changed")
      console.log(this.control)
    }
  }
})

var app = new Vue({
  el: '#app',
  components: {
    'child': child
  },
  data () {
    return {
      controlData: 2
    }
  },
  ready () {
    this.controlData = 55
  }
})
</code>```

HTML:

```<code><div id="app">
  <child :control="controlData"></child>
  <button @click="controlData++">Increment parent data</button>
</div>
</code>```

Body:
Props are not updated when I change them in parent component

Parent component:

I have controlData value as defaul value for child component prop control which is equal 2 and I can see that value when I run my app first time

data() {
  return {
    controlData: 2
  }
}

In ready() I need to load data from back-end and to set that value to child component prop control equal to the data from back-end.

But lets say that now I just want to change control (value in child) when parent component is ready. So I made this in parent component:

ready() {
  this.controlData = 55;
}

Then I use v-bind to send that value in child when controlData is changed

<child-component :control="controlData"></child-componenet>

Child component:

I have this in my child component

    export default Bar.extend({
    props: ["control"],
    ready() {
      console.log(this.control); // I see only default value "2" not "55" - but I expect to see "55" because I changed that value in ready() of parent
    }
})

I added also watch: {} to look for changes of props but I can't see the changes

watch: {
  control() {
    console.log("Control is changed"); // I don't see this message when I change controlData value in parent and then by v-bind:control="controlData" i send that data in child component
  }
}

Body:
The code you have posted should update the child prop if correctly implemented.

One thing to note, the child's ready() hook will be executed BEFORE the parent ready() hook. So you should see the console log the following:

2
Control is changed

This is working for me using Vue 1.0.28:

https://codepen.io/camaulay/pen/wejpPa?editors=1011

JS:

var child = Vue.extend({
  template: '<div>Child data: {{ control }}</div>',
  props: ['control'],
  ready () {
      console.log(this.control);
  },
  watch: {
    control () {
      console.log("Control is changed")
      console.log(this.control)
    }
  }
})

var app = new Vue({
  el: '#app',
  components: {
    'child': child
  },
  data () {
    return {
      controlData: 2
    }
  },
  ready () {
    this.controlData = 55
  }
})

HTML:

<div id="app">
  <child :control="controlData"></child>
  <button @click="controlData++">Increment parent data</button>
</div>


答:
Try using a dictionary to hold the key,value pairs like this:</p>

```<code>        string varname = "CalculationTimeDown";

        Dictionary<string, DateTime> values = new Dictionary<string, DateTime>();
        for (int i = 0; i <= 4; i++)
        {
            // Assemble the variable name
            values.Add(varname + i.ToString("000"), DateTime.Now.AddMinutes((i) * 30));

        }
</code>```

Title: Assigning a value to a variable which is stored in another variable

Body:
Try using a dictionary to hold the key,value pairs like this:

        string varname = "CalculationTimeDown";

        Dictionary<string, DateTime> values = new Dictionary<string, DateTime>();
        for (int i = 0; i <= 4; i++)
        {
            // Assemble the variable name
            values.Add(varname + i.ToString("000"), DateTime.Now.AddMinutes((i) * 30));

        }


问:
Linq outer join and specify DefaultIfEmpty values - anonymous type does not contain a definition for defaultifempty .. requires a receiver of type
I have a linq query that performs 2 outer joins like this:

```<code>            var finalDataSet = from a in alpha
                                join b in beta on a.field1 equals b.field1
                                // *outer join*
                                join c in charlie on a.field2 equals c.field2 into c_2
                                from c2 in c_2.DefaultIfEmpty(new MyObject1 { MyProperty1 = (string) String.Empty, MyProperty2 = (DateTime?) null })
                                join d in delta on a.field3 equals d.field3
                                // *outer join*
                                join e in echo on a.field4 equals e.field4 into e_2
                                from e2 in e_2.DefaultIfEmpty(new MyObject2 { MyProperty3 = String.Empty, MyProperty4 = String.Empty })
                                orderby a.field1
                                select new
                                {
                                    FinalProperty1 = a.field1,
                                    FinalProperty2 = a.field2,
                                    etc ...
</code>```

.. and my type definitions for the types I'm newing up for the 'DefaultIfEmpty'  values:

MyObject1:

```<code>public class MyObject1
{
    public string MyProperty1 { get; set; }
    public DateTime? MyProperty2 { get; set; }
}
</code>```

MyObject2:

```<code>public class MyObject2
{
    public string MyProperty3 { get; set; }
    public string MyProperty4 { get; set; }
}
</code>```

The 2nd outer join (to 'echo') is fine, but for the 1st, I get the compiler error when I reference c_2 on this line:

```<code>from c2 in **c_2**  --> compiler doesn't like the reference to c_2
</code>```

I get this error:

```<code>IEnumerable <<anonymous type: string Property1, DateTime? Property2 >> does not contain a definition for 'DefaultIfEmpty' and the best extension method overload 'Queryable.DefaultIfEmpty' <MyObject1>(IQueryable<MyObject1>, MyObject1)' requires a receive of type 'IQueryable<LatestExpiredSchedule>'
</code>```

Why am I getting this error for my 1st join and not the 2nd? If I change my 1st join to:

```<code>from e2 in e_2.DefaultIfEmpty()
</code>```

I don't get an error, but I need to explicitly specify defaults. What does the error message really mean, and how do I need to specify the defaults for my 1st left outer join?

答: Found the answer - my 'charlie' in the above query was the result of a linq query and so return anonymous types. I needed to construct an object of MyObject1 for each of the results returned by that query.</p>

Body:
I have a linq query that performs 2 outer joins like this:

            var finalDataSet = from a in alpha
                                join b in beta on a.field1 equals b.field1
                                // *outer join*
                                join c in charlie on a.field2 equals c.field2 into c_2
                                from c2 in c_2.DefaultIfEmpty(new MyObject1 { MyProperty1 = (string) String.Empty, MyProperty2 = (DateTime?) null })
                                join d in delta on a.field3 equals d.field3
                                // *outer join*
                                join e in echo on a.field4 equals e.field4 into e_2
                                from e2 in e_2.DefaultIfEmpty(new MyObject2 { MyProperty3 = String.Empty, MyProperty4 = String.Empty })
                                orderby a.field1
                                select new
                                {
                                    FinalProperty1 = a.field1,
                                    FinalProperty2 = a.field2,
                                    etc ...

.. and my type definitions for the types I'm newing up for the 'DefaultIfEmpty'  values:

MyObject1:

public class MyObject1
{
    public string MyProperty1 { get; set; }
    public DateTime? MyProperty2 { get; set; }
}

MyObject2:

public class MyObject2
{
    public string MyProperty3 { get; set; }
    public string MyProperty4 { get; set; }
}

The 2nd outer join (to 'echo') is fine, but for the 1st, I get the compiler error when I reference c_2 on this line:

from c2 in **c_2**  --> compiler doesn't like the reference to c_2

I get this error:

IEnumerable <<anonymous type: string Property1, DateTime? Property2 >> does not contain a definition for 'DefaultIfEmpty' and the best extension method overload 'Queryable.DefaultIfEmpty' <MyObject1>(IQueryable<MyObject1>, MyObject1)' requires a receive of type 'IQueryable<LatestExpiredSchedule>'

Why am I getting this error for my 1st join and not the 2nd? If I change my 1st join to:

from e2 in e_2.DefaultIfEmpty()

I don't get an error, but I need to explicitly specify defaults. What does the error message really mean, and how do I need to specify the defaults for my 1st left outer join?


问:
IOCTL_DISK_GET_STORAGEID WinCE vs Linux difference?
I'm trying to match a function from a WinCE program in Linux.

The function uses a WinCE call zu output the SD cards identifier.

but the problem is that the WINCE function outputs

0280XXXXXX as as serial number - whereas I get the same number on linux in /sys/block/mmcblk0/device/serial but the first byte (02) is missing (output is 80XXXXXX)

Does anyone that knows wince good know where the IOCTL_DISK_GET_STORAGEID function takes the first byte from?

答:
The WinCE output does look a bit odd for an SD card.

Assuming your WinCE device is using the standard Microsoft SD card driver, the serial number is taken from the card's CID (i.e. it is only 32 bits), and is formatted as %08X when the STORAGE_IDENTIFICATION struct is generated by the driver.

So unless there's an error in the program you're using to obtain the serial number, my guess would be that the WinCE device uses a custom SD card driver (e.g. one that combines the manufacturer ID and serial number, or one that simply has a bug).


问:
R upgrade to 3.4 installing packages
I had R working perfectly until I decided to upgrade to 3.4. Now I am unable to install packages.

while installing packages I get an error

```<code>Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n)
</code>```

If I hit yes I get

```<code>Would you like to create a personal library
NA
to install packages into?  (y/n)
</code>```

at which point it proceeds give this error

```<code>Error in install.packages("quantstrat") : unable to create ‘NA’
</code>```

答:
I don't know why R 3.4.1 changes the library path. To change it back, simply edit /etc/R/Renviron:

```<code>$ sudo gedit /etc/R/Renviron
</code>```

Comment-out R_LIBS_SITE=... then uncomment R_LIBS_USER=...

```<code># edd Jun 2017  Comment-out R_LIBS_USER
R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}

# edd Apr 2003  Allow local install in /usr/local, also add a directory for
#               Debian packaged CRAN packages, and finally the default dir
# edd Jul 2007  Now use R_LIBS_SITE, not R_LIBS
#R_LIBS_SITE=${R_LIBS_SITE-'/usr/local/lib/R/site-library:/usr/lib/R/site-library:/usr/lib/R/library'}
</code>```

Title: R upgrade to 3.4 installing packages

Body:
I had R working perfectly until I decided to upgrade to 3.4. Now I am unable to install packages.

while installing packages I get an error

Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n)

If I hit yes I get

Would you like to create a personal library
NA
to install packages into?  (y/n)

at which point it proceeds give this error

Error in install.packages("quantstrat") : unable to create ‘NA’

Body:
I don't know why R 3.4.1 changes the library path. To change it back, simply edit /etc/R/Renviron:

$ sudo gedit /etc/R/Renviron

Comment-out R_LIBS_SITE=... then uncomment R_LIBS_USER=...

# edd Jun 2017  Comment-out R_LIBS_USER
R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}

# edd Apr 2003  Allow local install in /usr/local, also add a directory for
#               Debian packaged CRAN packages, and finally the default dir
# edd Jul 2007  Now use R_LIBS_SITE, not R_LIBS
#R_LIBS_SITE=${R_LIBS_SITE-'/usr/local/lib/R/site-library:/usr/lib/R/site-library:/usr/lib/R/library'}


答:
The issue is that inside your ajax response you are doing:
var arrayOfShelters, but you already declared your arrayOfShelters variable before, so you don't need to declare the "var" again.

By doing that you're declaring a new variable inside your ajax response. and the same with happen with XMLdataResult.

Title: Unable to share data between functions in Javascript after AJAX call

Body:
First I declare an array to store my returned data and a variable to hold the raw JSON data for testing purposes.

I am probably missing something very basic being as Im still a green horn.  Possible conflicts I hypothesize, a previous ajax call further up the script could be causing problems?  My understanding of data flow and functions could be the issue.

Thanks for reading.


问:
ImageView in Dialogue Box -Xamarin
I am trying to save an image into my firebase database. I save my data using dialog box. What i want to now is that, i want to add images by clicking a button, then select the pic from my gallery. Now the i would want the the path of the photo to show on the dialogue and not the image itself. Save the path to firebase and retrieve the image itself into an imageview in another activity.

Is there any sample code to this please?

答:
i want to add images by clicking a button, then select the pic from my gallery.

Use Chooser to select an image from the gallery:

```<code>private void BtnClick_Click(object sender, System.EventArgs e)
{
    Intent intent = new Intent();
    intent.SetType("image/*");
    intent.SetAction(Intent.ActionGetContent);
    StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), 0);
}
</code>```

the i would want the the path of the photo to show on the dialogue and not the image itself. Save the path to firebase and retrieve the image itself into an imageview in another activity.

By using chooser, you can retrieve the content Url from OnActivityResult:

```<code>protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
     Android.Net.Uri uri = data.Data;
     string realFilePath=GetRealFilePath(uri);
     //post the realFilePath to Firebase here

     //store realFilePath locally to pass it to other activity
}
</code>```

To store the path of the image in Firebase, you need to convert the content url to real path of the file by using following codes:

```<code>public string GetRealFilePath(Uri uri)
{
    var isDocumentUri = DocumentsContract.IsDocumentUri(this, uri);
    if (isDocumentUri)
    {
        string id = DocumentsContract.GetDocumentId(uri);
        string[] split = id.Split(':');
        string type = split[0];
        if (IsMediaDocument(uri))
        {
            Uri contentUri = null;
            if ("image".Equals(type))
            {
                contentUri = MediaStore.Images.Media.ExternalContentUri;
                string selection = "_id=?";
                string[] selectionArgs = new string[] { split[1] };
                string filePath = GetDataColumn(this, contentUri, selection, selectionArgs);
                return filePath;
            }
        }
    }else
    {
      //when select the file directly from gallery, `isDocumentUri` will be false.
      var contentUri = MediaStore.Images.Media.ExternalContentUri;
      var selection = "_id=?";
      string[] selectionArgs = new string[] { uri.LastPathSegment };
      string filePath = GetDataColumn(this, contentUri, selection, selectionArgs);
      return filePath;
    }
    return null;
}

public  string GetDataColumn(Context context, Uri uri, string selection,string[] selectionArgs)
{

    ICursor cursor = null;
    string column = "_data";
    string[] projection = {
        column
    };

    try
    {
        cursor = ContentResolver.Query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.MoveToFirst())
        {
            int column_index = cursor.GetColumnIndexOrThrow(column);
            return cursor.GetString(column_index);
        }
    }
    finally
    {
        if (cursor != null)
            cursor.Close();
    }
    return null;
}

public static bool IsMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".Equals(uri.Authority);
}
</code>```

Title: ImageView in Dialogue Box -Xamarin

Body:
i want to add images by clicking a button, then select the pic from my gallery.

Use Chooser to select an image from the gallery:

private void BtnClick_Click(object sender, System.EventArgs e)
{
    Intent intent = new Intent();
    intent.SetType("image/*");
    intent.SetAction(Intent.ActionGetContent);
    StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), 0);
}

the i would want the the path of the photo to show on the dialogue and not the image itself. Save the path to firebase and retrieve the image itself into an imageview in another activity.

By using chooser, you can retrieve the content Url from OnActivityResult:

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
     Android.Net.Uri uri = data.Data;
     string realFilePath=GetRealFilePath(uri);
     //post the realFilePath to Firebase here

     //store realFilePath locally to pass it to other activity
}

To store the path of the image in Firebase, you need to convert the content url to real path of the file by using following codes:

public string GetRealFilePath(Uri uri)
{
    var isDocumentUri = DocumentsContract.IsDocumentUri(this, uri);
    if (isDocumentUri)
    {
        string id = DocumentsContract.GetDocumentId(uri);
        string[] split = id.Split(':');
        string type = split[0];
        if (IsMediaDocument(uri))
        {
            Uri contentUri = null;
            if ("image".Equals(type))
            {
                contentUri = MediaStore.Images.Media.ExternalContentUri;
                string selection = "_id=?";
                string[] selectionArgs = new string[] { split[1] };
                string filePath = GetDataColumn(this, contentUri, selection, selectionArgs);
                return filePath;
            }
        }
    }else
    {
      //when select the file directly from gallery, `isDocumentUri` will be false.
      var contentUri = MediaStore.Images.Media.ExternalContentUri;
      var selection = "_id=?";
      string[] selectionArgs = new string[] { uri.LastPathSegment };
      string filePath = GetDataColumn(this, contentUri, selection, selectionArgs);
      return filePath;
    }
    return null;
}

public  string GetDataColumn(Context context, Uri uri, string selection,string[] selectionArgs)
{

    ICursor cursor = null;
    string column = "_data";
    string[] projection = {
        column
    };

    try
    {
        cursor = ContentResolver.Query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.MoveToFirst())
        {
            int column_index = cursor.GetColumnIndexOrThrow(column);
            return cursor.GetString(column_index);
        }
    }
    finally
    {
        if (cursor != null)
            cursor.Close();
    }
    return null;
}

public static bool IsMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".Equals(uri.Authority);
}


问:
MS SQL apotrophe in prompt in WHERE clause
I am trying to deal with an apostrophe in a prompt field in my SQL statement.  Example below :

```<code>WHERE propertyfieldintable=@promptfromuser
</code>```

The problem is that there are addresses with an ' eg. Wood's therefore the SQL works for all other addresses except those with an '.

I have tried to use replace(@promptfromuser,"'","''") but keep getting an error (missing right ').  The propertyfieldintable is a text field so am assuming it needs a text input from the prompt.

I would appreciate any straightforward suggestions as the query is not in the database itself but sits within a reporting tool so can't take functions.

答: You need to use parameters.    </p>

Body:
I am trying to deal with an apostrophe in a prompt field in my SQL statement.  Example below :

WHERE propertyfieldintable=@promptfromuser

The problem is that there are addresses with an ' eg. Wood's therefore the SQL works for all other addresses except those with an '.

I have tried to use replace(@promptfromuser,"'","''") but keep getting an error (missing right ').  The propertyfieldintable is a text field so am assuming it needs a text input from the prompt.

I would appreciate any straightforward suggestions as the query is not in the database itself but sits within a reporting tool so can't take functions.

Body: You need to use parameters.


问:
"go get" git error on all sources but golang.org
go version go1.5.1 windows/amd64
git version 1.9.5.msysgit.1

I have been trying to get some Go libraries.
They are downloaded fine, when accessed on golang.org
but github.com or google.golang.org packages give an error.

```<code>There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details
</code>```

答: Delete the package from GOPATH and go get it again. Your package is modified and git is refusing to pull from upstream.</p>

Body:
go version go1.5.1 windows/amd64
git version 1.9.5.msysgit.1

I have been trying to get some Go libraries.
They are downloaded fine, when accessed on golang.org
but github.com or google.golang.org packages give an error.

There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details


问:
Materialize pushpin scrolling jumps
So I have a strange issue with scrolling when using the pushpin functionality on a navbar element.

When scrolling down on the page, once the pushpin navbar reaches the top where it becomes fixed, the content on the page jumps upward suddenly.

Here's a codepen to illustrate what I mean

If someone can point to what I'm doing wrong, I would be very grateful.

My initialization of pushpin:

```<code>$('#navbar').pushpin({
    top: $('#wrapper').offset().top
});
</code>```

General HTML Structure:

```<code><div class="intro">
    ...
</div>
<div id="wrapper">
    <nav id="navbar">
        ...
    </nav>
    <div class="content">
        ...
    </div>
</div>
</code>```

答:
In case it helps anyone here's the solution:

Wrap the navbar in a div with a fixed height equal to the navbar. When pushpin changes the navbar from relative to fixed, this changes the way it takes up space in the document. The wrapper div with a set height will conserve that space regardless of the navbar positioning.

HTML

```<code><div id="wrapper">
    <nav id="navbar">
        ...
    </nav>
</div>
</code>```

JS

```<code>$('#navbar').pushpin({
    top: $('#navbar').offset().top
});
</code>```

CSS

```<code>#wrapper {
    //height equal to height of navbar
    height: 64px;
}
</code>```

Title: Materialize pushpin scrolling jumps

Body:
So I have a strange issue with scrolling when using the pushpin functionality on a navbar element.

When scrolling down on the page, once the pushpin navbar reaches the top where it becomes fixed, the content on the page jumps upward suddenly.

Here's a codepen to illustrate what I mean

If someone can point to what I'm doing wrong, I would be very grateful.

My initialization of pushpin:

$('#navbar').pushpin({
    top: $('#wrapper').offset().top
});

General HTML Structure:

    ...

        ...

        ...

Body:
In case it helps anyone here's the solution:

Wrap the navbar in a div with a fixed height equal to the navbar. When pushpin changes the navbar from relative to fixed, this changes the way it takes up space in the document. The wrapper div with a set height will conserve that space regardless of the navbar positioning.

HTML

<div id="wrapper">
    <nav id="navbar">
        ...
    </nav>
</div>

JS

$('#navbar').pushpin({
    top: $('#navbar').offset().top
});

CSS

#wrapper {
    //height equal to height of navbar
    height: 64px;
}


问:
Number of digits using while true in Python
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:

```<code>number=int(input("Write number: "))
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break
print("The number of digits is: ", cont)
</code>```

My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?

答:
Have a look at this:

```<code>Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 123 / 10
12.3
</code>```

Yes, / is floating point division in Python so it's not doing what you expect.

You can see what's actually happening if you insert print(number) immediately after the division-by-ten. It does division continuously until it gets a number so small it cannot tell the difference between it and zero:

```<code>12.3
1.23
0.123
0.0123
0.00123
0.000123
1.23e-05
1.23e-06
1.23e-07
1.2300000000000001e-08
1.23e-09
1.2300000000000001e-10
1.2300000000000002e-11
1.2300000000000002e-12
1.2300000000000003e-13
1.2300000000000003e-14
1.2300000000000003e-15
:
1.2299999999999997e-307
1.2299999999999997e-308
1.23e-309
1.23e-310
1.23e-311
1.23e-312
1.23e-313
1.23e-314
1.23e-315
1.23e-316
1.23e-317
1.23e-318
1.23003e-319
1.23e-320
1.23e-321
1.24e-322
1e-323
0.0
</code>```

You can fix this by changing:

```<code>number=number/10
</code>```

into either of:

```<code>number = int(number / 10)
number = number // 10
</code>```

This will do integer division so will stop after the correct number of steps.

Body:
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:

number=int(input("Write number: "))
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break
print("The number of digits is: ", cont)

My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?

Body:
Have a look at this:

Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 123 / 10
12.3

Yes, / is floating point division in Python so it's not doing what you expect.

You can see what's actually happening if you insert print(number) immediately after the division-by-ten. It does division continuously until it gets a number so small it cannot tell the difference between it and zero:

12.3
1.23
0.123
0.0123
0.00123
0.000123
1.23e-05
1.23e-06
1.23e-07
1.2300000000000001e-08
1.23e-09
1.2300000000000001e-10
1.2300000000000002e-11
1.2300000000000002e-12
1.2300000000000003e-13
1.2300000000000003e-14
1.2300000000000003e-15
:
1.2299999999999997e-307
1.2299999999999997e-308
1.23e-309
1.23e-310
1.23e-311
1.23e-312
1.23e-313
1.23e-314
1.23e-315
1.23e-316
1.23e-317
1.23e-318
1.23003e-319
1.23e-320
1.23e-321
1.24e-322
1e-323
0.0

You can fix this by changing:

number=number/10

into either of:

number = int(number / 10)
number = number // 10

This will do integer division so will stop after the correct number of steps.


答: Python 3 does floating point division by default.  You need to use integer division.  number = number // 10.

Title: Number of digits using while true in Python


问:
Trying to hide all bbcode-generated divs within a span, but it isn't working
Here's an example of the html:

```<code><!-- Working Example-->
<span class='prv' style='cursor: pointer; cursor: hand';>
    This text is shown...
</span>
<span class='cnt' style='cursor: pointer; cursor: hand';>
    This text will be hidden on load and shown when the 'prv' class is clicked.
</span>
<!-- Broken Example-->
<span class='prv' style='cursor: pointer; cursor: hand';>
    This text is shown...</span>
<span class='cnt' style='cursor: pointer; cursor: hand';>
    <div class="bbcode_center" style="text-align:center">
        This text isn't hidden even though I want it to be.
    </div>
</span>
</code>```

In the working example, there aren't any bbcode tags, so no bbcode class divs are generated - but I can't just get rid of the bbcode tags because I need them displayed.

Here the jquery code:

```<code>function run_on_load() {
    $('.cnt').hide();
    //$('.cnt').children().hide(); <- Tried this too
}
$('.prv').click(function() {
    $('.prv').hide();
    $('.cnt').show();
});
$('.cnt').click(function() {
    $('.cnt').hide();
    $('.prv').show();
});
</code>```

This all works for the first example, but hides nothing in the second example. How do I make it so that the jquery code hides everything within the 'cnt' class span indiscriminately?

Also, the span in the broken example isn't clickable, apparently for the same reason. Is there a way to make all divs within the span clickable, like having a jquery findall type function add the clickable style to each individual bbcode class div?

Edit: To be clear, what happens in the working example is exactly what I want: 'prv' (the preview text) is shown, and when it is clicked it hides itself and instead shows 'cnt' (the full content/text). The only issue with the broken example is that nothing within bbcode divs in 'cnt' is ever hidden when I want it all hidden indiscriminately.

答:
Change your code like this:

```<code>$(function(){
  $('.cnt').hide();
});
</code>```

instead Old code:

```<code>function run_on_load() {

    //$('.cnt').children().hide(); <- Tried this too
}
</code>```

You have declare run_on_load() but not called on document load  . above i code is jquery short hand to do that

Body:
Here's an example of the html:

    This text is shown...

    This text will be hidden on load and shown when the 'prv' class is clicked.

    This text is shown...

        This text isn't hidden even though I want it to be.

In the working example, there aren't any bbcode tags, so no bbcode class divs are generated - but I can't just get rid of the bbcode tags because I need them displayed.

Here the jquery code:

function run_on_load() {
    $('.cnt').hide();
    //$('.cnt').children().hide(); <- Tried this too
}
$('.prv').click(function() {
    $('.prv').hide();
    $('.cnt').show();
});
$('.cnt').click(function() {
    $('.cnt').hide();
    $('.prv').show();
});

This all works for the first example, but hides nothing in the second example. How do I make it so that the jquery code hides everything within the 'cnt' class span indiscriminately?

Also, the span in the broken example isn't clickable, apparently for the same reason. Is there a way to make all divs within the span clickable, like having a jquery findall type function add the clickable style to each individual bbcode class div?

Edit: To be clear, what happens in the working example is exactly what I want: 'prv' (the preview text) is shown, and when it is clicked it hides itself and instead shows 'cnt' (the full content/text). The only issue with the broken example is that nothing within bbcode divs in 'cnt' is ever hidden when I want it all hidden indiscriminately.

Body:
Change your code like this:

$(function(){
  $('.cnt').hide();
});

instead Old code:

function run_on_load() {

    //$('.cnt').children().hide(); <- Tried this too
}

You have declare run_on_load() but not called on document load  . above i code is jquery short hand to do that


问:
SQLite : Need reference to "current" row in a UPDATE
I'm working with a SQLite table representing a tree.  Its columns include id and parent.  Of course, each parent value is the id of another row.

There is also a changeCount column, which I must increment by 1 for each child deleted in a bulk operation.

For example, say that

Rows with id 11, 12 and 13 are going to be deleted in a bulk operation.

The rows with id=11 and id=12 both have the same parent=5.

The row with id=13 has parent=8.

Then the row with id=5 should have its changeCount incremented by 2, and the row with id=8 should have its changeCount incremented by 1.

It seems like there should be a way to do this in one query.  Maybe something like this:

```<code>UPDATE myTable
    SET changeCount = changeCount
    + (SELECT COUNT(*) FROM myTable
       WHERE id IN (11,12,13) AND parent = XXXX);
</code>```

Expression XXXX should be a reference to the "current" row; that whose changeCount is being set.  Is there an expression for that?  Or is there a better approach to this problem?

答:
Thanks to the comment by @CL, I've herein edited my previous working but messy answer into one that looks pretty decent:

```<code>UPDATE myTable
  SET changeCount = changeCount
    + ifnull(
      (SELECT theCount FROM (SELECT parent AS theParent, COUNT(*) AS theCount FROM myTable WHERE id IN (11,12,13) GROUP BY parent) WHERE theParent = id)
      , 0);
</code>```

The reason for the ifnull() is that the id at the end of Line 4 makes that a correlated subquery, which is evaluated for each row in the table, and for rows which are not having any children deleted, it evaluates to NULL.

I wonder if performance could be improved by using two queries instead, first running the subquery (Line 4) as a standalone query, returning to the program a dictionary whose keys are the ids of parents with children being deleted and values are how many of its children are being deleted.  But my question was how to do this in one query :)

UPDATE: THE ABOVE IS OK FOR HOME BUT DON'T TRY IT AT WORK

I should have given more thought to the original comment by @CL.  Although this answer works, performance on a real SQLite database containing tens of thousands of rows was horrible.

LESSON: Fancy SQL queries such as this "answer" are interesting brain teasers, but in practice, if performance matters, if you have a real programming language available, you should instead use simple queries and do your processing in the real language.

That's what I ended up doing in the real-life case from which this question arose.

Body:
I'm working with a SQLite table representing a tree.  Its columns include id and parent.  Of course, each parent value is the id of another row.

There is also a changeCount column, which I must increment by 1 for each child deleted in a bulk operation.

For example, say that

Rows with id 11, 12 and 13 are going to be deleted in a bulk operation.

The rows with id=11 and id=12 both have the same parent=5.

The row with id=13 has parent=8.

Then the row with id=5 should have its changeCount incremented by 2, and the row with id=8 should have its changeCount incremented by 1.

It seems like there should be a way to do this in one query.  Maybe something like this:

UPDATE myTable
    SET changeCount = changeCount
    + (SELECT COUNT(*) FROM myTable
       WHERE id IN (11,12,13) AND parent = XXXX);

Expression XXXX should be a reference to the "current" row; that whose changeCount is being set.  Is there an expression for that?  Or is there a better approach to this problem?

Body:
Thanks to the comment by @CL, I've herein edited my previous working but messy answer into one that looks pretty decent:

UPDATE myTable
  SET changeCount = changeCount
    + ifnull(
      (SELECT theCount FROM (SELECT parent AS theParent, COUNT(*) AS theCount FROM myTable WHERE id IN (11,12,13) GROUP BY parent) WHERE theParent = id)
      , 0);

The reason for the ifnull() is that the id at the end of Line 4 makes that a correlated subquery, which is evaluated for each row in the table, and for rows which are not having any children deleted, it evaluates to NULL.

I wonder if performance could be improved by using two queries instead, first running the subquery (Line 4) as a standalone query, returning to the program a dictionary whose keys are the ids of parents with children being deleted and values are how many of its children are being deleted.  But my question was how to do this in one query :)

UPDATE: THE ABOVE IS OK FOR HOME BUT DON'T TRY IT AT WORK

I should have given more thought to the original comment by @CL.  Although this answer works, performance on a real SQLite database containing tens of thousands of rows was horrible.

LESSON: Fancy SQL queries such as this "answer" are interesting brain teasers, but in practice, if performance matters, if you have a real programming language available, you should instead use simple queries and do your processing in the real language.

That's what I ended up doing in the real-life case from which this question arose.


问:
How can I export a blender file into fbx and import it to unity so it will look and work the same way?
I have a model in blender with texturas, animations and multiple objects. When I put the blend file in the unity project it works just fine, but when I export it as fbx and import it into unity everything is completely messed up. The texturas mess up, the animations donwt wotk or only one of them and parts of the model apear rotated and not placed at their places. I tried every export and import settings, parented them to one empty object, changes rigging to legasy and went through all the animations to play them:

```<code>Animation animation = GameObject.Find("Head").GetComponent<Animation>();
         animation.Play();
         foreach (AnimationState state in animation)
         {
             animation.Play(state.name);
             Debug.Log(state.name);
         }
</code>```

but still nothing works and everything is completely messed up..What do I do wrong?

答:
Try adding empty object to your blender hierarchy I use plain axes and then export again. Just add it no need to reorganize your structure. This happens for axys orientation, is different across blender and unity.

BTW: why are you exporting using fbx? You can drag and drop any blender file into unity assets folder, ready for using.

Body:
I have a model in blender with texturas, animations and multiple objects. When I put the blend file in the unity project it works just fine, but when I export it as fbx and import it into unity everything is completely messed up. The texturas mess up, the animations donwt wotk or only one of them and parts of the model apear rotated and not placed at their places. I tried every export and import settings, parented them to one empty object, changes rigging to legasy and went through all the animations to play them:

Animation animation = GameObject.Find("Head").GetComponent<Animation>();
         animation.Play();
         foreach (AnimationState state in animation)
         {
             animation.Play(state.name);
             Debug.Log(state.name);
         }

but still nothing works and everything is completely messed up..What do I do wrong?


问:
displaying list of dates for loop
i have this code..that will display a list of month for the current year and the first day of first month and second month

```<code>$cur_year = date("Y");
$next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
{
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

echo "$monthName<br />";
echo "$cur_year-$monthNumber-01<br />";
echo "$cur_year-$nextmonth-01<br /><br />";
}
</code>```

i would like to be display like this

```<code>January
2017-01-01
2017-02-01

February
2017-02-01
2017-03-01

up to December

December
2017-12-01
2018-01-01
</code>```

current ouput

```<code>January
2017-01-01
2017-2-01

February
2017-02-01
2017-3-01

up to December

December
2017-12-01
2017-13-01
</code>```

答:
You can use "sprintf()".

You edit a line.

```<code>echo "$cur_year-".sprintf("%02d",$nextmonth)."-01<br /><br />";
</code>```

Title: displaying list of dates for loop

Body:
i have this code..that will display a list of month for the current year and the first day of first month and second month

$cur_year = date("Y");
$next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
{
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

echo "$monthName
";
echo "$cur_year-$monthNumber-01
";
echo "$cur_year-$nextmonth-01

";
}

i would like to be display like this

January
2017-01-01
2017-02-01

February
2017-02-01
2017-03-01

up to December

December
2017-12-01
2018-01-01

current ouput

January
2017-01-01
2017-2-01

February
2017-02-01
2017-3-01

up to December

December
2017-12-01
2017-13-01

Body:
You can use "sprintf()".

You edit a line.

echo "$cur_year-".sprintf("%02d",$nextmonth)."-01<br /><br />";


问:
Find shortest path between list of nodes in single query Neo4j
I have two lists

```<code>['avia', 'paul', 'tom']

['james','bond']
</code>```

I am tring to find the shortes path between

```<code>avia -> james
paul -> james
tom -> james
avia -> bond
paul -> bond
tom -> bond
</code>```

i create the query with in two loops and query neo4j every time
so multiple calls are being made to neo4j. is ther a way to creat this in one stored procedure and make only one call to neo4j. sample query is like below

```<code>match p = allShortestPaths((a{name:'avia'})-[*..2]-(b {name:'james'})) return p
</code>```

答:
Easiest way should be just to match both start and end nodes using index lookups (via property membership within your list parameters) for both, then running shortestPath. Something like this, but with parameterized inputs:

```<code>WITH ['avia', 'paul', 'tom'] as startNames, ['james','bond'] as endNames
MATCH (start:Person), (end:Person)
WHERE start.name in startNames and end.name in endNames
MATCH p=allShortestPaths((start)-[*..2]-(end))
RETURN p
</code>```

You'll want to have an index on :Person(name) (or on whatever equivalent you're using) so these utilize index lookups

Body:
I have two lists

['avia', 'paul', 'tom']

['james','bond']

I am tring to find the shortes path between

avia -> james
paul -> james
tom -> james
avia -> bond
paul -> bond
tom -> bond

i create the query with in two loops and query neo4j every time
so multiple calls are being made to neo4j. is ther a way to creat this in one stored procedure and make only one call to neo4j. sample query is like below

match p = allShortestPaths((a{name:'avia'})-[*..2]-(b {name:'james'})) return p

Body:
Easiest way should be just to match both start and end nodes using index lookups (via property membership within your list parameters) for both, then running shortestPath. Something like this, but with parameterized inputs:

WITH ['avia', 'paul', 'tom'] as startNames, ['james','bond'] as endNames
MATCH (start:Person), (end:Person)
WHERE start.name in startNames and end.name in endNames
MATCH p=allShortestPaths((start)-[*..2]-(end))
RETURN p

You'll want to have an index on :Person(name) (or on whatever equivalent you're using) so these utilize index lookups


问:
Ordering file http stream
I'm streaming a video over a http connection, using a nodeJS server.

At the moment, I'm reading chunks from the video before writing the each chunk to the stream, sequentially; thus, very slowly.

I want to pipeline this, so I'm multiple asynchronous requests for data, thus, increasing my throughput.

But, the data I request will not arrive in order, so I cant simply relay the chunks to the HTTP stream as I was before.

I believe I will need to buffer the data until I have the next peice(s) to be written, in order. However, I also believe this will use much more memory, because I the application will be storing multiple chunks on behalf of the user.

Is it possible to have the client sort the chunks, some how, so I can instantly relay it in an unordered fashion (with a chunk-id), allowing me to resume minimal memory usage?

答:
I think you need a causal RTP algorithm, you could read about Saul E. Pomares Hernandez, Eduardo Lopez Dominguez works, they have some good papers about this subject, they both are researcher from INAOE University.

Enjoy it!

Title: Ordering file http stream


问:
java regular expression to match file path
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

```<code>import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}
</code>```

However it's always giving me , false as result .

答:
It does not match, because your regex match only to paths, not to files. -- More correct: it does not accept the dot in your file name.

And in addition, there is the escaping problem mentiond by roe.

Body:
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}

However it's always giving me , false as result .


问:
Wordpress Site down for my own IP address
I just migrate my site to another hosting provider using wordpress Duplicator plugin. Before waiting for DNS propagate, i already change the host file so that I can run the installer file from Duplicator. When everything is done, I revert the host file to original, but then my site appear as white screen of death (other browsers) and 500 error (chrome). But it looks perfectly fine when I test it from other ip adress (mobile 4g, or home wifi), it only fail for my work wifi. Does anyone know what's wrong with this?

ps: I have checked my own IP address is not blocked

答:
Open your wp-config.php and change line from define('WP_DEBUG', false); to define('WP_DEBUG', true);. If you don't have this line in your wp-config.php then you should add it after database settings.

You will reload a page after the changes and will see more details of error

Read more about Wordpress Debugging