问:
String array comparison using Jasmine toContains or toMatch
I have a string array names which gets dynamically filled with the names from a dataset. Three names in this array are always the same even though the dataset is changed. So, in my spec I want to check if the names array contains these three specific names. But the matchers aren't helping me in Jasmine.

Example:

```<code>names = ["a", "b", "c", "d", "e", "f", "g"];
expect(names).toContain("b","d","c"); // this should return true as b, d, and c are in the names array
</code>```

The above expect statement doesn't work. Is there a way to use toMatch and use a regex to solve this problem?

Could anyone help me out with this.

Thank you.

答:
Instead of using toContain() you can simply implement the following function and expect the result to be true or false.

```<code>function arrayContains(superset, subset) {
    if (subset.length === 0) return false;
    return subset.every(function (value) {
        return (superset.indexOf(value) >= 0);
    });
}
</code>```

Now, you can call this function inside your expect statement as follows:

```<code>expect(arrayContains(names,["b", "d", "c"])).toBe(true);
</code>```

As you have mentioned, the three names are always expected, you can assign it to a variable and just pass that in the function above.

Hope that helps. You can even implement a customMatcher if necessary.

Body:
I have a string array names which gets dynamically filled with the names from a dataset. Three names in this array are always the same even though the dataset is changed. So, in my spec I want to check if the names array contains these three specific names. But the matchers aren't helping me in Jasmine.

Example:

names = ["a", "b", "c", "d", "e", "f", "g"];
expect(names).toContain("b","d","c"); // this should return true as b, d, and c are in the names array

The above expect statement doesn't work. Is there a way to use toMatch and use a regex to solve this problem?

Could anyone help me out with this.

Thank you.

Body:
Instead of using toContain() you can simply implement the following function and expect the result to be true or false.

function arrayContains(superset, subset) {
    if (subset.length === 0) return false;
    return subset.every(function (value) {
        return (superset.indexOf(value) >= 0);
    });
}

Now, you can call this function inside your expect statement as follows:

expect(arrayContains(names,["b", "d", "c"])).toBe(true);

As you have mentioned, the three names are always expected, you can assign it to a variable and just pass that in the function above.

Hope that helps. You can even implement a customMatcher if necessary.


来源: stackexchange

问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答: "C:\Program Files" is just a convention, although it certainly is handy to have a single directory where all program files reside.  The directory can also be hidden from clumsy casual users who might otherwise unintentionally delete program files.  However, with that said, you can install an application anywhere you can write to.</p>

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MattK


问:
How to set the icon-size in a QTreeWidget?
How does one set the icon size for items within a Qtreewidget? So far I have tried

QTreeWidget.setIconSize(QSize(32,32))

But all that does is increase the width, not the height.

However, a

print QTreeWidget.iconSize()

shows the correct result :
PyQt4.QtCore.QSize(32, 32)

Does anyone have a better understanding of how QTreewidget works?

答: Looks to me like you need to adjust the row height of the QTreeView to accommodate the larger icons.  From what I can see in the pictures, it looks like the icons are being resized properly, but because the rows are not tall enough and the icons are being cropped.  See this for how to change the row heights.</p>

ContentLicense: CC BY-SA 3.0


问:
Element showing as null on page load
I am trying to attach a hover function to a dynamic div ID that is being generated by a script (using Smooch api). The function doesn't work even when I run it in my console after everything has been loaded.

I tried doing:

```<code>$(document).on("mouseenter", "#messenger-button", function() {
    alert("hey")
});
</code>```

and I keep getting this error: Uncaught TypeError: Cannot read property 'on' of undefined

The html that is being generated after the Smooch api is initiated looks like this:

```<code><iframe>
 <html>
   <div id="messenger-button" style="background-color: rgb(10, 74, 119);>
 </html>
</iframe>
</code>```

There is no function that is allowing me to add a class, change the css, or do anything to change the properties for the div in the generated iframe. Can anyone who has used Smooch api tell me how I can add a hover state to the messenger button that is generated?

答:
You'll need to select the iframe and get its contents and change the elements from there, see.</p>

```<code>$(document).ready(function(){
    var iFrameDOM = $("iframe").contents();

    iFrameDOM.find("#messenger-button").addClass("new-messenger");
});
</code>```

Title: Element showing as null on page load

Body:
I am trying to attach a hover function to a dynamic div ID that is being generated by a script (using Smooch api). The function doesn't work even when I run it in my console after everything has been loaded.

I tried doing:

$(document).on("mouseenter", "#messenger-button", function() {
    alert("hey")
});

and I keep getting this error: Uncaught TypeError: Cannot read property 'on' of undefined

The html that is being generated after the Smooch api is initiated looks like this:

There is no function that is allowing me to add a class, change the css, or do anything to change the properties for the div in the generated iframe. Can anyone who has used Smooch api tell me how I can add a hover state to the messenger button that is generated?

Body:
You'll need to select the iframe and get its contents and change the elements from there, see.

$(document).ready(function(){
    var iFrameDOM = $("iframe").contents();

    iFrameDOM.find("#messenger-button").addClass("new-messenger");
});


问:
C - malloc and automatic storage
I understand that variables declared within a function have automatic storage. Does this mean it's not necessary to free pointers (p below) that have been explicitly allocated within a function call using malloc?

```<code>void f() {
  int *p;

  p = malloc(sizeof(int));
  *p = 1;
  printf("%p %d\n", p, *p);  // 0x7fc135c02850 1
  free(p);                   // is this necessary?
}

int main() {
  f();
}
</code>```

(Note that I used a pointer to an int here, but the question applies to any pointer that's a return value of malloc and friends.)

I'm guessing no, since malloc allocates memory on the heap and not the stack; thus the memory p points to won't automatically be deallocated when the stack frame for f() is popped.

答: Correct, a call to free is necessary.

Title: C - malloc and automatic storage

Body:
I understand that variables declared within a function have automatic storage. Does this mean it's not necessary to free pointers (p below) that have been explicitly allocated within a function call using malloc?

void f() {
  int *p;

  p = malloc(sizeof(int));
  *p = 1;
  printf("%p %d\n", p, *p);  // 0x7fc135c02850 1
  free(p);                   // is this necessary?
}

int main() {
  f();
}

(Note that I used a pointer to an int here, but the question applies to any pointer that's a return value of malloc and friends.)

I'm guessing no, since malloc allocates memory on the heap and not the stack; thus the memory p points to won't automatically be deallocated when the stack frame for f() is popped.

Body: Correct, a call to free is necessary.


问:
How to create shortcut to desktop app in the all apps menu using Visual Studio Installer
In my solution I have a Windows desktop project and a Visual Studio installer setup project. The Windows project is just for testing purposes and does not have any UI.

I want to configure my installer project to install my Windows app and create an entry in the all apps list in the start menu, however I don't see any way of doing this.

The only way I have found that I can create an entry in the all apps list is by creating and installing a UWP app.

How do I create an entry for my Windows app?

答:
I found the answer.

In the Visual Studio installer setup project, in the solution explorer, right click on the project and go to view file system.

Right click on 'File System on Target Machine' in the file system menu, and go to 'add special folder'. Add 'User's start menu'. Cut and paste shortcut of primary output into the start menu.


问:
Updating a SQL record with Powershell
It's me again, I'm still getting to limited grips about how PowerShell and SQL work together, this isn't my main field of experience so please excuse the simple mistake I've probably made.

I am trying to update one field in a row.  I've searched here and been able to build most of what I need but am getting an error message that states

"Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near 'f7'."
At line:61 char:5
+     $rowsAffected = $command2.ExecuteNonQuery()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException"

This is the code snippet I am using is this section, it is embedded within a foreach loop that steps through the rows of a dataset and sends an email.  This section is supposed to change the bit type field "mailed" to true which ensure that only one email is sent per record.

```<code>$connect2 = New-Object System.Data.SqlClient.SqlConnection
$connect2.ConnectionString=$ServerConnection
$connect2.Open()
$command2 = New-Object System.Data.SqlClient.SqlCommand
$command2.Connection = $connect2
$MySql2="UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ="+$BT1
$command2.CommandText = $MySql2
$rowsAffected = $command2.ExecuteNonQuery()
Write-Output "Updating mailed marker"
$connect2.Close()
</code>```

EBGreen's suggestion worked perfectly.  Changing the text string for the $MySql2 = "UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ='"+$BT1+"'" fixed the error and the field is being updated as required.

答:
Try displaying your sql string to make sure it looks correct.  It could be that your $BT1 variable is blank.

```<code>write-host $MySql2
</code>```

Also, when dealing with sql syntax errors it is helpful to log in directly to the sql server and submit the string through the sql command line shell.  Once you can submit the string successfully from the command line then check that your powershell string looks exactly the same.

Title: Updating a SQL record with Powershell

Body:
It's me again, I'm still getting to limited grips about how PowerShell and SQL work together, this isn't my main field of experience so please excuse the simple mistake I've probably made.

I am trying to update one field in a row.  I've searched here and been able to build most of what I need but am getting an error message that states

"Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near 'f7'."
At line:61 char:5
+     $rowsAffected = $command2.ExecuteNonQuery()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException"

This is the code snippet I am using is this section, it is embedded within a foreach loop that steps through the rows of a dataset and sends an email.  This section is supposed to change the bit type field "mailed" to true which ensure that only one email is sent per record.

$connect2 = New-Object System.Data.SqlClient.SqlConnection
$connect2.ConnectionString=$ServerConnection
$connect2.Open()
$command2 = New-Object System.Data.SqlClient.SqlCommand
$command2.Connection = $connect2
$MySql2="UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ="+$BT1
$command2.CommandText = $MySql2
$rowsAffected = $command2.ExecuteNonQuery()
Write-Output "Updating mailed marker"
$connect2.Close()

EBGreen's suggestion worked perfectly.  Changing the text string for the $MySql2 = "UPDATE dbo.scans SET Mailed = 'True' WHERE SessionID ='"+$BT1+"'" fixed the error and the field is being updated as required.

Body:
Try displaying your sql string to make sure it looks correct.  It could be that your $BT1 variable is blank.

write-host $MySql2

Also, when dealing with sql syntax errors it is helpful to log in directly to the sql server and submit the string through the sql command line shell.  Once you can submit the string successfully from the command line then check that your powershell string looks exactly the same.


问:
Increasing and decreasing value of the clicks of the button
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="Button" id="bt" /></code>```

答:
Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:

```<code>function clickME(event) {
    var btn = event.target;
    btn.clicks = ((btn.clicks || 0) + 1) % 2;
    window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
    document.getElementById("clicks").innerText = window.clicks;
}
</code>```

Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.

Note:
Don't forget to pass the event data object with the onclick attribute in HTML:

```<code><input onclick="clickME(event)" ...>
</code>```

Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/

Body:
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}

<input type="Button" id="bt" />

Body:
Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:

function clickME(event) {
    var btn = event.target;
    btn.clicks = ((btn.clicks || 0) + 1) % 2;
    window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
    document.getElementById("clicks").innerText = window.clicks;
}

Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.

Note:
Don't forget to pass the event data object with the onclick attribute in HTML:

<input onclick="clickME(event)" ...>

Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/


问:
Html Agility Pack vs. 302 redirects to same page
I'm trying to pick up meta tags from the old http://www.printprint.ca site at 108.170.59.213 (I have this in my hosts file), but can't seem to get anything in DocumentNode.
The old site seems to 302 redirect to the same page, and it breaks all crawlers like Xenu, ScreamingFrog, BeamUsUp...
After inital 302 to same page it responds with 200 but I don't know how to make HtmlAgilityPack pick up on that.
I've tried adding this:</p>

```<code>web.PreRequest = OnPreRequest;

private static bool OnPreRequest(HttpWebRequest request)
    {
        request.AllowAutoRedirect = true;
        return true;
    }
</code>```

答:
I know this old. But since there is no answer I might input my solution.</p>

```<code>public static void Main(string[] args)
{
    HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.printprint.ca ");
        request.Method = "GET";
        request.ContentType = "text/html;charset=utf-8";

        using (var response = (HttpWebResponse)request.GetResponse())
        {

            using (var stream = response.GetResponseStream())
            {
                doc.Load(stream, Encoding.GetEncoding("utf-8"));
            }
        }
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
    }
    HtmlNodeCollection metas = doc.DocumentNode.SelectNodes(".//meta");
    foreach(HtmlNode meta in metas)
    {
        Console.WriteLine(meta.OuterHtml);
        Console.WriteLine();
    }
    Console.ReadKey();
}
</code>```

Body:
I'm trying to pick up meta tags from the old http://www.printprint.ca site at 108.170.59.213 (I have this in my hosts file), but can't seem to get anything in DocumentNode.
The old site seems to 302 redirect to the same page, and it breaks all crawlers like Xenu, ScreamingFrog, BeamUsUp...
After inital 302 to same page it responds with 200 but I don't know how to make HtmlAgilityPack pick up on that.
I've tried adding this:

web.PreRequest = OnPreRequest;

private static bool OnPreRequest(HttpWebRequest request)
    {
        request.AllowAutoRedirect = true;
        return true;
    }

Body:
I know this old. But since there is no answer I might input my solution.

public static void Main(string[] args)
{
    HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.printprint.ca ");
        request.Method = "GET";
        request.ContentType = "text/html;charset=utf-8";

        using (var response = (HttpWebResponse)request.GetResponse())
        {

            using (var stream = response.GetResponseStream())
            {
                doc.Load(stream, Encoding.GetEncoding("utf-8"));
            }
        }
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
    }
    HtmlNodeCollection metas = doc.DocumentNode.SelectNodes(".//meta");
    foreach(HtmlNode meta in metas)
    {
        Console.WriteLine(meta.OuterHtml);
        Console.WriteLine();
    }
    Console.ReadKey();
}


答: If you ask for memory allocate manually, you must free manually the space you asked for. So free is necessary there </p>

Title: C - malloc and automatic storage


问:
Get Twilio Chat User Channels sorted by last activity or unread count?
We are developing a chat system where users can be in many chat rooms, and I'd like to be able to show the most recent channels first.

This could be either by the time the last message was sent, or even by the number of unread messages, as long as there is some order and I don't need to go through all the pages of channels and get additional metadata to sort it manually.

I can't see any options in the docs and even though the response metadata has a "key" set to "channels", I haven't been able to figure out a query parameter that can change that.

It seems like channels will always be returned ordered by the random unique channel ID, so for pretty much every use case you'd need to get all channels and sort manually. Is that the case or am I missing something?

答:
Twilio developer evangelist here.

I'm afraid you cannot order the channels within the API right now. This feature is on the roadmap though, however I can't give any time estimates for it.

The solution for now is sorting manually. I will update once that changes though.


问:
golang regular expression ReplaceAllString
I am writing a chatbot program in the Go programming language.
In this function it reads in a user string checks for a regular expression and then is supposed to remove the expression and replace with another string if found. It is successful in finding a match but will not append it to the string

```<code>input = "I am feeling happy"
pattern2 := []string{`.*i am.*`, `.*I AM.*`, `.*I'm.*`, `.*i'm.*`, `.*im.*`, `.*I am.*`}

// loop through pattern2 array
//if pattern is found extract substring
//set response

for _, checkPattern := range pattern2 {
    re := regexp.MustCompile(checkPattern)
    if re.MatchString(input) {
        match := re.ReplaceAllString(input, "How do you know you are $1 ?")
        response = "output : " + match
        return response
    } //if re.MatchString
} //for pattern2
</code>```

my output for response is "how do you know you are"

my intended output "how do you know you are feeling happy"

答: Your regular expressions are matching everything before and after the literals and extracting them. You need to actually capture the substring that will be used in your re.ReplaceAllString call. Replace the second .* in each expression with (.*).

Body:
I am writing a chatbot program in the Go programming language.
In this function it reads in a user string checks for a regular expression and then is supposed to remove the expression and replace with another string if found. It is successful in finding a match but will not append it to the string

input = "I am feeling happy"
pattern2 := []string{`.*i am.*`, `.*I AM.*`, `.*I'm.*`, `.*i'm.*`, `.*im.*`, `.*I am.*`}

// loop through pattern2 array
//if pattern is found extract substring
//set response

for _, checkPattern := range pattern2 {
    re := regexp.MustCompile(checkPattern)
    if re.MatchString(input) {
        match := re.ReplaceAllString(input, "How do you know you are $1 ?")
        response = "output : " + match
        return response
    } //if re.MatchString
} //for pattern2

my output for response is "how do you know you are"

my intended output "how do you know you are feeling happy"


答: p itself is automatic storage, and it will disappear when the function ends. What it points to however does need to be free()'d, at some point. For example, you could return the malloc()'d memory from the function, and free() it later on - p has still disappeared

Title: C - malloc and automatic storage


问:
Change Validation Summary Text in MVC for a password validation
How do I change the default message on the validation summary when a password does not meet the requirements. The current message the appears is

"Passwords must have at least one digit ('0'-'9'). Passwords must have at least one uppercase ('A'-'Z')."

I want to change that text to something else.

答:
I figured it out.. I hope it is the right way to do this. but here is my code. I commented out one line and replaced with the one right under it.</p>

```<code>private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                //ModelState.AddModelError("", error);
                ModelState.AddModelError("", "PASSWORDS MUST BE AT LEAST 6 CHARACTERS LONG, WITH AT LEAST ONE NUMBER, AND ONE NON LETTER OR DIGIT SUCH AS %, #, @, !, AND *. AN EXAMPLE: PASSWORD1$.");
            }
</code>```

Body:
I figured it out.. I hope it is the right way to do this. but here is my code. I commented out one line and replaced with the one right under it.

private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                //ModelState.AddModelError("", error);
                ModelState.AddModelError("", "PASSWORDS MUST BE AT LEAST 6 CHARACTERS LONG, WITH AT LEAST ONE NUMBER, AND ONE NON LETTER OR DIGIT SUCH AS %, #, @, !, AND *. AN EXAMPLE: PASSWORD1$.");
            }


问:
Autodesk Forge - Best training for transitioning from desktop .Net coding
I have background in Inventor/Revit API development only, and need to learn enough JS to be able to work comfortably with the Forge APIs. I'll be booking myself into a JS training course to learn general skills, but what topics/modules must I definitely cover to have a solid foundation for Forge API development. I'll be working with BOM data, viewers and possibly web configurators.

Many thanks for your help.

答:
We're a .Net shop that recently implemented the Forge Viewer for a client with Inventor Files.  We built our service on top of Azure Functions and utilized as much .Net C# code as possible, as it is where we have the most experience and comfortability.  The provided .Net SDK is very helpful: https://www.nuget.org/packages/Autodesk.Forge/.

The only API that you can't do entirely in .Net is the Viewer API.  However, to get started I was able to use boilerplate code from the provided examples and get the models loading.  From there I had our web developers get involved to handle the more extensive javascript programming for me.

Feel free to bounce any questions you may have off of me.  We've just finished going down this road and it is very rewarding, but somewhat challenging at times for us .Net developers.


问:
postgres array_agg ERROR: cannot accumulate arrays of different dimensionality
I have a parcels table in postgresql in which the zoning and zoning_description columns are array_agg cast over to text. the new.universities table has 9 rows and I need to return 9 rows in the output.

The purpose of this query is to find all the properties these universities are located on and collapse there zoning types into 1 unique column and union/dissolve their geometries into multipolygons

```<code>select array_agg(distinct dp.zoning) zoning,array_agg(distinct dp.zoning_description) zoning_description,
    uni.school name_,uni.address,'University' type_,1000 buff,st_union(dp.geom)
from new.universities uni join new.detroit_parcels_update dp
on st_intersects(st_buffer(uni.geom,-10),dp.geom)
group by name_,uni.address,type_,buff
</code>```

I get this error

```<code>ERROR:  cannot accumulate arrays of different dimensionality
********** Error **********

ERROR: cannot accumulate arrays of different dimensionality
SQL state: 2202E
</code>```

I can do array_agg(distinct dp.zoning::text) zoning etc.. but this returns a completely messed up column with nested arrays in arrays...

Based on the answer here is my updated query which does not work

```<code>select array_agg(distinct zoning_u) zoning,array_agg(distinct zoning_description_u) zoning_description,
        uni.school name_,uni.address,'University' type_,1000::int buff,st_union(dp.geom) geom
from new.detroit_parcels_update dp,unnest(zoning) zoning_u,
unnest(zoning_description) zoning_description_u
join new.universities uni
on st_intersects(st_buffer(uni.geom,-10),dp.geom)
group by name_,uni.address,type_,buff order by name_
</code>```

get this error

```<code>ERROR:  invalid reference to FROM-clause entry for table "dp"
LINE 6: on st_intersects(st_buffer(uni.geom,-10),dp.geom)
                                                 ^
HINT:  There is an entry for table "dp", but it cannot be referenced from this part of the query.

********** Error **********

ERROR: invalid reference to FROM-clause entry for table "dp"
SQL state: 42P01
Hint: There is an entry for table "dp", but it cannot be referenced from this part of the query.
Character: 373
</code>```

My Final query which worked was

```<code>with t as(select dp.zoning,dp.zoning_description,uni.school name_,uni.address,'University' type_,1000::int buff,st_union(dp.geom) geom
    from new.detroit_parcels_update dp
    join new.universities uni
    on st_intersects(st_buffer(uni.geom,-10),dp.geom)
    group by name_,uni.address,type_,buff,dp.zoning,zoning_description order by name_
    )
select name_,address,type_,buff,st_union(geom) geom,array_agg(distinct z) zoning, array_agg(distinct zd) zoning_description
from t,unnest(zoning) z,unnest(zoning_description) zd
group by name_,address,type_,buff
</code>```

答:
Example data:

```<code>create table my_table(name text, numbers text[], letters text[]);
insert into my_table values
    ('first',  '{1, 2}', '{a}'   ),
    ('first',  '{2, 3}', '{a, b}'),
    ('second', '{4}',    '{c, d}'),
    ('second', '{5, 6}', '{c}'   );
</code>```

You should aggregate arrays elements, not arrays. Use unnest():

```<code>select
    name,
    array_agg(distinct number) as numbers,
    array_agg(distinct letter) as letters
from
    my_table,
    unnest(numbers) as number,
    unnest(letters) as letter
group by name;

  name  | numbers | letters
--------+---------+---------
 first  | {1,2,3} | {a,b}
 second | {4,5,6} | {c,d}
(2 rows)
</code>```

Alternatively, you can create a custom aggregate. You need a function to merge arrays (concatenation with duplicates removing):

```<code>create or replace function public.array_merge(arr1 anyarray, arr2 anyarray)
    returns anyarray language sql immutable
as $$
    select array_agg(distinct elem order by elem)
    from (
        select unnest(arr1) elem
        union
        select unnest(arr2)
    ) s
$$;

create aggregate array_merge_agg(anyarray) (
    sfunc = array_merge,
    stype = anyarray
);

select
    name,
    array_merge_agg(numbers) as numbers,
    array_merge_agg(letters) as letters
from my_table
group by name;
</code>```

Body:
I have a parcels table in postgresql in which the zoning and zoning_description columns are array_agg cast over to text. the new.universities table has 9 rows and I need to return 9 rows in the output.

The purpose of this query is to find all the properties these universities are located on and collapse there zoning types into 1 unique column and union/dissolve their geometries into multipolygons

select array_agg(distinct dp.zoning) zoning,array_agg(distinct dp.zoning_description) zoning_description,
    uni.school name_,uni.address,'University' type_,1000 buff,st_union(dp.geom)
from new.universities uni join new.detroit_parcels_update dp
on st_intersects(st_buffer(uni.geom,-10),dp.geom)
group by name_,uni.address,type_,buff

I get this error

ERROR:  cannot accumulate arrays of different dimensionality
********** Error **********

ERROR: cannot accumulate arrays of different dimensionality
SQL state: 2202E

I can do array_agg(distinct dp.zoning::text) zoning etc.. but this returns a completely messed up column with nested arrays in arrays...

Based on the answer here is my updated query which does not work

select array_agg(distinct zoning_u) zoning,array_agg(distinct zoning_description_u) zoning_description,
        uni.school name_,uni.address,'University' type_,1000::int buff,st_union(dp.geom) geom
from new.detroit_parcels_update dp,unnest(zoning) zoning_u,
unnest(zoning_description) zoning_description_u
join new.universities uni
on st_intersects(st_buffer(uni.geom,-10),dp.geom)
group by name_,uni.address,type_,buff order by name_

get this error

ERROR:  invalid reference to FROM-clause entry for table "dp"
LINE 6: on st_intersects(st_buffer(uni.geom,-10),dp.geom)
                                                 ^
HINT:  There is an entry for table "dp", but it cannot be referenced from this part of the query.

********** Error **********

ERROR: invalid reference to FROM-clause entry for table "dp"
SQL state: 42P01
Hint: There is an entry for table "dp", but it cannot be referenced from this part of the query.
Character: 373

My Final query which worked was

with t as(select dp.zoning,dp.zoning_description,uni.school name_,uni.address,'University' type_,1000::int buff,st_union(dp.geom) geom
    from new.detroit_parcels_update dp
    join new.universities uni
    on st_intersects(st_buffer(uni.geom,-10),dp.geom)
    group by name_,uni.address,type_,buff,dp.zoning,zoning_description order by name_
    )
select name_,address,type_,buff,st_union(geom) geom,array_agg(distinct z) zoning, array_agg(distinct zd) zoning_description
from t,unnest(zoning) z,unnest(zoning_description) zd
group by name_,address,type_,buff

Body:
Example data:

create table my_table(name text, numbers text[], letters text[]);
insert into my_table values
    ('first',  '{1, 2}', '{a}'   ),
    ('first',  '{2, 3}', '{a, b}'),
    ('second', '{4}',    '{c, d}'),
    ('second', '{5, 6}', '{c}'   );

You should aggregate arrays elements, not arrays. Use unnest():

select
    name,
    array_agg(distinct number) as numbers,
    array_agg(distinct letter) as letters
from
    my_table,
    unnest(numbers) as number,
    unnest(letters) as letter
group by name;

  name  | numbers | letters
--------+---------+---------
 first  | {1,2,3} | {a,b}
 second | {4,5,6} | {c,d}
(2 rows)

Alternatively, you can create a custom aggregate. You need a function to merge arrays (concatenation with duplicates removing):

create or replace function public.array_merge(arr1 anyarray, arr2 anyarray)
    returns anyarray language sql immutable
as $$
    select array_agg(distinct elem order by elem)
    from (
        select unnest(arr1) elem
        union
        select unnest(arr2)
    ) s
$$;

create aggregate array_merge_agg(anyarray) (
    sfunc = array_merge,
    stype = anyarray
);

select
    name,
    array_merge_agg(numbers) as numbers,
    array_merge_agg(letters) as letters
from my_table
group by name;


答: The memory you allocate with malloc() needs to be free()'d. In your case, automatic storage applies to the variable p itself, but not to the memory you allocated! When you use free(p), you free the memory p points to and not the p variable itself.

Title: C - malloc and automatic storage


问:
Shared Preferences Not Applying Changes
I have an activity (A) that checks my server for APK updates. When this function is called, whether there is or is not an update, I need the shared preferences to be edited so the application knows to skip or run the actual update activity (B). Question 1 is, why are the shared preferences not being edited by activity (A)? Question 2 is, if they are being edited, why isn't activity (B) reading them?

Thank You in advance!

Shared preferences should be edited here (Activity (A)):

```<code>    private void parseJson(String result) {
    try {

        JSONObject obj = new JSONObject(result);
        String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
        String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
        int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

        int versionCode = AppUtils.getVersionCode(mContext);

        if (apkCode > versionCode) {
            if (mType == Constants.TYPE_NOTIFICATION) {
                showNotification(mContext, updateMessage, apkUrl);
            } else if (mType == Constants.TYPE_DIALOG) {
                SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = pref.edit();
                ed.putBoolean("activity_update", true);
                ed.apply();
                showDialog(mContext, updateMessage, apkUrl);
            }
        } else if (mShowProgressDialog) {
            SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putBoolean("activity_update", false);
            ed.apply();
            Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "parse json error");
    }
}
</code>```

Activity (B):

```<code>        SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_update", false)){
        Intent intent = new Intent(this, Main.class);
        deleteCache(getApplicationContext());
        startActivity(intent);
        finish();
    } else {
        functionUp();
    }
</code>```

答:
You code is ok,you should check you ed.apply(); is executed is your code .

In Activity(A) , you should check the order in which the program is executed .

1.Make sure that parseJson method is executed .

2.If you parse json error ,you should check JSONException.

```<code>Log.e(Constants.TAG, "parse json error");
e.printStackTrace();
</code>```

3.If apkCode > versionCode is executed ,IsmType == Constants.TYPE_DIALOG executed ?

4.If apkCode < versionCode is executed ,Is mShowProgressDialog true in your code ?

And you can add Log to check it .

```<code>ed.apply();
Log.e(Constants.TAG, "SharedPreferences is apply");
</code>```

Title: Shared Preferences Not Applying Changes

Body:
I have an activity (A) that checks my server for APK updates. When this function is called, whether there is or is not an update, I need the shared preferences to be edited so the application knows to skip or run the actual update activity (B). Question 1 is, why are the shared preferences not being edited by activity (A)? Question 2 is, if they are being edited, why isn't activity (B) reading them?

Thank You in advance!

Shared preferences should be edited here (Activity (A)):

    private void parseJson(String result) {
    try {

        JSONObject obj = new JSONObject(result);
        String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
        String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
        int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

        int versionCode = AppUtils.getVersionCode(mContext);

        if (apkCode > versionCode) {
            if (mType == Constants.TYPE_NOTIFICATION) {
                showNotification(mContext, updateMessage, apkUrl);
            } else if (mType == Constants.TYPE_DIALOG) {
                SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = pref.edit();
                ed.putBoolean("activity_update", true);
                ed.apply();
                showDialog(mContext, updateMessage, apkUrl);
            }
        } else if (mShowProgressDialog) {
            SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putBoolean("activity_update", false);
            ed.apply();
            Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "parse json error");
    }
}

Activity (B):

        SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_update", false)){
        Intent intent = new Intent(this, Main.class);
        deleteCache(getApplicationContext());
        startActivity(intent);
        finish();
    } else {
        functionUp();
    }

Body:
You code is ok,you should check you ed.apply(); is executed is your code .

In Activity(A) , you should check the order in which the program is executed .

1.Make sure that parseJson method is executed .

2.If you parse json error ,you should check JSONException.

Log.e(Constants.TAG, "parse json error");
e.printStackTrace();

3.If apkCode > versionCode is executed ,IsmType == Constants.TYPE_DIALOG executed ?

4.If apkCode < versionCode is executed ,Is mShowProgressDialog true in your code ?

And you can add Log to check it .

ed.apply();
Log.e(Constants.TAG, "SharedPreferences is apply");


问:
Garbage collection of threads
Do I need to protect Thread objects from the Garbage Collector?  What about the object that contains the function that the thread runs?

Consider this simple server:

```<code>class Server{
    readonly TcpClient client;

    public Server(TcpClient client){this.client = client;}

    public void Serve(){
        var stream = client.GetStream();
        var writer = new StreamWriter(stream);
        var reader = new StreamReader(stream);

        writer.AutoFlush = true;
        writer.WriteLine("Hello");

        while(true){
            var input = reader.ReadLine();
            if(input.Trim() == "Goodbye")
                break;
            writer.WriteLine(input.ToUpper());
        }

        client.Close();
    }
}
static void Main(string[] args){
    var listener = new TcpListener(IPAddress.Any, int.Parse(args[0]));
    listener.Start();

    while(true){
        var client = listener.AcceptTcpClient();
        var server = new Server(client);
        var thread = new Thread(server.Serve);
        thread.Start();
    }
}
</code>```

Should I wrap my thread objects in some sort of static collection to keep them from being swept up by the garbage collector?

Presumably, if the Thread object itself stays alive, then the Server object will live, because the thread holds a reference to the delegate which holds a reference to the target object.  Or maybe the thread object itself is collected, but the actual thread continues to run.  Now the Server object is up for collection.  And then what happens if it tries to access its field(s)?

Garbage collection makes my head spin some times.  I'm glad I usually don't have to think about it.

Given the potential gotchas here, I would like to believe that the garbage collector is smart enough not to collect thread objects when the thread itself is still executing, but I can't find any documentation saying so.  Reflector is of little help here, since much of the Thread class is, unsurprisingly, implemented in MethodImplOptions.InternalCall functions.  And I'd rather not dig through my old outdated copy of SSCLI for answers (both because it's a pain, and because it's not a sure answer).

答:
Despite my caution to Conrad Frix about the difficulty in proving things with test code when it comes to either multithreading or GC, let alone both, I myself threw together a simple little test.  I think the results put a satisfactory rest to this question.

The more I read the answers posted here, and the more I thought about it, the more it seemed to boil down to one specific question:

How much havoc will the Thread object's finalizer wreak when and if it runs before my thread has exited.

Obviously, the GC itself wouldn't (directly) abort the actual execution thread.  And as long as the Server object's Serve() method was executing, its this pointer should be protected as being an object locally accessible to the currently running method.

But if the GC collected and finalized the Thread object, what would happen?  Since the thread object is supposed to represent the execution thread, would its finalizer kill the execution thread, bringing them to equilibrium?  Or perhaps worse, would it destroy some internal state that the runtime uses to manage the thread?

I really didn't want to pry open Rotor to answer these questions, both because it's obtuse, and because I didn't want to rely on the SSCLI implementation; not for this.

But then I started wondering if I wasn't thinking about this somewhat backwards.  I was thinking of the Thread object as controlling the execution thread, implying that the latter would live and die with the former.

But in fact, the Thread class is merely an interface to the execution thread—a convenient abstraction.  It, instead, must live and die with the execution thread, not the other way around.

Looking at it from this perspective, I thought the framework must already do the job of keeping the abstraction alive, right?  Of course!  I'd used it a million times.  It's the Thread.CurrentThread property!

The simplest of tests revealed that the created Thread object was indeed accessible from within the framework itself:

```<code>Thread t;
t = new Thread(o=>Console.WriteLine(o == Thread.CurrentThread));
t.Start(t);
</code>```

This tiny test confirmed that, no matter whether I keep a reference to my Thread objects, the framework does.  And with that known, everything else is a given.  The Server object lives and the execution thread keeps on executing.

Yay!  I can go back to not having to think about the garbage collector for a while!

Title: Garbage collection of threads

Body:
Do I need to protect Thread objects from the Garbage Collector?  What about the object that contains the function that the thread runs?

Consider this simple server:

class Server{
    readonly TcpClient client;

    public Server(TcpClient client){this.client = client;}

    public void Serve(){
        var stream = client.GetStream();
        var writer = new StreamWriter(stream);
        var reader = new StreamReader(stream);

        writer.AutoFlush = true;
        writer.WriteLine("Hello");

        while(true){
            var input = reader.ReadLine();
            if(input.Trim() == "Goodbye")
                break;
            writer.WriteLine(input.ToUpper());
        }

        client.Close();
    }
}
static void Main(string[] args){
    var listener = new TcpListener(IPAddress.Any, int.Parse(args[0]));
    listener.Start();

    while(true){
        var client = listener.AcceptTcpClient();
        var server = new Server(client);
        var thread = new Thread(server.Serve);
        thread.Start();
    }
}

Should I wrap my thread objects in some sort of static collection to keep them from being swept up by the garbage collector?

Presumably, if the Thread object itself stays alive, then the Server object will live, because the thread holds a reference to the delegate which holds a reference to the target object.  Or maybe the thread object itself is collected, but the actual thread continues to run.  Now the Server object is up for collection.  And then what happens if it tries to access its field(s)?

Garbage collection makes my head spin some times.  I'm glad I usually don't have to think about it.

Given the potential gotchas here, I would like to believe that the garbage collector is smart enough not to collect thread objects when the thread itself is still executing, but I can't find any documentation saying so.  Reflector is of little help here, since much of the Thread class is, unsurprisingly, implemented in MethodImplOptions.InternalCall functions.  And I'd rather not dig through my old outdated copy of SSCLI for answers (both because it's a pain, and because it's not a sure answer).

Body:
Despite my caution to Conrad Frix about the difficulty in proving things with test code when it comes to either multithreading or GC, let alone both, I myself threw together a simple little test.  I think the results put a satisfactory rest to this question.

The more I read the answers posted here, and the more I thought about it, the more it seemed to boil down to one specific question:

How much havoc will the Thread object's finalizer wreak when and if it runs before my thread has exited.

Obviously, the GC itself wouldn't (directly) abort the actual execution thread.  And as long as the Server object's Serve() method was executing, its this pointer should be protected as being an object locally accessible to the currently running method.

But if the GC collected and finalized the Thread object, what would happen?  Since the thread object is supposed to represent the execution thread, would its finalizer kill the execution thread, bringing them to equilibrium?  Or perhaps worse, would it destroy some internal state that the runtime uses to manage the thread?

I really didn't want to pry open Rotor to answer these questions, both because it's obtuse, and because I didn't want to rely on the SSCLI implementation; not for this.

But then I started wondering if I wasn't thinking about this somewhat backwards.  I was thinking of the Thread object as controlling the execution thread, implying that the latter would live and die with the former.

But in fact, the Thread class is merely an interface to the execution thread—a convenient abstraction.  It, instead, must live and die with the execution thread, not the other way around.

Looking at it from this perspective, I thought the framework must already do the job of keeping the abstraction alive, right?  Of course!  I'd used it a million times.  It's the Thread.CurrentThread property!

The simplest of tests revealed that the created Thread object was indeed accessible from within the framework itself:

Thread t;
t = new Thread(o=>Console.WriteLine(o == Thread.CurrentThread));
t.Start(t);

This tiny test confirmed that, no matter whether I keep a reference to my Thread objects, the framework does.  And with that known, everything else is a given.  The Server object lives and the execution thread keeps on executing.

Yay!  I can go back to not having to think about the garbage collector for a while!


问:
service workers: async await in combination with waituntil is not working properly
i'm struggling with promises in a service worker while using async/await syntax.

Following situation: I got a push notification and want to handle the click event. If i use the "old" syntax with then and catch i can iteratore over the list of clients and do something with it. If i use my prefered way with async/await it wouldn't do anything.

```<code>self.addEventListener("notificationclick", event => {

  // is working
  event.waitUntil(self.clients.matchAll().then(clientList => {
    console.log(clientList);
  }));

  // is not working
  event.waitUntil(async () => {
    const clientList = await self.clients.matchAll();
    console.log(clientList);
  });
});
</code>```

答:
Thanks to @Crice and @Keith,

waitUntil need a promise as argument instead of a function. So this is the working example in async/await style:

```<code>self.addEventListener("notificationclick", event =>
{
    event.waitUntil(getClients());
});

async function getClients()
{
    const clientList = await self.clients.matchAll();
    console.log(clientList);
}
</code>```

Body:
i'm struggling with promises in a service worker while using async/await syntax.

Following situation: I got a push notification and want to handle the click event. If i use the "old" syntax with then and catch i can iteratore over the list of clients and do something with it. If i use my prefered way with async/await it wouldn't do anything.

self.addEventListener("notificationclick", event => {

  // is working
  event.waitUntil(self.clients.matchAll().then(clientList => {
    console.log(clientList);
  }));

  // is not working
  event.waitUntil(async () => {
    const clientList = await self.clients.matchAll();
    console.log(clientList);
  });
});

Body:
Thanks to @Crice and @Keith,

waitUntil need a promise as argument instead of a function. So this is the working example in async/await style:

self.addEventListener("notificationclick", event =>
{
    event.waitUntil(getClients());
});

async function getClients()
{
    const clientList = await self.clients.matchAll();
    console.log(clientList);
}


问:
SQL Access Sentence
I been trying to use this sentences that i made in SQL Server Management Studio, on access with no luck, after hours googling, i think they use different languages, can someone help me turn these in Access language?

```<code>select c.id_client 'Client ID',
c.client_name 'First Name'
c.client_lname 'Last Name'
from client c join bills b
on c.id_client = b.id_client join bill_detail d
on d.bill_num=b.bill_num
where month (b.date)=3
and year(b.date)= year(getdate())
group by c.id_client, c.client_name,c.client_lname
having d.price > (select avg(prirce) from bill_detail)

select s.id_seller 'Seller ID',
s.seller_name 'First Name',
s.seller_lname 'Last Name',
avg(quantity*d.price),
from sellers s join bills b
on v.id_seller=b.id_seller join bill_detail d
on b.bill_num = d.bill_num
group by s.id_seller, s.seller_name, s.seller_lname
having avg (quantity*d.price) < (select avg(quantity*d.price) from
bill_detail)

select date 'Date',
sum(quantity) 'Tickets Sold',
sum(quantity*d.price) 'Total Amount Sold',
avg(quantity*d.price) 'Average Amount Sold',
from bills b join bill_detail d
on b.bill_num = d.bill_num
group by date
</code>```

Sry, they were in spanish, hence the awfull english. And thanks in advance.

答:
Useful references:

Converting Access Queries to SQL Server

T-SQL Equivalents for Microsoft Access VBA Functions

I think these will work.. (it's been a while)

```<code>SELECT
      client.id_client    [client id]
    , client.client_name  [first name]
    , client.client_lname [last name]
FROM (client
JOIN bills ON client.id_client = bills.id_client)
JOIN bill_detail ON bill_detail.bill_num = bills.bill_num
WHERE MONTH(bills.date) = 3
AND YEAR(bills.date) = YEAR(DATE())
GROUP BY
      client.id_client
    , client.client_name
    , client.client_lname
HAVING d.price > (
      SELECT
            AVG(prirce)
      FROM bill_detail
)
;
</code>```

For some reason Access likes parentheses in the from clause. No idea why. There should be MONTH() & YEAR() . Don't recall if Access like table aliases, so I removed them and don't use single quotes for column labels (don't do this is SQL Server either).

```<code>SELECT
      sellers.id_seller    [seller id]
    , sellers.seller_name  [first name]
    , sellers.seller_lname [last name]
    , AVG(quantity * bill_detail.price)
FROM (sellers
JOIN bills ON v.id_seller = bills.id_seller)
JOIN bill_detail ON bills.bill_num = bill_detail.bill_num
GROUP BY
      sellers.id_seller
    , sellers.seller_name
    , sellers.seller_lname
HAVING AVG(quantity * bill_detail.price) < (
      SELECT
            AVG(quantity * bill_detail.price)
      FROM bill_detail
)
;
</code>```

Aside from table & column aliases changes these 2 should be ok.

```<code>SELECT
      datex                   [date]
    , SUM(quantity)           [tickets sold]
    , SUM(quantity * bill_detail.price) [total amount sold]
    , AVG(quantity * bill_detail.price) [average amount sold]
FROM (bills
JOIN bill_detail ON bills.bill_num = bill_detail.bill_num)
GROUP BY
      datex
;
</code>```

Title: SQL Access Sentence

Body:
I been trying to use this sentences that i made in SQL Server Management Studio, on access with no luck, after hours googling, i think they use different languages, can someone help me turn these in Access language?

select c.id_client 'Client ID',
c.client_name 'First Name'
c.client_lname 'Last Name'
from client c join bills b
on c.id_client = b.id_client join bill_detail d
on d.bill_num=b.bill_num
where month (b.date)=3
and year(b.date)= year(getdate())
group by c.id_client, c.client_name,c.client_lname
having d.price > (select avg(prirce) from bill_detail)

select s.id_seller 'Seller ID',
s.seller_name 'First Name',
s.seller_lname 'Last Name',
avg(quantity*d.price),
from sellers s join bills b
on v.id_seller=b.id_seller join bill_detail d
on b.bill_num = d.bill_num
group by s.id_seller, s.seller_name, s.seller_lname
having avg (quantity*d.price) < (select avg(quantity*d.price) from
bill_detail)

select date 'Date',
sum(quantity) 'Tickets Sold',
sum(quantity*d.price) 'Total Amount Sold',
avg(quantity*d.price) 'Average Amount Sold',
from bills b join bill_detail d
on b.bill_num = d.bill_num
group by date

Sry, they were in spanish, hence the awfull english. And thanks in advance.

Body:
Useful references:

Converting Access Queries to SQL Server

T-SQL Equivalents for Microsoft Access VBA Functions

I think these will work.. (it's been a while)

SELECT
      client.id_client    [client id]
    , client.client_name  [first name]
    , client.client_lname [last name]
FROM (client
JOIN bills ON client.id_client = bills.id_client)
JOIN bill_detail ON bill_detail.bill_num = bills.bill_num
WHERE MONTH(bills.date) = 3
AND YEAR(bills.date) = YEAR(DATE())
GROUP BY
      client.id_client
    , client.client_name
    , client.client_lname
HAVING d.price > (
      SELECT
            AVG(prirce)
      FROM bill_detail
)
;

For some reason Access likes parentheses in the from clause. No idea why. There should be MONTH() & YEAR() . Don't recall if Access like table aliases, so I removed them and don't use single quotes for column labels (don't do this is SQL Server either).

SELECT
      sellers.id_seller    [seller id]
    , sellers.seller_name  [first name]
    , sellers.seller_lname [last name]
    , AVG(quantity * bill_detail.price)
FROM (sellers
JOIN bills ON v.id_seller = bills.id_seller)
JOIN bill_detail ON bills.bill_num = bill_detail.bill_num
GROUP BY
      sellers.id_seller
    , sellers.seller_name
    , sellers.seller_lname
HAVING AVG(quantity * bill_detail.price) < (
      SELECT
            AVG(quantity * bill_detail.price)
      FROM bill_detail
)
;

Aside from table & column aliases changes these 2 should be ok.

SELECT
      datex                   [date]
    , SUM(quantity)           [tickets sold]
    , SUM(quantity * bill_detail.price) [total amount sold]
    , AVG(quantity * bill_detail.price) [average amount sold]
FROM (bills
JOIN bill_detail ON bills.bill_num = bill_detail.bill_num)
GROUP BY
      datex
;


问:
npm WARN npm npm does not support Node.js v9.1.0
I updated to the latest node v9.1.0 and now npm doesn't work.

npm WARN npm npm does not support Node.js v9.1.0

答:
I was getting the below warning  when I executed, npm install to install package.json for my angular project.

npm WARN npm npm does not support Node.js v9.1.0
  npm WARN npm You should probably upgrade to a newer version of node as we
  npm WARN npm can't make any promises that npm will work with this version.
  npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
  npm WARN npm You can find the latest version at https://nodejs.org/
  WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.ng-080b84bf08dd68e5.lock for ...\Angular\node
  Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
  C:\Program Files\nodejs\node.exe: src\node_zlib.cc:437: Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.

According to @Ilyich, I uninstalled global npm, npm uninstall -g npm
And then I executed npm install to install my package, it installed successfully.


问:
create nested json from plain jsons
I need to create a nested json object from a node-mysql results (json objects) here is what I'm trying to acomplish

Those are the mysql json objects that I have:

```<code>plants:
[{id: 1, name: 'plant 1'},
{id: 2, name: 'plant 2'}]

areas:
[{id: 1, nombre: 'area 1', plants_id: 1 },
{ id: 2, nombre: 'area 1 - plant 2', plantas_id: 2 },
{ id: 3, nombre: 'area n', plantas_id: 1 }]

machines:
[{id: 1, nombre: 'machine 1 - area 1', areas_id: 1 },
{ id: 2, nombre: 'machine 1 - area 2', areas_id: 2 },
{ id: 3, nombre: 'machine n', areas_id: 2 }]
</code>```

And this the json that I need to create with the values of the previous json:

```<code>{
  "plants":[
    {
      "name":"plant 1",
      "areas": [
        { "name":"area 1",
          "machines":[
            {"nombre":"machine 1 - area 1"
          }]
        },
        { "nombre":"area 2",
          "machines":[
            {"nombre":"machine 1 - area 2"
          }]
        }
      ]
    },
    {
      "name":"plant 2",
      "areas": [
        { "nombre":"area 1 - plant 2",
          "maquinas":[ ]
        }
      ]
    }
  ]
}
</code>```

I've been trying with nested for loops but it's a mess, I read about linq but I have never worked with it

Sorry for the bad english. Any help is appreciated

Thanks and regards

答:
This isn't an efficient solution but if your dataset is small, it works.

var plants = [
    { id: 1, name: 'plant 1' },
    { id: 2, name: 'plant 2' },
];

var areas = [
    { id: 1, nombre: 'area 1', plantas_id: 1 }, // there was a spelling mistake here
    { id: 2, nombre: 'area 1 - plant 2', plantas_id: 2 },
    { id: 3, nombre: 'area n', plantas_id: 1 },
];

var machines = [
    { id: 1, nombre: 'machine 1 - area 1', areas_id: 1 },
    { id: 2, nombre: 'machine 1 - area 2', areas_id: 2 },
    { id: 3, nombre: 'machine n', areas_id: 2 },
];

console.time('result');

function result() {
    return plants.map(function(plant) {
        return {
            "name": plant.name,
            "areas": areas.filter(function(area) {
                return area.plantas_id == plant.id;
            }).map(function(area) {
                return {
                    "nombre": area.nombre,
                    "machines": machines.filter(function(machine) {
                        return machine.areas_id == area.id;
                    }).map(function(machine) {
                        return {
                            "nombre": machine.nombre,
                        };
                    }),
                };
            }),
        };
    });
}

console.timeEnd('result');
console.log(result());```

Title: create nested json from plain jsons

Body:
I need to create a nested json object from a node-mysql results (json objects) here is what I'm trying to acomplish

Those are the mysql json objects that I have:

plants:
[{id: 1, name: 'plant 1'},
{id: 2, name: 'plant 2'}]

areas:
[{id: 1, nombre: 'area 1', plants_id: 1 },
{ id: 2, nombre: 'area 1 - plant 2', plantas_id: 2 },
{ id: 3, nombre: 'area n', plantas_id: 1 }]

machines:
[{id: 1, nombre: 'machine 1 - area 1', areas_id: 1 },
{ id: 2, nombre: 'machine 1 - area 2', areas_id: 2 },
{ id: 3, nombre: 'machine n', areas_id: 2 }]

And this the json that I need to create with the values of the previous json:

{
  "plants":[
    {
      "name":"plant 1",
      "areas": [
        { "name":"area 1",
          "machines":[
            {"nombre":"machine 1 - area 1"
          }]
        },
        { "nombre":"area 2",
          "machines":[
            {"nombre":"machine 1 - area 2"
          }]
        }
      ]
    },
    {
      "name":"plant 2",
      "areas": [
        { "nombre":"area 1 - plant 2",
          "maquinas":[ ]
        }
      ]
    }
  ]
}

I've been trying with nested for loops but it's a mess, I read about linq but I have never worked with it

Sorry for the bad english. Any help is appreciated

Thanks and regards


问:
Java - possible to modify and parse gzipped xml files without unzipping?
I have an arraylist of gzipped xml files. Is it possible to view and manipulate the contents of these xml files all without unzipping them and taking up disk space? If so, what would be the correct class(es) to use for this task?

I know I can create a gzipinputstream from a fileinputstream of the zip file but from there I'm not sure what to do. I have only this written:

```<code> GZIPInputStream in = new GZIPInputStream(new FileInputStream(zippedFiles.get(i)));
</code>```

I need some way to parse text within the xml files and modify the xml itself but again, extracting all of them would take up too much disk space.

答:
The fact that they're in a list doesn't change much, but no.

Ignoring compression, files are stored linearly on disks. You can append to them cheaply, you can replace bytes cheaply, but you can't replace sequences of different lengths (like replace("Testing Procedure Specification", "TPS")) without rewriting the file after the modified substring.

Gziping the file complicates things, but the same rule applies. In general, making arbitrary modifications to a file requires rewriting the file.

Your code for reading the files is on the right track, though. You can easily read through gziped files as streams and without having to decompress the entire file.

Body:
I have an arraylist of gzipped xml files. Is it possible to view and manipulate the contents of these xml files all without unzipping them and taking up disk space? If so, what would be the correct class(es) to use for this task?

I know I can create a gzipinputstream from a fileinputstream of the zip file but from there I'm not sure what to do. I have only this written:

 GZIPInputStream in = new GZIPInputStream(new FileInputStream(zippedFiles.get(i)));

I need some way to parse text within the xml files and modify the xml itself but again, extracting all of them would take up too much disk space.


问:
Mocking Rspec any_instance_of method return value relative to instance's actual args
I'm running into an issue where I'm trying to mock out an async method in a service class, but I want the result set to be based on the inputs to the call.

eg:

allow_any_instance_of(Emails::EmailService)
  .to receive(:send_many_async)
  .and_wrap_original { |m, *args| args[1].map { |recipient| Emails::EmailResult.new(recipient.email) } }
```

<p>The signature for this method is <code>send_many_async(email, users)</code> </p>

<p>I don't think that <code>and_wrap_original</code> is behaving as I expect though, as when I print out the values for <code>m</code> and <code>args</code> I see:</p>

<pre class="lang-ruby prettyprint-override"><code>#<Method: Emails::EmailService#__send_many_async_without_any_instance__(send_many_async)>
#<Emails::EmailService:0x007fa5c4e1b448>
#<Emails::MyEmail:0x007fa5c4e1b4e8>
</code>```

As in, where I would expect arg[0] to be the email object, and arg[1] to be the list of users -- instead arg[0] is the service I'm mocking and there is no users list at all (eg: an arg[2])

I effectively just want to confirm the method is called, and that the users are the count I expect them to be.

Alternatively, if I could substitute the method for another on the same class that would work too (the non-async call) but I haven't been able to find a way to replace :send_many_async with the regular :send_many which is successfully mocked in another way (that I cannot apply here)

Anyone succeed doing something like this? I was expecting and_wrap_original to provide what was passed into the instance's method, but clearly I am confused in this regard.

Edit

If anyone is wondering, here's a working test sample. It's unfortunately not working for me quite yet in my application but others may find it helpful.

class TestEmailSvc
  def send_many_async(email, to_email_users, from_email_user: nil, send_at: nil)
    puts 'Real one called!'
  end
end

class TestEmail
end

class TestEmailUser
  attr_reader :email
  def initialize(email)
    @email = email
  end
end

class TestEmailResult
  attr_reader :user
  def initialize(user)
    @user = user
  end

  def status
    :pending
  end
end

describe 'Test Spec' do

  it 'tests my mock' do
    allow_any_instance_of(TestEmailSvc)
      .to receive(:send_many_async)
        .and_wrap_original { |m, _, args| args.map { |recipient| TestEmailResult.new(recipient) } }

    svc = TestEmailSvc.new

    users = [
      TestEmailUser.new('email 1'),
      TestEmailUser.new('email 2')
    ]

    results = svc.send_many_async(TestEmail.new, users)

    expect(results.count).to eql 2
  end

end
```

答:
When you use allow_any_instance_of(...).to receive(...).and_wrap_original, the block receives the following:

The original method

The instance that received the message (in case you want to use any of the state of the instance in your block)

The arguments passed by the caller, in order

In your case, it sounds like you don't need to use the EmailService instance in your block, so you can just ignore that argument:

```<code>allow_any_instance_of(Emails::EmailService)
  .to receive(:send_many_async)
  .and_wrap_original { |m, _, *args| args[1].map { |recipient| Emails::EmailResult.new(recipient.email) } }
</code>```

Alternately, I'd encourage you to consider if there's a way to improve the interface of Emails::EmailService so that you don't need to use any_instance (which suffers from these sorts of confusing usability problems and also tends to calcify existing designs instead of putting pressure on your design).  We talk about this in my book Effective Testing with RSpec 3: Build Ruby Apps with Confidence.

Body:
I'm running into an issue where I'm trying to mock out an async method in a service class, but I want the result set to be based on the inputs to the call.

eg:

allow_any_instance_of(Emails::EmailService)
  .to receive(:send_many_async)
  .and_wrap_original { |m, *args| args[1].map { |recipient| Emails::EmailResult.new(recipient.email) } }

The signature for this method is send_many_async(email, users)

I don't think that and_wrap_original is behaving as I expect though, as when I print out the values for m and args I see:

#<Method: Emails::EmailService#__send_many_async_without_any_instance__(send_many_async)>
#<Emails::EmailService:0x007fa5c4e1b448>
#<Emails::MyEmail:0x007fa5c4e1b4e8>

As in, where I would expect arg[0] to be the email object, and arg[1] to be the list of users -- instead arg[0] is the service I'm mocking and there is no users list at all (eg: an arg[2])

I effectively just want to confirm the method is called, and that the users are the count I expect them to be.

Alternatively, if I could substitute the method for another on the same class that would work too (the non-async call) but I haven't been able to find a way to replace :send_many_async with the regular :send_many which is successfully mocked in another way (that I cannot apply here)

Anyone succeed doing something like this? I was expecting and_wrap_original to provide what was passed into the instance's method, but clearly I am confused in this regard.

Edit

If anyone is wondering, here's a working test sample. It's unfortunately not working for me quite yet in my application but others may find it helpful.

class TestEmailSvc
  def send_many_async(email, to_email_users, from_email_user: nil, send_at: nil)
    puts 'Real one called!'
  end
end

class TestEmail
end

class TestEmailUser
  attr_reader :email
  def initialize(email)
    @email = email
  end
end

class TestEmailResult
  attr_reader :user
  def initialize(user)
    @user = user
  end

  def status
    :pending
  end
end

describe 'Test Spec' do

  it 'tests my mock' do
    allow_any_instance_of(TestEmailSvc)
      .to receive(:send_many_async)
        .and_wrap_original { |m, _, args| args.map { |recipient| TestEmailResult.new(recipient) } }

    svc = TestEmailSvc.new

    users = [
      TestEmailUser.new('email 1'),
      TestEmailUser.new('email 2')
    ]

    results = svc.send_many_async(TestEmail.new, users)

    expect(results.count).to eql 2
  end

end

Body:
When you use allow_any_instance_of(...).to receive(...).and_wrap_original, the block receives the following:

The original method

The instance that received the message (in case you want to use any of the state of the instance in your block)

The arguments passed by the caller, in order

In your case, it sounds like you don't need to use the EmailService instance in your block, so you can just ignore that argument:

allow_any_instance_of(Emails::EmailService)
  .to receive(:send_many_async)
  .and_wrap_original { |m, _, *args| args[1].map { |recipient| Emails::EmailResult.new(recipient.email) } }

Alternately, I'd encourage you to consider if there's a way to improve the interface of Emails::EmailService so that you don't need to use any_instance (which suffers from these sorts of confusing usability problems and also tends to calcify existing designs instead of putting pressure on your design).  We talk about this in my book Effective Testing with RSpec 3: Build Ruby Apps with Confidence.


问:
Dynamically Displaying Text with TextView (Android)
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

```<code>    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);
</code>```

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.

答:
There are two options for you.

One is

Spannable

and other is

fromHtml (String source)

So that you can get your desired output.

Body:
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.


问:
Difference in time based on time records and subequent time records from same table
I placed a sample of some data on SQLFiddle where I'm trying to figure out how to build a query from this data that will give:

The TIMEDIFF() of the TimeStr field of the scl1_fill table and the very next sc1_weight table TimeStr field

example: SELECT TIMEDIFF('2017-11-14 07:21:29','2017-11-14 07:15:56')

I think I need to emulate ROW_NUMBER() with MySQL and I always seem to have trouble with that for some reason using variables and sub queries to get the row numbers, etc.

I tried quite a few things and came up short every time so not even sure it's worth showing what I tried so I will provide what I have and the expected results for visualization/clarification.

Essentially when the sc1_fill gets a 1 value the device starts to fill and when the sc1_weight gets any value then that means it met the weight setpoint and gives back a value at that point.

Getting the time difference between the two will show the amount of time it took from the time the sc1_fill started until the very next record time wise the sc1_weight gets any value ran.

I figured I could throw this as a value on the sc1_weight records with the TIMEDIFF() and have a new column and have all other records show NULL and that'd work (see Expected Results).

Full Table Data

(Always and only get data from one specific date so e.g. WHERE TimeStr LIKE '2017-11-14%')

```<code>| test_tbl |               TimeStr |   Value |
----------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650
sc1_disch       2017-11-14 07:10:24     1
sc1_fill        2017-11-14 07:15:56     1
sc1_weight      2017-11-14 07:21:29     651
sc1_disch       2017-11-14 07:26:18     1
sc1_fill        2017-11-14 07:27:32     1
sc1_weight      2017-11-14 07:33:07     650
sc1_disch       2017-11-14 08:18:36     1
sc1_fill        2017-11-14 08:19:53     1
sc1_weight      2017-11-14 08:25:29     651
sc1_disch       2017-11-14 08:30:21     1
sc1_fill        2017-11-14 08:31:39     1
sc1_weight      2017-11-14 08:37:20     650
sc1_disch       2017-11-14 08:46:00     1
sc1_fill        2017-11-14 08:47:17     1
sc1_weight      2017-11-14 08:52:50     649
sc1_disch       2017-11-14 09:03:22     1
sc1_fill        2017-11-14 09:04:36     1
sc1_weight      2017-11-14 09:10:10     651
sc1_disch       2017-11-14 09:18:45     1
sc1_fill        2017-11-14 09:20:35     1
sc1_weight      2017-11-14 09:26:11     650
sc1_disch       2017-11-14 09:36:40     1
sc1_fill        2017-11-14 09:37:59     1
sc1_weight      2017-11-14 09:43:39     650
sc1_disch       2017-11-14 09:46:55     1
sc1_fill        2017-11-14 09:53:49     1
sc1_weight      2017-11-14 09:59:42     650
sc1_disch       2017-11-14 10:36:06     1
sc1_fill        2017-11-14 10:37:27     1
sc1_weight      2017-11-14 10:43:14     650
sc1_disch       2017-11-14 10:50:44     1
sc1_fill        2017-11-14 10:52:01     1
sc1_weight      2017-11-14 10:57:47     650
sc1_disch       2017-11-14 11:05:46     1
sc1_fill        2017-11-14 11:07:19     1
sc1_weight      2017-11-14 11:12:48     650
sc1_disch       2017-11-14 11:25:25     1
sc1_fill        2017-11-14 11:36:18     1
sc1_fill        2017-11-14 11:39:12     1
sc1_fill        2017-11-14 11:45:26     1
sc1_weight      2017-11-14 11:50:39     651
sc1_disch       2017-11-14 12:00:45     1
sc1_fill        2017-11-14 12:04:44     1
sc1_weight      2017-11-14 12:10:16     651
sc1_disch       2017-11-14 12:58:48     1
sc1_fill        2017-11-14 13:00:01     1
sc1_weight      2017-11-14 13:05:23     651
sc1_disch       2017-11-14 13:06:19     1
sc1_fill        2017-11-14 13:10:52     1
sc1_weight      2017-11-14 13:16:19     650
sc1_disch       2017-11-14 13:18:27     1
sc1_fill        2017-11-14 13:24:35     1
sc1_weight      2017-11-14 13:30:01     651
sc1_disch       2017-11-14 13:31:35     1
sc1_fill        2017-11-14 13:35:40     1
sc1_weight      2017-11-14 13:41:05     650
sc1_disch       2017-11-14 13:47:04     1
sc1_fill        2017-11-14 13:50:19     1
sc1_weight      2017-11-14 13:55:43     649
sc1_disch       2017-11-14 14:06:57     1
sc1_fill        2017-11-14 14:08:11     1
sc1_weight      2017-11-14 14:13:32     651
sc1_disch       2017-11-14 14:26:10     1
sc1_fill        2017-11-14 14:27:24     1
sc1_weight      2017-11-14 14:32:49     650
sc1_disch       2017-11-14 14:42:00     1
sc1_fill        2017-11-14 14:43:11     1
sc1_weight      2017-11-14 14:48:25     650
</code>```

Expected Results

```<code>| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650              NULL
sc1_disch       2017-11-14 07:10:24     1                NULL
sc1_fill        2017-11-14 07:15:56     1                NULL
sc1_weight      2017-11-14 07:21:29     651          00:05:33
sc1_disch       2017-11-14 07:26:18     1                NULL
sc1_fill        2017-11-14 07:27:32     1                NULL
sc1_weight      2017-11-14 07:33:07     650          00:05:35
sc1_disch       2017-11-14 08:18:36     1                NULL
sc1_fill        2017-11-14 08:19:53     1                NULL
sc1_weight      2017-11-14 08:25:29     651          00:05:36
sc1_disch       2017-11-14 08:30:21     1                NULL
sc1_fill        2017-11-14 08:31:39     1                NULL
sc1_weight      2017-11-14 08:37:20     650         00:05:41
sc1_disch       2017-11-14 08:46:00     1                NULL
</code>```

Making Matters Worse

Okay to make matters worse, it seems at times there are multiple sc1_fill values of 1 before the subsequent sc1_weight value but I would only need to calculate the most recent or newest TimeStr of the set to get the fill time (e.g. SELECT TIMEDIFF('2017-11-14 11:50:39','2017-11-14 11:45:26'))

Expected results where this is the case

```<code>| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_fill        2017-11-14 11:36:18     1               NULL
sc1_fill        2017-11-14 11:39:12     1               NULL
sc1_fill        2017-11-14 11:45:26     1               NULL
sc1_weight      2017-11-14 11:50:39     651         00:05:13
sc1_disch       2017-11-14 12:00:45     1               NULL
</code>```

答:
You can use a correlated subquery:

```<code>select t.*,
       (select t2.TimeStr
        from Detail t2
        where t2.TimeStr < t.TimeStr and
              t2.tbl = 'sc1_fill' and t2.value = 1
        order by t2.TimeStr desc
        limit 1
       ) as prev_timestamp
from Detail t
where t.tbl = 'sc1_weight';
</code>```

You can then get the time difference from timestamp and prev_timestamp.

Here is the SQL Fiddle.

Body:
I placed a sample of some data on SQLFiddle where I'm trying to figure out how to build a query from this data that will give:

The TIMEDIFF() of the TimeStr field of the scl1_fill table and the very next sc1_weight table TimeStr field

example: SELECT TIMEDIFF('2017-11-14 07:21:29','2017-11-14 07:15:56')

I think I need to emulate ROW_NUMBER() with MySQL and I always seem to have trouble with that for some reason using variables and sub queries to get the row numbers, etc.

I tried quite a few things and came up short every time so not even sure it's worth showing what I tried so I will provide what I have and the expected results for visualization/clarification.

Essentially when the sc1_fill gets a 1 value the device starts to fill and when the sc1_weight gets any value then that means it met the weight setpoint and gives back a value at that point.

Getting the time difference between the two will show the amount of time it took from the time the sc1_fill started until the very next record time wise the sc1_weight gets any value ran.

I figured I could throw this as a value on the sc1_weight records with the TIMEDIFF() and have a new column and have all other records show NULL and that'd work (see Expected Results).

Full Table Data

(Always and only get data from one specific date so e.g. WHERE TimeStr LIKE '2017-11-14%')

| test_tbl |               TimeStr |   Value |
----------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650
sc1_disch       2017-11-14 07:10:24     1
sc1_fill        2017-11-14 07:15:56     1
sc1_weight      2017-11-14 07:21:29     651
sc1_disch       2017-11-14 07:26:18     1
sc1_fill        2017-11-14 07:27:32     1
sc1_weight      2017-11-14 07:33:07     650
sc1_disch       2017-11-14 08:18:36     1
sc1_fill        2017-11-14 08:19:53     1
sc1_weight      2017-11-14 08:25:29     651
sc1_disch       2017-11-14 08:30:21     1
sc1_fill        2017-11-14 08:31:39     1
sc1_weight      2017-11-14 08:37:20     650
sc1_disch       2017-11-14 08:46:00     1
sc1_fill        2017-11-14 08:47:17     1
sc1_weight      2017-11-14 08:52:50     649
sc1_disch       2017-11-14 09:03:22     1
sc1_fill        2017-11-14 09:04:36     1
sc1_weight      2017-11-14 09:10:10     651
sc1_disch       2017-11-14 09:18:45     1
sc1_fill        2017-11-14 09:20:35     1
sc1_weight      2017-11-14 09:26:11     650
sc1_disch       2017-11-14 09:36:40     1
sc1_fill        2017-11-14 09:37:59     1
sc1_weight      2017-11-14 09:43:39     650
sc1_disch       2017-11-14 09:46:55     1
sc1_fill        2017-11-14 09:53:49     1
sc1_weight      2017-11-14 09:59:42     650
sc1_disch       2017-11-14 10:36:06     1
sc1_fill        2017-11-14 10:37:27     1
sc1_weight      2017-11-14 10:43:14     650
sc1_disch       2017-11-14 10:50:44     1
sc1_fill        2017-11-14 10:52:01     1
sc1_weight      2017-11-14 10:57:47     650
sc1_disch       2017-11-14 11:05:46     1
sc1_fill        2017-11-14 11:07:19     1
sc1_weight      2017-11-14 11:12:48     650
sc1_disch       2017-11-14 11:25:25     1
sc1_fill        2017-11-14 11:36:18     1
sc1_fill        2017-11-14 11:39:12     1
sc1_fill        2017-11-14 11:45:26     1
sc1_weight      2017-11-14 11:50:39     651
sc1_disch       2017-11-14 12:00:45     1
sc1_fill        2017-11-14 12:04:44     1
sc1_weight      2017-11-14 12:10:16     651
sc1_disch       2017-11-14 12:58:48     1
sc1_fill        2017-11-14 13:00:01     1
sc1_weight      2017-11-14 13:05:23     651
sc1_disch       2017-11-14 13:06:19     1
sc1_fill        2017-11-14 13:10:52     1
sc1_weight      2017-11-14 13:16:19     650
sc1_disch       2017-11-14 13:18:27     1
sc1_fill        2017-11-14 13:24:35     1
sc1_weight      2017-11-14 13:30:01     651
sc1_disch       2017-11-14 13:31:35     1
sc1_fill        2017-11-14 13:35:40     1
sc1_weight      2017-11-14 13:41:05     650
sc1_disch       2017-11-14 13:47:04     1
sc1_fill        2017-11-14 13:50:19     1
sc1_weight      2017-11-14 13:55:43     649
sc1_disch       2017-11-14 14:06:57     1
sc1_fill        2017-11-14 14:08:11     1
sc1_weight      2017-11-14 14:13:32     651
sc1_disch       2017-11-14 14:26:10     1
sc1_fill        2017-11-14 14:27:24     1
sc1_weight      2017-11-14 14:32:49     650
sc1_disch       2017-11-14 14:42:00     1
sc1_fill        2017-11-14 14:43:11     1
sc1_weight      2017-11-14 14:48:25     650

Expected Results

| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650              NULL
sc1_disch       2017-11-14 07:10:24     1                NULL
sc1_fill        2017-11-14 07:15:56     1                NULL
sc1_weight      2017-11-14 07:21:29     651          00:05:33
sc1_disch       2017-11-14 07:26:18     1                NULL
sc1_fill        2017-11-14 07:27:32     1                NULL
sc1_weight      2017-11-14 07:33:07     650          00:05:35
sc1_disch       2017-11-14 08:18:36     1                NULL
sc1_fill        2017-11-14 08:19:53     1                NULL
sc1_weight      2017-11-14 08:25:29     651          00:05:36
sc1_disch       2017-11-14 08:30:21     1                NULL
sc1_fill        2017-11-14 08:31:39     1                NULL
sc1_weight      2017-11-14 08:37:20     650         00:05:41
sc1_disch       2017-11-14 08:46:00     1                NULL

Making Matters Worse

Okay to make matters worse, it seems at times there are multiple sc1_fill values of 1 before the subsequent sc1_weight value but I would only need to calculate the most recent or newest TimeStr of the set to get the fill time (e.g. SELECT TIMEDIFF('2017-11-14 11:50:39','2017-11-14 11:45:26'))

Expected results where this is the case

| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_fill        2017-11-14 11:36:18     1               NULL
sc1_fill        2017-11-14 11:39:12     1               NULL
sc1_fill        2017-11-14 11:45:26     1               NULL
sc1_weight      2017-11-14 11:50:39     651         00:05:13
sc1_disch       2017-11-14 12:00:45     1               NULL

Body:
You can use a correlated subquery:

select t.*,
       (select t2.TimeStr
        from Detail t2
        where t2.TimeStr < t.TimeStr and
              t2.tbl = 'sc1_fill' and t2.value = 1
        order by t2.TimeStr desc
        limit 1
       ) as prev_timestamp
from Detail t
where t.tbl = 'sc1_weight';

You can then get the time difference from timestamp and prev_timestamp.

Here is the SQL Fiddle.


问:
JS - Object Constructor Methods
I am trying to make an object that includes the teams points (as shown below where it says "this.update"). When I run the program it does not seem to give the points to the teams and it does not seem to even evaluate both teams' goals.

I want the team1Points and team2Points properties to be derived from an IF statement like the one above or another solution would help, akin to the 1 point to both teams for a draw, 3 points for a win, 0 for a loss.

teamsArray = ["Blue Team", "Red Team"];

function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.update = function() {
    if (team1Goals > team2Goals) {
      team1Points = 3;
      team2Points = 0;
    } else if (team2Goals > team1Goals) {
      team2Points = 3;
      team1Points = 0;
    } else if (team1Goals == team2Goals) {
      team1Points = 1;
      team2Points = 1;
    }
  };
  this.update();
}

testMatch();

function testMatch() {
  var match1 = new match(teamsArray[0], teamsArray[1], 2, 0);
  console.log(match1);
}```

答:
Your method creates global variables instead of properties, and you never even called it!

In order to avoid issues like this, I suggest switching to the modern JavaScript syntax. Begin your scripts with the instruction 'use strict'; to enable strict mode and define variables using let instead of var. If you do that, the browser won't let you define global variables from within a function.

As for the solution to your code:

```<code>function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.team1Points = this.team2Points = 0;

  this.update = function() {
    if (this.team1Goals > this.team2Goals) {
      this.team1Points = 3;
      this.team2Points = 0;
    } else if (this.team2Goals > this.team1Goals) {
      this.team2Points = 3;
      this.team1Points = 0;
    } else if (this.team1Goals == this.team2Goals) {
      this.team1Points = 1;
      this.team2Points = 1;
    }
  };
}
</code>```

And don't forget to call .update() somewhere.

```<code>m = new match("Alpha", "Beta", 0, 2);
m.update();

console.log("Team " + m.team1Name + " has " + m.team1Points + " points.");
console.log("Team " + m.team2Name + " has " + m.team2Points + " points.");
</code>```

Title: JS - Object Constructor Methods

Body:
Your method creates global variables instead of properties, and you never even called it!

In order to avoid issues like this, I suggest switching to the modern JavaScript syntax. Begin your scripts with the instruction 'use strict'; to enable strict mode and define variables using let instead of var. If you do that, the browser won't let you define global variables from within a function.

As for the solution to your code:

function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.team1Points = this.team2Points = 0;

  this.update = function() {
    if (this.team1Goals > this.team2Goals) {
      this.team1Points = 3;
      this.team2Points = 0;
    } else if (this.team2Goals > this.team1Goals) {
      this.team2Points = 3;
      this.team1Points = 0;
    } else if (this.team1Goals == this.team2Goals) {
      this.team1Points = 1;
      this.team2Points = 1;
    }
  };
}

And don't forget to call .update() somewhere.

m = new match("Alpha", "Beta", 0, 2);
m.update();

console.log("Team " + m.team1Name + " has " + m.team1Points + " points.");
console.log("Team " + m.team2Name + " has " + m.team2Points + " points.");


问:
Increasing and decreasing value of the clicks of the button
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="Button" id="bt" /></code>```

答:
On your html:

lets say you have 50 of these

```<code><button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>
</code>```

and on your javascript

```<code>var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
  button.addEventListener('click', function() {
    if (this.dataset.clicked == 'false') {
      this.dataset.clicked = 'true';
      this.innerHTML = parseInt(this.innerHTML) + 1;
    }
    else {
      this.dataset.clicked = 'false'
      this.innerHTML = parseInt(this.innerHTML) - 1;
    }
  })
});
</code>```

EDIT: Here is a working fiddle

Body:
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}

<input type="Button" id="bt" />

Body:
On your html:

lets say you have 50 of these

<button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>

and on your javascript

var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
  button.addEventListener('click', function() {
    if (this.dataset.clicked == 'false') {
      this.dataset.clicked = 'true';
      this.innerHTML = parseInt(this.innerHTML) + 1;
    }
    else {
      this.dataset.clicked = 'false'
      this.innerHTML = parseInt(this.innerHTML) - 1;
    }
  })
});

EDIT: Here is a working fiddle


问:
upgraded rails 3 app rake db:reset error
I upgraded my rails 2.3.8 app to rails 3. when I run the rake db:reset command, it returns the following error

rake aborted!
test-unit is not part of the bundle. Add it to Gemfile.
/Users/Shenario/Desktop/stack24/Rakefile:7:in `'
(See full trace by running task with --trace)

i'm new to rails, and wud be glad if you guys out ther coud help me! thanks!

the trace --

rake aborted!
test-unit is not part of the bundle. Add it to Gemfile.
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/bundler-1.0.7/lib/bundler/shared_helpers.rb:102:in block in cripple_rubygems'
/Users/Shenario/Desktop/stack24/lib/tasks/rspec.rake:1:in'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/engine.rb:131:in load'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/engine.rb:131:inblock in load_tasks'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/engine.rb:131:in each'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/engine.rb:131:inload_tasks'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:141:in load_tasks'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:77:inmethod_missing'
/Users/Shenario/Desktop/stack24/Rakefile:7:in <top (required)>'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2383:inload'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2383:in raw_load_rakefile'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2017:inblock in load_rakefile'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2068:in standard_exception_handling'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2016:inload_rakefile'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2000:in block in run'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:2068:instandard_exception_handling'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/lib/rake.rb:1998:in run'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/gems/rake-0.8.7/bin/rake:31:in'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/bin/rake:19:in load'
/Users/Shenario/.rvm/gems/ruby-1.9.2-p136/bin/rake:19:in'

答:
After searching for "test-unit", found this:

```<code>gem 'test-unit', '2.0.7' if RUBY_VERSION.to_f >= 1.9
</code>```

in lib/tasks/rspec.rake

I suspected it was caused by me copying the whole lib folder from older rails version to this new one.

Solution: removed that file, then things seem to work fine after.

Basically I suggest you look at lib/tasks and see if there are rake tasks that are incompatible with rails 3.

Body:
After searching for "test-unit", found this:

gem 'test-unit', '2.0.7' if RUBY_VERSION.to_f >= 1.9

in lib/tasks/rspec.rake

I suspected it was caused by me copying the whole lib folder from older rails version to this new one.

Solution: removed that file, then things seem to work fine after.

Basically I suggest you look at lib/tasks and see if there are rake tasks that are incompatible with rails 3.