问:
Corrupt IE object (IE automation with Powershell)
I want to automate an accesspoint configuration on the web console with Powershell.

I developed on Win8/IE10 and everything works fine when testing the code.
Unfortunately I received the "productive system" after development/tests.
Now the code should work on Windows Server 2012 R2/IE11.

This is my code for connecting and login to the accesspoint (simplified):

```<code>$IE = New-Object -ComObject "InternetExplorer.Application"
$IE.Visible = $true #1#
$IE.Navigate("192.168.0.100")
Write-Host $IE.LocationName

$IE.Document.GetElementByID("login-username").Value = "admin"
$IE.Document.GetElementByID("login-password").Value = "admin"
$IE.Document.GetElementByID("login-btn").Click()
Write-Host $IE.LocationName
</code>```

For debugging reasons normally I show the window (comment #1#).
At first Write-Host, the correct location is shown ("Login").
At second Write-Host, the wrong location is shown ("about:blank").
In the IE window you see the right location/tabname ("AP").
Seems like the IE object become unuseable, other properties (like $IE.Document.*) does not work then. I have to close the window manually.

I have two workarounds:

When I click (get focus) on the IE window manually before login, it
works.

When I don't  show the windows ($IE.Visible = $false), also
everything works.

My scenario/tests so far:

IE ESC is disabled.

I copied the C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll from another productive machine (2008R2), so $IE.Document functions would work (dll from my develop machine produces the same error).

I tried to enable/disable protected mode (Internet options > Security) for every zone, does not work for me (found on reddit)

Does someone else have an idea to try?
Debugging works with workaround, productive it also works (so far) with unvisible window - but I want to understand the troubles...

Thanks, best regards,
kvo

答:
I came across this issue once I deployed my scripts to windows server 2012 which runs on IE11.

The cause for this is losing the handler for the IE object created by Powershell.

I used the following snippet, authored in, PowerShell IE9 ComObject has all null properties after navigating to webpage for resolving this issue.

```<code>function ConnectIExplorer() {
    param($HWND)

    $objShellApp = New-Object -ComObject Shell.Application
    try {
      $EA = $ErrorActionPreference; $ErrorActionPreference = 'Stop'
      $objNewIE = $objShellApp.Windows() | ?{$_.HWND -eq $HWND}
      $objNewIE.Visible = $true
    } catch {
      #it may happen, that the Shell.Application does not find the window in a timely-manner, therefore quick-sleep and try again
      Write-Host "Waiting for page to be loaded ..."
      Start-Sleep -Milliseconds 500
      try {
        $objNewIE = $objShellApp.Windows() | ?{$_.HWND -eq $HWND}
        $objNewIE.Visible = $true
      } catch {
        Write-Host "Could not retreive the -com Object InternetExplorer. Aborting." -ForegroundColor Red
        $objNewIE = $null
      }
    } finally {
      $ErrorActionPreference = $EA
      $objShellApp = $null
    }
    return $objNewIE
  }

$HWND = ($objIE = New-Object -ComObject InternetExplorer.Application).HWND
$objIE.Navigate("https://www.google.com")
$objIE = ConnectIExplorer -HWND $HWND
</code>```

Body:
I want to automate an accesspoint configuration on the web console with Powershell.

I developed on Win8/IE10 and everything works fine when testing the code.
Unfortunately I received the "productive system" after development/tests.
Now the code should work on Windows Server 2012 R2/IE11.

This is my code for connecting and login to the accesspoint (simplified):

$IE = New-Object -ComObject "InternetExplorer.Application"
$IE.Visible = $true #1#
$IE.Navigate("192.168.0.100")
Write-Host $IE.LocationName

$IE.Document.GetElementByID("login-username").Value = "admin"
$IE.Document.GetElementByID("login-password").Value = "admin"
$IE.Document.GetElementByID("login-btn").Click()
Write-Host $IE.LocationName

For debugging reasons normally I show the window (comment #1#).
At first Write-Host, the correct location is shown ("Login").
At second Write-Host, the wrong location is shown ("about:blank").
In the IE window you see the right location/tabname ("AP").
Seems like the IE object become unuseable, other properties (like $IE.Document.*) does not work then. I have to close the window manually.

I have two workarounds:

When I click (get focus) on the IE window manually before login, it
works.

When I don't  show the windows ($IE.Visible = $false), also
everything works.

My scenario/tests so far:

IE ESC is disabled.

I copied the C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll from another productive machine (2008R2), so $IE.Document functions would work (dll from my develop machine produces the same error).

I tried to enable/disable protected mode (Internet options > Security) for every zone, does not work for me (found on reddit)

Does someone else have an idea to try?
Debugging works with workaround, productive it also works (so far) with unvisible window - but I want to understand the troubles...

Thanks, best regards,
kvo

Body:
I came across this issue once I deployed my scripts to windows server 2012 which runs on IE11.

The cause for this is losing the handler for the IE object created by Powershell.

I used the following snippet, authored in, PowerShell IE9 ComObject has all null properties after navigating to webpage for resolving this issue.

function ConnectIExplorer() {
    param($HWND)

    $objShellApp = New-Object -ComObject Shell.Application
    try {
      $EA = $ErrorActionPreference; $ErrorActionPreference = 'Stop'
      $objNewIE = $objShellApp.Windows() | ?{$_.HWND -eq $HWND}
      $objNewIE.Visible = $true
    } catch {
      #it may happen, that the Shell.Application does not find the window in a timely-manner, therefore quick-sleep and try again
      Write-Host "Waiting for page to be loaded ..."
      Start-Sleep -Milliseconds 500
      try {
        $objNewIE = $objShellApp.Windows() | ?{$_.HWND -eq $HWND}
        $objNewIE.Visible = $true
      } catch {
        Write-Host "Could not retreive the -com Object InternetExplorer. Aborting." -ForegroundColor Red
        $objNewIE = $null
      }
    } finally {
      $ErrorActionPreference = $EA
      $objShellApp = $null
    }
    return $objNewIE
  }

$HWND = ($objIE = New-Object -ComObject InternetExplorer.Application).HWND
$objIE.Navigate("https://www.google.com")
$objIE = ConnectIExplorer -HWND $HWND


来源: stackexchange

问:
PHP contact form using bootstrap
I've tried like 3 other contact forms and none worked so I downloaded this template https://startbootstrap.com/template-overviews/freelancer/ it's a bootstrap template + contact form, I uploaded it on the server with only one edit, I changed this line:

```<code>$to = 'myemail@gmail.com'; // Add your email address in between the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
</code>```

And it's not working.
Then I found this file in the same folder as contact_me.php
eror_log

```<code>[04-Jun-2017 22:17:29 UTC] PHP Warning:  mail() has been disabled for security reasons in /home/myname/public_html/startbootstrap-freelancer-gh-pages/mail/contact_me.php on line 24
</code>```

Can someone help please?

答: If you check your php.ini you can see the settings for disable_functions. It is possible that this is set here and you can edit this to enable.</p>

ContentLicense: CC BY-SA 4.0

Title: PHP contact form using bootstrap

Body:
I've tried like 3 other contact forms and none worked so I downloaded this template https://startbootstrap.com/template-overviews/freelancer/ it's a bootstrap template + contact form, I uploaded it on the server with only one edit, I changed this line:

$to = 'myemail@gmail.com'; // Add your email address in between the '' replacing yourname@yourdomain.com - This is where the form will send a message to.

And it's not working.
Then I found this file in the same folder as contact_me.php
eror_log

[04-Jun-2017 22:17:29 UTC] PHP Warning:  mail() has been disabled for security reasons in /home/myname/public_html/startbootstrap-freelancer-gh-pages/mail/contact_me.php on line 24

Can someone help please?

ContentLicense: CC BY-SA 3.0


问:
Covert comma-separated string to array
Trying to convert comma-separated string to array w/ quotes around each value in js:

var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + ipdarray); // field1,field2```

I want the array to be: ["field1","field2"]

Tried to follow this:  Convert comma separated string to array
but it's not converting to an array.

答:
It is being converted to an array, but when you output the string (in console.log), the array is being coerced back into that string syntax because of the + operator (acting as a concatenator).

Here is a more isolated example of what is happening:

var string = 'field1,field2';
var arr = string.split(',');
console.log(Array.isArray(arr));
console.log(arr.length);

//When using the +, it will coerce into a string
console.log('Coerce to string ' + arr);

//When passing the array as an argument, it will stay an array
console.log('Stays and array', arr);```
</div>
</div>
</p>

<p>In order to preserve the array literal syntax, you'll need to JSON.stringify the array before outputting it if you want to use the + operator, or you can just output the array as a separate argument to console.log</p>

```JSON.stringify(ipdarray);
```

<p>See it in action:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + JSON.stringify(ipdarray)); // ["field1","field2"]
// OR
console.log('Img Pad array: ', ipdarray); // ["field1","field2"]</code>```

Also, arrays are "object"s, but there are other ways to determine if that "object" is an instance of an array:

var arr = [];
console.log(typeof arr);
console.log(arr instanceof Array)
console.log(Array.isArray(arr));```

Title: Covert comma-separated string to array

Body:
Trying to convert comma-separated string to array w/ quotes around each value in js:

var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + ipdarray); // field1,field2

I want the array to be: ["field1","field2"]

Tried to follow this:  Convert comma separated string to array
but it's not converting to an array.

Body:
It is being converted to an array, but when you output the string (in console.log), the array is being coerced back into that string syntax because of the + operator (acting as a concatenator).

Here is a more isolated example of what is happening:

var string = 'field1,field2';
var arr = string.split(',');
console.log(Array.isArray(arr));
console.log(arr.length);

//When using the +, it will coerce into a string
console.log('Coerce to string ' + arr);

//When passing the array as an argument, it will stay an array
console.log('Stays and array', arr);

In order to preserve the array literal syntax, you'll need to JSON.stringify the array before outputting it if you want to use the + operator, or you can just output the array as a separate argument to console.log

JSON.stringify(ipdarray);

See it in action:

var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + JSON.stringify(ipdarray)); // ["field1","field2"]
// OR
console.log('Img Pad array: ', ipdarray); // ["field1","field2"]

Also, arrays are "object"s, but there are other ways to determine if that "object" is an instance of an array:

var arr = [];
console.log(typeof arr);
console.log(arr instanceof Array)
console.log(Array.isArray(arr));


问:
WPF Window PreviewMouseMove event doen't fire when mouse is over WebBrowser control
I'm building a small WPF application to be run on a tablet which has a DockPanel with some kind of content and a set of buttons which, when pressed, load media of various kinds as the content to be displayed, including images, video files, PDFs and webpages. The default content is a slideshow of images and if no input is detected after a certain amount of time, the current content should revert to the slideshow.

I've been doing this by having a timer fire every second, increasing a counter by 1 and returning to the slideshow if the counter exceeds some value, and having a PreviewMouseMove event tied to my main window which resets the counter to 0. This works fine for the images and video files, but the PDFs and webpages, which I'm displaying in a WebBrowser control, prevent the PreviewMouseMove event from firing somehow. Am I right in thinking this should be impossible? If not, is there any other way to detect mouse motion globally, or to get events from the WebBrowser? It seems like odd behavior from the WebBrowser with mouse events is common, and there are a number of questions about it but I've only been able to find examples using the WinForms implementation of the browser rather than the Windows.Controls.WebBrowser, which has a different Document property.

答:
```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        //must wait for load completed
        webBrowser1.LoadCompleted += new LoadCompletedEventHandler(webBrowser1_LoadCompleted);
    }

    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
    {
        mshtml.HTMLDocument doc;
        doc = (mshtml.HTMLDocument)webBrowser1.Document;
        //get the IHTMLDocumentEvents2 interface
        mshtml.HTMLDocumentEvents2_Event iEvent;
        iEvent = (mshtml.HTMLDocumentEvents2_Event)doc;
        //Register a handler
        iEvent.onclick += new mshtml.HTMLDocumentEvents2_onclickEventHandler(ClickEventHandler);
    }

    //here's the handler
    private bool ClickEventHandler(mshtml.IHTMLEventObj e)
    {
        textBox1.Text = "Item Clicked";
        return true;
    }
}
</code>```


问:
Stuck with linking SQL queries together
I'm trying get the MAX value of my subquery denoted as NUM_of_CUST column and to display it alongside with the artist name in tge main query so it would display like this:

ARTIST_NAME | NUM_of_CUST

```<code>Select A.Lastname ||''|| A.FirstName as Artist_Name from dhey.ARTIST A
LEFT JOIN
(SELECT * FROM(
SELECT COUNT(*) As Num_of_Customer From Dhey.CUSTOMER_ARTIST_INT CAI
GROUP BY ARTISTID
ORDER BY COUNT(*) desc) WHERE ROWNUM = 1) B on A.ArtistID = B.ArtistID;
</code>```

However SQL is throwing me B"."ARTISTID": invalid identifier exception.

Can anyone advise on this?

Thank you!

答:
I do not really understand what you want to do but i think it is either you want the number of customers per artist

```<code>Select  A.Lastname ||''|| A.FirstName as Artist_Name
        COUNT(*) as nb_cust
from dhey.ARTIST A
LEFT outer JOIN Dhey.CUSTOMER_ARTIST_INT B on A.ArtistID = B.ArtistID
group by A.ArtistID, A.Lastname ||''|| A.FirstName
order by nb_cust desc
</code>```

Or you want the max number of customer overall and link that to your artist... which is a cross product with one line.

```<code>Select  A.Lastname ||''|| A.FirstName as Artist_Name
        nb_cust_max
from dhey.ARTIST A
cross join  (   select max(nb_cust) as nb_cust_max
                from    (   select count(*) as nb_cust
                            From Dhey.CUSTOMER_ARTIST_INT
                            group by ARTISTID
                        )
            )
</code>```

Am I close ? or totally wrong?

Otherwise, as suggested by MatBailie, you can just add the missing field

```<code>Select A.Lastname ||''|| A.FirstName as Artist_Name from dhey.ARTIST A
LEFT JOIN
(SELECT * FROM(
SELECT ARTISTID, COUNT(*) As Num_of_Customer From Dhey.CUSTOMER_ARTIST_INT CAI
GROUP BY ARTISTID
ORDER BY COUNT(*) desc) WHERE ROWNUM = 1) B on A.ArtistID = B.ArtistID;
</code>```

Title: Stuck with linking SQL queries together

Body:
I'm trying get the MAX value of my subquery denoted as NUM_of_CUST column and to display it alongside with the artist name in tge main query so it would display like this:

ARTIST_NAME | NUM_of_CUST

Select A.Lastname ||''|| A.FirstName as Artist_Name from dhey.ARTIST A
LEFT JOIN
(SELECT * FROM(
SELECT COUNT(*) As Num_of_Customer From Dhey.CUSTOMER_ARTIST_INT CAI
GROUP BY ARTISTID
ORDER BY COUNT(*) desc) WHERE ROWNUM = 1) B on A.ArtistID = B.ArtistID;

However SQL is throwing me B"."ARTISTID": invalid identifier exception.

Can anyone advise on this?

Thank you!

Body:
I do not really understand what you want to do but i think it is either you want the number of customers per artist

Select  A.Lastname ||''|| A.FirstName as Artist_Name
        COUNT(*) as nb_cust
from dhey.ARTIST A
LEFT outer JOIN Dhey.CUSTOMER_ARTIST_INT B on A.ArtistID = B.ArtistID
group by A.ArtistID, A.Lastname ||''|| A.FirstName
order by nb_cust desc

Or you want the max number of customer overall and link that to your artist... which is a cross product with one line.

Select  A.Lastname ||''|| A.FirstName as Artist_Name
        nb_cust_max
from dhey.ARTIST A
cross join  (   select max(nb_cust) as nb_cust_max
                from    (   select count(*) as nb_cust
                            From Dhey.CUSTOMER_ARTIST_INT
                            group by ARTISTID
                        )
            )

Am I close ? or totally wrong?

Otherwise, as suggested by MatBailie, you can just add the missing field

Select A.Lastname ||''|| A.FirstName as Artist_Name from dhey.ARTIST A
LEFT JOIN
(SELECT * FROM(
SELECT ARTISTID, COUNT(*) As Num_of_Customer From Dhey.CUSTOMER_ARTIST_INT CAI
GROUP BY ARTISTID
ORDER BY COUNT(*) desc) WHERE ROWNUM = 1) B on A.ArtistID = B.ArtistID;


问:
MYSQL InnoDB: LOAD DATA INFILE issue with Unique key
Does the performance of LOAD DATA LOCAL INFILE will come down when we use UNIQUE Key Column as to avoid the duplicates?

When i test a .csv file import with Unique and without Unique Key columns, I have following observations:

I see 1 Million records stores/inserts into the table without having any issue without using the Unique key constraint, So it takes duplicates.

With Unique Key constraint on a column to avoid duplicates, I tested with 70k records, it stored well in a minutes time where as for half million records are not inserting/storing into the table and it is running hours of hours through web or MySQL Workbench.  Some times i see following issue:

Error Code: 1205. Lock wait timeout exceeded; try restarting transaction
Query Used:

```<code>LOAD DATA LOCAL INFILE 'file.csv' ignore
    INTO TABLE table1
    CHARACTER SET UTF8mb4 FIELDS
    TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\r\n';`
</code>```

Table structure:

CREATE TABLE table1 (
  Idint(11) NOT NULL AUTO_INCREMENT,
  cUrlvarchar(255) DEFAULT NULL,
  SUrlvarchar(255) DEFAULT NULL,
  FirstNamevarchar(100) DEFAULT NULL,
  LastNamevarchar(100) DEFAULT NULL,
  EmailIdvarchar(150) NOT NULL,
  Filtervarchar(55) DEFAULT NULL,
  Designationvarchar(255) DEFAULT NULL,
  Companyvarchar(255) DEFAULT NULL,
  WebSitevarchar(255) DEFAULT NULL,
  sizevarchar(25) DEFAULT NULL,
  Industryvarchar(255) DEFAULT NULL,
  Typevarchar(25) DEFAULT NULL,
  Foundedvarchar(5) DEFAULT NULL,
  datevarchar(55) NOT NULL,
    PRIMARY KEY (Id),
    UNIQUE KEYEmailId(EmailId`)
  ) ENGINE=InnoDB AUTO_INCREMENT=16812 DEFAULT CHARSET=UTF8mb4;

Applied following steps too:

```<code>set names utf8mb4;
set unique_checks = 0;
set foreign_key_checks = 0;
set sql_log_bin=0;

mysqld select version();
+------------+
| version()  |
+------------+
| 5.7.18-log |
+------------+
1 row in set (0.00 sec)

SELECT @@innodb_buffer_pool_size;
+---------------------------+
| @@innodb_buffer_pool_size |
+---------------------------+
|                   8388608 |
+---------------------------+
1 row in set (0.00 sec)
</code>```

I fixed the UTF8mb4 issue but with Unique key constraint i am failing to import the csv file of half million in the test. I have to work with 40 million records but ofcourse in chucks i will do.

Is it not efficient to use LOAD DATA LOCAL INFILE to import a large csv and with Unique Key constraint.

Suggestions and guidance will be appreciable.

答:
Set innodb_buffer_pool_size to about 70% of available RAM.  8G is ridiculously small.  Did you upgrade from a previous version where that was the default?  I'm pretty sure 5.7.18 has a bigger default, but no big enough.

If practical, sort the csv file by email before doing the LOAD.  In *nix, it is a pretty simple sort command.  This will avoid having to jump around finding to validate the uniqueness for each row.

Will you have any other indexes?  Do you need id?  If no to both, then make email be the PRIMARY KEY and get rid of id.

Use reasonable datatypes for the various columns.  Else you will have SQL issues later.  (Or perhaps you need to bring in the values as strings, then cleanse them?)

Normalize (I agree with @e4c5).

Body:
Does the performance of LOAD DATA LOCAL INFILE will come down when we use UNIQUE Key Column as to avoid the duplicates?

When i test a .csv file import with Unique and without Unique Key columns, I have following observations:

I see 1 Million records stores/inserts into the table without having any issue without using the Unique key constraint, So it takes duplicates.

With Unique Key constraint on a column to avoid duplicates, I tested with 70k records, it stored well in a minutes time where as for half million records are not inserting/storing into the table and it is running hours of hours through web or MySQL Workbench.  Some times i see following issue:

Error Code: 1205. Lock wait timeout exceeded; try restarting transaction
Query Used:

LOAD DATA LOCAL INFILE 'file.csv' ignore
    INTO TABLE table1
    CHARACTER SET UTF8mb4 FIELDS
    TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\r\n';`

Table structure:

CREATE TABLE table1 (
  Idint(11) NOT NULL AUTO_INCREMENT,
  cUrlvarchar(255) DEFAULT NULL,
  SUrlvarchar(255) DEFAULT NULL,
  FirstNamevarchar(100) DEFAULT NULL,
  LastNamevarchar(100) DEFAULT NULL,
  EmailIdvarchar(150) NOT NULL,
  Filtervarchar(55) DEFAULT NULL,
  Designationvarchar(255) DEFAULT NULL,
  Companyvarchar(255) DEFAULT NULL,
  WebSitevarchar(255) DEFAULT NULL,
  sizevarchar(25) DEFAULT NULL,
  Industryvarchar(255) DEFAULT NULL,
  Typevarchar(25) DEFAULT NULL,
  Foundedvarchar(5) DEFAULT NULL,
  datevarchar(55) NOT NULL,
    PRIMARY KEY (Id),
    UNIQUE KEYEmailId(EmailId`)
  ) ENGINE=InnoDB AUTO_INCREMENT=16812 DEFAULT CHARSET=UTF8mb4;

Applied following steps too:

set names utf8mb4;
set unique_checks = 0;
set foreign_key_checks = 0;
set sql_log_bin=0;

mysqld select version();
+------------+
| version()  |
+------------+
| 5.7.18-log |
+------------+
1 row in set (0.00 sec)

SELECT @@innodb_buffer_pool_size;
+---------------------------+
| @@innodb_buffer_pool_size |
+---------------------------+
|                   8388608 |
+---------------------------+
1 row in set (0.00 sec)

I fixed the UTF8mb4 issue but with Unique key constraint i am failing to import the csv file of half million in the test. I have to work with 40 million records but ofcourse in chucks i will do.

Is it not efficient to use LOAD DATA LOCAL INFILE to import a large csv and with Unique Key constraint.

Suggestions and guidance will be appreciable.


问:
How to use $http.then response in another method which is called from view in angularjs?
I have view which has a function inside a table td to check whether the td has data stored in database. If td has data, it will red colored:

```<code><tr ng-repeat="row in rows">
            <td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
                ng-style="{background: getWeight(row, column) ? 'red' :  '' }"
                ng-click="onCellselect(row, column)">
                @{{row}}@{{column}}
            </td>
        </tr>
</code>```

JS:

```<code>  $http.get("api/getYardGraphDetails")

    .then(function (r) {
        console.log(r.data)

        $scope.weights =r.data

    })

$scope.getWeight = function (row, column) {
    console.log($scope.weights)

        // See if there's a record with the row and column.
        var record = _.find($scope.weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }

};
</code>```

in $scope.getWeight() function $scope.weights comes from an $http.get response. But console.log($scope.weights) inside $scope.getWeight()  returns undefined

How can i get $scope.weights from $http.get for $scope.getWeight() ?

I think i should call $scope.getWeight() after $http.getreturns data from database. As $http.get is async it doesn't wait for response and that's my $scope.weights doesn't has value in $scope.getWeight().

答:
First of all, you should familiarize yourself with promises.  You should understand when to use .then, how to chain promises and when to use $q in AngularJS.

I don't really understand what your question is exactly.  Assume it's "How do I make sure that getWeight doesn't have its logic execute until after the $http request is done", you can do it like this (untested):

```<code>var weightsPromise = $http.get("api/getYardGraphDetails")
.then(function (r) {
    console.log(r.data);
    return r.data;
});

$scope.getWeight = function (row, column) {
    return weightsPromise.then(function (weights) {
        // weights here is r.data from above.
        console.log(weights);

        // See if there's a record with the row and column.
        var record = _.find(weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }
    });
};
</code>```

The only thing is now the API is different. $scope.getWeight returns a promise that returns the weight, and doesn't just return the weight anymore.

If this doesn't do what you want, your other option is to wait until the request is finished before calling $scope.getWeight.  Spitfire's ng-if approach does this.

Body:
I have view which has a function inside a table td to check whether the td has data stored in database. If td has data, it will red colored:

                @{{row}}@{{column}}

JS:

  $http.get("api/getYardGraphDetails")

    .then(function (r) {
        console.log(r.data)

        $scope.weights =r.data

    })

$scope.getWeight = function (row, column) {
    console.log($scope.weights)

        // See if there's a record with the row and column.
        var record = _.find($scope.weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }

};

in $scope.getWeight() function $scope.weights comes from an $http.get response. But console.log($scope.weights) inside $scope.getWeight()  returns undefined

How can i get $scope.weights from $http.get for $scope.getWeight() ?

I think i should call $scope.getWeight() after $http.getreturns data from database. As $http.get is async it doesn't wait for response and that's my $scope.weights doesn't has value in $scope.getWeight().

Body:
First of all, you should familiarize yourself with promises.  You should understand when to use .then, how to chain promises and when to use $q in AngularJS.

I don't really understand what your question is exactly.  Assume it's "How do I make sure that getWeight doesn't have its logic execute until after the $http request is done", you can do it like this (untested):

var weightsPromise = $http.get("api/getYardGraphDetails")
.then(function (r) {
    console.log(r.data);
    return r.data;
});

$scope.getWeight = function (row, column) {
    return weightsPromise.then(function (weights) {
        // weights here is r.data from above.
        console.log(weights);

        // See if there's a record with the row and column.
        var record = _.find(weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }
    });
};

The only thing is now the API is different. $scope.getWeight returns a promise that returns the weight, and doesn't just return the weight anymore.

If this doesn't do what you want, your other option is to wait until the request is finished before calling $scope.getWeight.  Spitfire's ng-if approach does this.


问:
Combining Meteor Collections
This problem is in relation to this post.

In short, I'm trying to build a newsfeed, much like Facebook's with infinite scroll functionality. In this newsfeed, I would like to display posts from different collections, according to date posted. I've got a partially working code (check below), but the problem is, because I've set the limit to 3, upon refresh, the site will serve 3 posts from each collections, and not 3 latest posts from any collections.

I think it's because of either the way I publish the collections, or the way I subscribe them. Here are the codes:

publish.js

```<code>Meteor.publish('newsfeed', function(limit){
  data = [
    Status.find({}, {limit:limit, sort: {createdAt:-1}}),
    Story.find({}, {limit:limit, sort: {createdAt:-1}}),
    Lesson.find({}, {limit:limit, sort: {createdAt:-1}}),
    Images.find(),
    Documents.find()
  ];
  return data;
});
</code>```

statusBox.js

```<code>newsfeed_increment = 3;
Session.setDefault('newsfeedLimit', newsfeed_increment);
Deps.autorun(function(){
  Meteor.subscribe('newsfeed', Session.get('newsfeedLimit'));
});

Template.statusBox.helpers({
  //Merging few collections into one template helper: https://stackoverflow.com/questions/21296712/merging-collections-in-meteor
  newsfeedList: function(){
    var hza = Status.find().fetch()
      .concat(Story.find().fetch())
      .concat(Lesson.find().fetch());
      var sortie = _.sortBy(hza, function(doc) { return doc.createdAt; });
      var ietros = sortie.reverse();
      return ietros;
...
});
</code>```

Any ideas?

答:
You should sort and do other filters on the client-side as well, i.e, in

statusBox.js

```<code>Template.statusBox.helpers({
  newsfeedList: function(){
    var limit = Session.get('newsfeedLimit');
    var hza = Status.find({limit:limit, sort: {createdAt:-1}).fetch()
      .concat(Story.find({limit:limit, sort: {createdAt:-1}).fetch())
      .concat(Lesson.find({limit:limit, sort: {createdAt:-1}).fetch());
    var sortie = _.sortBy(hza, function(doc) { return doc.createdAt; });
    var ietros = sortie.reverse();
   return ietros;
   ...
});
</code>```

Title: Combining Meteor Collections

Body:
This problem is in relation to this post.

In short, I'm trying to build a newsfeed, much like Facebook's with infinite scroll functionality. In this newsfeed, I would like to display posts from different collections, according to date posted. I've got a partially working code (check below), but the problem is, because I've set the limit to 3, upon refresh, the site will serve 3 posts from each collections, and not 3 latest posts from any collections.

I think it's because of either the way I publish the collections, or the way I subscribe them. Here are the codes:

publish.js

Meteor.publish('newsfeed', function(limit){
  data = [
    Status.find({}, {limit:limit, sort: {createdAt:-1}}),
    Story.find({}, {limit:limit, sort: {createdAt:-1}}),
    Lesson.find({}, {limit:limit, sort: {createdAt:-1}}),
    Images.find(),
    Documents.find()
  ];
  return data;
});

statusBox.js

newsfeed_increment = 3;
Session.setDefault('newsfeedLimit', newsfeed_increment);
Deps.autorun(function(){
  Meteor.subscribe('newsfeed', Session.get('newsfeedLimit'));
});

Template.statusBox.helpers({
  //Merging few collections into one template helper: https://stackoverflow.com/questions/21296712/merging-collections-in-meteor
  newsfeedList: function(){
    var hza = Status.find().fetch()
      .concat(Story.find().fetch())
      .concat(Lesson.find().fetch());
      var sortie = _.sortBy(hza, function(doc) { return doc.createdAt; });
      var ietros = sortie.reverse();
      return ietros;
...
});

Any ideas?

Body:
You should sort and do other filters on the client-side as well, i.e, in

statusBox.js

Template.statusBox.helpers({
  newsfeedList: function(){
    var limit = Session.get('newsfeedLimit');
    var hza = Status.find({limit:limit, sort: {createdAt:-1}).fetch()
      .concat(Story.find({limit:limit, sort: {createdAt:-1}).fetch())
      .concat(Lesson.find({limit:limit, sort: {createdAt:-1}).fetch());
    var sortie = _.sortBy(hza, function(doc) { return doc.createdAt; });
    var ietros = sortie.reverse();
   return ietros;
   ...
});


问:
How are @"Strings" allocated in memory?
I am curious of the memory allocation for the following code.

```<code>NSString *myString = [NSString string];
</code>```

I know this will create an autoreleased empty string, @""

What happens when I then call

```<code>myString = @"Hello world";
</code>```

Is my reference the same as the autoreleased object NSString provided or did I just allocate a new object that I am responsible for releasing?

答:
When wondering whether you own an object, ask yourself:

Does the method I used to create this object...

begin with new?

begin with alloc?

contain copy?

equal retain?

If you can answer "Yes" to any of those, then you are responsible for invoking release or autorelease on the returned object.  (Note that the rules for Core Foundation objects are slightly different.  Also note that anything that the documentation explicitly says that contradicts this wins.  The documentation always supersedes the guidelines)

In the case of your string, the answers to all your questions are "no", so you are not responsible for the object.  Constant strings (of the style @"foo") are hard-coded into the application binary and cannot be deallocated.  That, however, is an implementation detail.  As long as you follow the memory management rules, you'll be good!

ContentLicense: CC BY-SA 2.5

Title: How are @"Strings" allocated in memory?

Body:
I am curious of the memory allocation for the following code.

NSString *myString = [NSString string];

I know this will create an autoreleased empty string, @""

What happens when I then call

myString = @"Hello world";

Is my reference the same as the autoreleased object NSString provided or did I just allocate a new object that I am responsible for releasing?


问:
AWS SQS Required or not
I am building one service which would use the data that would come from another source(service). So, I am thinking to use the following pipeline:-

Other service ----> SNS Topic ----> SQS ----> AWS Lambda ----> Dynamo Db

So, what above flow says is Another service will push data to SNS Topic to which an SQS would be a subscriber. Now AWS Lambda will have a trigger on this SQS which would listen to the messages in SQS and push it to Dynamo Db. Although it looks okay to do this. But now I am thinking if I really need SQS or not. Can I avoid using it? Instead of using SQS, AWS Lambda directly has a trigger on SNS. I am just thinking of one case if I don't use AWS SQS. How will it handle the scenario if AWS Dynamo DB fails? I think with only SNS, I would lose some messages during the time, my Dynamo Db is in failed state but if I have SQS, then those messages would be stored in SQS queue.

Please let me know if my understanding is correct.

Thanks a lot for your help.

答:
Couldn't answer as much in the comments so I'll try here.

The architecture you linked to is pretty common.  The two biggest downfalls are that you're going to billed for Lambda usage even if there is nothing to do and your data may be delayed by the amount of the polling interval which is a minimum of 1 minute.  Neither of these things may matter in your problem though.

SQS could be used as a temporary store for data in the event of a DynamoDB failure.  But what exactly are you going to do if it fails?  What if SQS fails and loses your messages?  What if Lambda fails and never runs your code?  DynamoDB is a hosted service just like SQS  and Lambda - Amazon is going to work very hard to keep it running just like their other services.  Trying to architect around every possible failure scenario will mean you never deliver code.  I'd focus on the simplest architecture you can and put some trust in the services you're paying for.

Title: AWS SQS Required or not


问:
Built in way to read couchdb document size?
I'm experimenting with using couchdb as a message store and would like to report the message size.

Ideally it would be nice to read a _size attribute.  At worst I could check the string length of the entire document's JSON.  I may even want to use the size as a view key.

What do you think is the best way to record document size and why do you think that method is best?

答:
Based on the accepted answer, I suggest the following improvement:

```<code>function (doc) {
    emit([JSON.stringify(doc).length, doc._id], doc._id);
}
</code>```

This has the following advantages:

doc length as the first key part lets you sort by document size.

doc id as second key part ensures that documents with the same size show up as separate entries.

doc id in the value part makes it easier to copy the ID when in futon (as the key part gives you a link pointer there).

Body:
Based on the accepted answer, I suggest the following improvement:

function (doc) {
    emit([JSON.stringify(doc).length, doc._id], doc._id);
}

This has the following advantages:

doc length as the first key part lets you sort by document size.

doc id as second key part ensures that documents with the same size show up as separate entries.

doc id in the value part makes it easier to copy the ID when in futon (as the key part gives you a link pointer there).


答:
Given input string you can use String.prototype.match() with RegExp /[^,]+/g to match one or more characters which are not comma ,

```<code>var ipd = 'field1,field2';
var ipdarray = ipd.match(/[^,]+/g);
</code>```

Note that  + operator converts array to string at

```<code>console.log('Img Pad array: ' + ipdarray); // field1,field2
</code>```

use comma , operator at console.log() call

```<code>console.log('Img Pad array: ', ipdarray); // field1,field2
</code>```

Title: Covert comma-separated string to array

Body:
Given input string you can use String.prototype.match() with RegExp /[^,]+/g to match one or more characters which are not comma ,

var ipd = 'field1,field2';
var ipdarray = ipd.match(/[^,]+/g);

Note that  + operator converts array to string at

console.log('Img Pad array: ' + ipdarray); // field1,field2

use comma , operator at console.log() call

console.log('Img Pad array: ', ipdarray); // field1,field2


问:
Routing system with array - Sending parameter with variable
I try to build a routing system with PHP. I have a problem with changeable URLs.

```<code>private $routes = array(
    "blog" => array("Blog", "GetAll"),
    "/blog\/*/" => array("Blog", "GetOne"),
);

private $query;

public function __construct()
{
    $this->query = filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_URL);
}

public function SendAction()
{
    $route = array();
    if (array_key_exists($this->query, $this->routes)) {
        $route['controller'] = $this->routes[$this->query][0];
        $route['action'] = $this->routes[$this->query][1];
        $route['params'] = $this->routes[$this->query][2];
    } else {
        $route['controller'] = "Error";
        $route['action'] = "Main";
        $route['params'] = array();
    }
    return $route;
}
</code>```

The problem is with the url that contains abc/my_custom_variable_or/slug.

I need to get my_custom_variable_or and slug and put them into params['fdsaf'] so I can use it in my controller

I find a temp solution with else if, like: else if (preg_match("/blog\/*/", $this->query)) .... explode() etc...

To make my system more flexible, I need to make something in $routes array. The routes array will be a different file.

===Sample inputs and the expected results===

URL: blog

```<code>$route['controller'] = Blog
$route['action'] = GetAll
$route['params'] = array()
</code>```

URL: blog/my-first-post

```<code>$route['controller'] = Blog
$route['action'] = GetOne
$route['params'] = array('slug' => 'my-first-post')
</code>```

URL: blog/user/martin/page2 (page2 is optional)

```<code>$route['controller'] = Blog
$route['action'] = GetUserPost
$route['params'] = array('slug' => 'martin')
</code>```

答:
My regex pattern will capture 3 groups.  The first is the leading text -- for all three samples inputs, this is blog.  The second group will either be empty or user -- this identifies when GetUserPost is to be used.  The third group may be empty or contain the slug value.

Pattern Demo

Code (PHP Demo):

```<code>if(preg_match('/^([^\/]+)\/?((?:user)?)\/?((?:[^\/]+)?)/',$v,$out)){
    $route['controller']=ucfirst($out[1]);
    if($out[2]==''){
        if($out[3]==''){
            $route['action']='GetAll';
            $route['params']=[];
        }else{
            $route['action']='GetOne';
            $route['params']=['slug'=>$out[3]];
        }
    }else{
        $route['action']='GetUserPost';
        $route['params']=['slug'=>$out[3]];
    }
}
</code>```

Hard-coded Blog version:

```<code>$inputs=['blog','blog/my-first-post','blog/user/martin/page2'];
foreach($inputs as $v){
    $route=[];
    if(preg_match('/^[^\/]+\/?((?:user)?)\/?((?:[^\/]+)?)/',$v,$out)){
        $route['controller']='Blog';
        if($out[1]==''){
            if($out[2]==''){
                $route['action']='GetAll';
                $route['params']=[];
            }else{
                $route['action']='GetOne';
                $route['params']=['slug'=>$out[2]];
            }
        }else{
            $route['action']='GetUserPost';
            $route['params']=['slug'=>$out[2]];
        }
    }
    var_export($route);
}
</code>```

Output (from either method):

```<code>array (
  'controller' => 'Blog',
  'action' => 'GetAll',
  'params' =>
  array (
  ),
)array (
  'controller' => 'Blog',
  'action' => 'GetOne',
  'params' =>
  array (
    'slug' => 'my-first-post',
  ),
)array (
  'controller' => 'Blog',
  'action' => 'GetUserPost',
  'params' =>
  array (
    'slug' => 'martin',
  ),
)
</code>```

Body:
I try to build a routing system with PHP. I have a problem with changeable URLs.

private $routes = array(
    "blog" => array("Blog", "GetAll"),
    "/blog\/*/" => array("Blog", "GetOne"),
);

private $query;

public function __construct()
{
    $this->query = filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_URL);
}

public function SendAction()
{
    $route = array();
    if (array_key_exists($this->query, $this->routes)) {
        $route['controller'] = $this->routes[$this->query][0];
        $route['action'] = $this->routes[$this->query][1];
        $route['params'] = $this->routes[$this->query][2];
    } else {
        $route['controller'] = "Error";
        $route['action'] = "Main";
        $route['params'] = array();
    }
    return $route;
}

The problem is with the url that contains abc/my_custom_variable_or/slug.

I need to get my_custom_variable_or and slug and put them into params['fdsaf'] so I can use it in my controller

I find a temp solution with else if, like: else if (preg_match("/blog\/*/", $this->query)) .... explode() etc...

To make my system more flexible, I need to make something in $routes array. The routes array will be a different file.

===Sample inputs and the expected results===

URL: blog

$route['controller'] = Blog
$route['action'] = GetAll
$route['params'] = array()

URL: blog/my-first-post

$route['controller'] = Blog
$route['action'] = GetOne
$route['params'] = array('slug' => 'my-first-post')

URL: blog/user/martin/page2 (page2 is optional)

$route['controller'] = Blog
$route['action'] = GetUserPost
$route['params'] = array('slug' => 'martin')

Body:
My regex pattern will capture 3 groups.  The first is the leading text -- for all three samples inputs, this is blog.  The second group will either be empty or user -- this identifies when GetUserPost is to be used.  The third group may be empty or contain the slug value.

Pattern Demo

Code (PHP Demo):

if(preg_match('/^([^\/]+)\/?((?:user)?)\/?((?:[^\/]+)?)/',$v,$out)){
    $route['controller']=ucfirst($out[1]);
    if($out[2]==''){
        if($out[3]==''){
            $route['action']='GetAll';
            $route['params']=[];
        }else{
            $route['action']='GetOne';
            $route['params']=['slug'=>$out[3]];
        }
    }else{
        $route['action']='GetUserPost';
        $route['params']=['slug'=>$out[3]];
    }
}

Hard-coded Blog version:

$inputs=['blog','blog/my-first-post','blog/user/martin/page2'];
foreach($inputs as $v){
    $route=[];
    if(preg_match('/^[^\/]+\/?((?:user)?)\/?((?:[^\/]+)?)/',$v,$out)){
        $route['controller']='Blog';
        if($out[1]==''){
            if($out[2]==''){
                $route['action']='GetAll';
                $route['params']=[];
            }else{
                $route['action']='GetOne';
                $route['params']=['slug'=>$out[2]];
            }
        }else{
            $route['action']='GetUserPost';
            $route['params']=['slug'=>$out[2]];
        }
    }
    var_export($route);
}

Output (from either method):

array (
  'controller' => 'Blog',
  'action' => 'GetAll',
  'params' =>
  array (
  ),
)array (
  'controller' => 'Blog',
  'action' => 'GetOne',
  'params' =>
  array (
    'slug' => 'my-first-post',
  ),
)array (
  'controller' => 'Blog',
  'action' => 'GetUserPost',
  'params' =>
  array (
    'slug' => 'martin',
  ),
)


答:
var a = "field1,field2"

var b = a.split(',');

var c = b.map(function (v) {
return '"' + v + '"';
})

console.log(c);
console.log(c[0]);
console.log(c[1]);```

Title: Covert comma-separated string to array


问:
Why am I getting Premature End of File Error?
I am trying to parse an XML response, but I am failing miserably. I thought initially
that the xml was just not being returned in the response, so I crafted up the code below with a direct link to my xml file online. I am able to print the XML to screen with no problems. However when I call my parse method I get Premature end of file.

It works if I pass the URL directly:

builder.parse("");

but fails when I passed an InputStream:

builder.parse(connection.getInputStream());

```<code>  try {
    URL url = new URL(xml);
    URLConnection uc =  url.openConnection();
    HttpURLConnection  connection = (HttpURLConnection )uc;

    connection.setDoInput(true);
    connection.setDoOutput(true);

    InputStream instream;
    InputSource source;
    //get XML from InputStream
    if(connection.getResponseCode()>= 200){
        connection.connect();
        instream = connection.getInputStream();
        parseDoc(instream);
    }
    else{
        instream = connection.getErrorStream();
    }

} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

 static void parseDoc(InputStream instream) throws ParserConfigurationException,
 SAXException, IOException{

  BufferedReader buff_read = new BufferedReader(new InputStreamReader(instream,"UTF-8"));
    String  inputLine = null;

    while((inputLine = buff_read.readLine())!= null){
        System.out.println(inputLine);
    }

  DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
  factory.isIgnoringElementContentWhitespace();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse(instream);
}
</code>```

The errors I am getting:

```<code>    [Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at com.ameba.api.network.MainApp.parseDoc(MainApp.java:78)
    at com.ameba.api.network.MainApp.main(MainApp.java:41)
</code>```

答: You are getting the error because the SAXBuilder is not intelligent enough to deal with "blank states". So it looks for at least an <xml ..> declaration, and when that causes a no data response it creates the exception you see rather than report the empty state.

Body:
I am trying to parse an XML response, but I am failing miserably. I thought initially
that the xml was just not being returned in the response, so I crafted up the code below with a direct link to my xml file online. I am able to print the XML to screen with no problems. However when I call my parse method I get Premature end of file.

It works if I pass the URL directly:

builder.parse("");

but fails when I passed an InputStream:

builder.parse(connection.getInputStream());

  try {
    URL url = new URL(xml);
    URLConnection uc =  url.openConnection();
    HttpURLConnection  connection = (HttpURLConnection )uc;

    connection.setDoInput(true);
    connection.setDoOutput(true);

    InputStream instream;
    InputSource source;
    //get XML from InputStream
    if(connection.getResponseCode()>= 200){
        connection.connect();
        instream = connection.getInputStream();
        parseDoc(instream);
    }
    else{
        instream = connection.getErrorStream();
    }

} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

 static void parseDoc(InputStream instream) throws ParserConfigurationException,
 SAXException, IOException{

  BufferedReader buff_read = new BufferedReader(new InputStreamReader(instream,"UTF-8"));
    String  inputLine = null;

    while((inputLine = buff_read.readLine())!= null){
        System.out.println(inputLine);
    }

  DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
  factory.isIgnoringElementContentWhitespace();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse(instream);
}

The errors I am getting:

    [Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at com.ameba.api.network.MainApp.parseDoc(MainApp.java:78)
    at com.ameba.api.network.MainApp.main(MainApp.java:41)


问:
Removing an item from a list
I would like to remove to ignore duplicates in my list. For example, let's say the function checks for words that end with a ''.'' and puts them in a list. I would like to make sure that duplicate words don't go in the list.

Here is what I have so far:

```<code>def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix
        if (word == list):
            list.remove(word)
    return list
</code>```

答:
Why not use a set?</p>

```<code>def endwords(sent):
    my_list = set()
    words = sent.split()
    for word in words:
        if "." in word:
            my_list.add(word)
    return my_list
</code>```

Title: Removing an item from a list

Body:
I would like to remove to ignore duplicates in my list. For example, let's say the function checks for words that end with a ''.'' and puts them in a list. I would like to make sure that duplicate words don't go in the list.

Here is what I have so far:

def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix
        if (word == list):
            list.remove(word)
    return list

Body:
Why not use a set?

def endwords(sent):
    my_list = set()
    words = sent.split()
    for word in words:
        if "." in word:
            my_list.add(word)
    return my_list


问:
How to call asynchronous recursive functions after each other?
I am using trying to have typing text in a div that has three different lines of text. So I want to call the function typed_text() for line one, then call it again for line two, then line three. I tried to use promises, but I was lost when it came to using setTimeout() and recursion.

I call the function something like this.

```<code>typed_text("#line_one", frame.text_one, 0, 25)
        typed_text("#line_two", frame.text_two, 0, 25)
        typed_text("#line_three", frame.text_three, 0, 25)

        function typed_text(div, text, index, interval)
        {
            if (quit_typed_text == true) {
                interval = 0;
            }
            if (index < text.length) {
                $(div).append(text[index++]);
                setTimeout(function() {typed_text(div, text, index, interval); }, interval);
            } else {
                click_disabled = false;
            }

        }
</code>```

Edit: Here is what I was attempting using recursion and promises

```<code>    typed_text("#text_one", frame.text_one, 0, 25).then(typed_text("#text_two", frame.text_two, 0, 25));

function typed_text(div, text, index, interval)
{
    return new Promise(function (resolve) {
        if (quit_typed_text == true) {
            interval = 0;
        }
        if (index >= text.length) {
            click_disabled = false;
            resolve();
        }
    }).then(function() {
        if (index < text.length) {
            $(div).append(text[index++]);
            /* Problem is here, setTimeout.then() does not exist as a function */
            setTimeout(function() {typed_text(div, text, index, interval); }, interval);
        }
    });
}
</code>```

答:
It seems there's no asynchronous function in your code, so why don't you call your function "typed_text" in a setTimeOut ?

By example :

```<code>setTimeout(function() { typed_text("#line_one", frame.text_one, 0); }, 25);
setTimeout(function() { typed_text("#line_two", frame.text_two, 0); }, 50);
setTimeout(function() { typed_text("#line_three", frame.text_three, 0); }, 75);

function typed_text(div, text, index){
    if (quit_typed_text == true) interval = 0;
    if (index < text.length) $(div).append(text[index++]);
    else click_disabled = false;
}
</code>```

Could this be ok for you ?

Body:
I am using trying to have typing text in a div that has three different lines of text. So I want to call the function typed_text() for line one, then call it again for line two, then line three. I tried to use promises, but I was lost when it came to using setTimeout() and recursion.

I call the function something like this.

typed_text("#line_one", frame.text_one, 0, 25)
        typed_text("#line_two", frame.text_two, 0, 25)
        typed_text("#line_three", frame.text_three, 0, 25)

        function typed_text(div, text, index, interval)
        {
            if (quit_typed_text == true) {
                interval = 0;
            }
            if (index < text.length) {
                $(div).append(text[index++]);
                setTimeout(function() {typed_text(div, text, index, interval); }, interval);
            } else {
                click_disabled = false;
            }

        }

Edit: Here is what I was attempting using recursion and promises

    typed_text("#text_one", frame.text_one, 0, 25).then(typed_text("#text_two", frame.text_two, 0, 25));

function typed_text(div, text, index, interval)
{
    return new Promise(function (resolve) {
        if (quit_typed_text == true) {
            interval = 0;
        }
        if (index >= text.length) {
            click_disabled = false;
            resolve();
        }
    }).then(function() {
        if (index < text.length) {
            $(div).append(text[index++]);
            /* Problem is here, setTimeout.then() does not exist as a function */
            setTimeout(function() {typed_text(div, text, index, interval); }, interval);
        }
    });
}

Body:
It seems there's no asynchronous function in your code, so why don't you call your function "typed_text" in a setTimeOut ?

By example :

setTimeout(function() { typed_text("#line_one", frame.text_one, 0); }, 25);
setTimeout(function() { typed_text("#line_two", frame.text_two, 0); }, 50);
setTimeout(function() { typed_text("#line_three", frame.text_three, 0); }, 75);

function typed_text(div, text, index){
    if (quit_typed_text == true) interval = 0;
    if (index < text.length) $(div).append(text[index++]);
    else click_disabled = false;
}

Could this be ok for you ?


答:
The less verbose way to do it would be using list comprehension, that is

```<code>my_list = [word for word in words if '.' in word]
</code>```

And to ensure the elements aren't duplicated, just use set.

```<code>my_list = set(my_list)  # No more duplicated values
</code>```

Title: Removing an item from a list

Body:
The less verbose way to do it would be using list comprehension, that is

my_list = [word for word in words if '.' in word]

And to ensure the elements aren't duplicated, just use set.

my_list = set(my_list)  # No more duplicated values


问:
Joining two datasets using fuzzy logic
I’m trying to do a fuzzy logic join in R between two datasets:

first data set has the name of a location and a column called config

second data set has the name of a location and two additional attributes that need to be summarized before they are joined to the first data set.

I would like to use the name column to join between the two data sets. However the name column may have additional or leading characters in either data set or have one word contained inside of a larger word. So for example if we looked at these two data sets, I'd like the name OPAL to join to the OPALAS, and SAUSALITO Y to join to SAUSALITO.

```<code>Dataset1:
     Name           Config
     ALTO D         BB
     CONTRA         ST
     EIGHT A        DD
     OPALAS         BB
     SAUSALITO Y    AA
     SOLANO J       ST

Dataset2:
    Name       Age     Rank
    ALTO D     50      2
    ALTO D     20      6
    CONTRA     10      10
    CONTRA     15      15
    EIGHTH     18      21
    OPAL       19      4
    SAUSALITO  2       12
    SOLANO     34      43
</code>```

Code for Summarizing of Dataset2

```<code>Data2a <- summaryBy(Age ~ Name,FUN=c(mean), data=Data2,na.rm=TRUE)
Data2b <- summaryBy(Rank ~ Name,FUN=c(sum), data=Data2,na.rm=TRUE)
Data2 <- data.frame(Data2a$Name, Data2a$Age.mean, Data2b$Rank.sum)

Desired Outcome:
    Name        Config  Age   Rank
    ALTO D      BB      35    8
    CONTRA      ST      12.5  25
    EIGHT A     DD      18    21
    OPALAS      BB      19    4
    SAUSALITO Y AA      12    5
    SOLANO J    ST      34    43
</code>```

答:
I was able to join the two datasets, using the fuzzyjoin package:</p>

```<code>library(fuzzyjoin)
stringdist_inner_join(Dataset1, Data2,
     by ="Name", distance_col = NULL)
</code>```

Title: Joining two datasets using fuzzy logic

Body:
I’m trying to do a fuzzy logic join in R between two datasets:

first data set has the name of a location and a column called config

second data set has the name of a location and two additional attributes that need to be summarized before they are joined to the first data set.

I would like to use the name column to join between the two data sets. However the name column may have additional or leading characters in either data set or have one word contained inside of a larger word. So for example if we looked at these two data sets, I'd like the name OPAL to join to the OPALAS, and SAUSALITO Y to join to SAUSALITO.

Dataset1:
     Name           Config
     ALTO D         BB
     CONTRA         ST
     EIGHT A        DD
     OPALAS         BB
     SAUSALITO Y    AA
     SOLANO J       ST

Dataset2:
    Name       Age     Rank
    ALTO D     50      2
    ALTO D     20      6
    CONTRA     10      10
    CONTRA     15      15
    EIGHTH     18      21
    OPAL       19      4
    SAUSALITO  2       12
    SOLANO     34      43

Code for Summarizing of Dataset2

Data2a <- summaryBy(Age ~ Name,FUN=c(mean), data=Data2,na.rm=TRUE)
Data2b <- summaryBy(Rank ~ Name,FUN=c(sum), data=Data2,na.rm=TRUE)
Data2 <- data.frame(Data2a$Name, Data2a$Age.mean, Data2b$Rank.sum)

Desired Outcome:
    Name        Config  Age   Rank
    ALTO D      BB      35    8
    CONTRA      ST      12.5  25
    EIGHT A     DD      18    21
    OPALAS      BB      19    4
    SAUSALITO Y AA      12    5
    SOLANO J    ST      34    43

Body:
I was able to join the two datasets, using the fuzzyjoin package:

library(fuzzyjoin)
stringdist_inner_join(Dataset1, Data2,
     by ="Name", distance_col = NULL)


问:
R: Conditionally replacing values based on column pre-fixes and suffixes
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

```<code>library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")
</code>```

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

```<code>  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6
</code>```

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

答:
If you don't mind verbose baseR approaches, then you can easily accomplish this using merge() and a careful subsetting of your data frame.

```<code>df <- merge(foo, bar, by="id", all.x=TRUE)
names(df) <- c("id", "x", "z", "y")
df$x[is.na(df$x)] <- df$y[is.na(df$x)]
df <- df[c("id", "x", "z")]

> df
  id  x z
1  1 10 1
2  2  9 2
3  3 NA 3
4  4  1 4
5  5  3 5
6  6  8 6
</code>```

Body:
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

Body:
If you don't mind verbose baseR approaches, then you can easily accomplish this using merge() and a careful subsetting of your data frame.

df <- merge(foo, bar, by="id", all.x=TRUE)
names(df) <- c("id", "x", "z", "y")
df$x[is.na(df$x)] <- df$y[is.na(df$x)]
df <- df[c("id", "x", "z")]

> df
  id  x z
1  1 10 1
2  2  9 2
3  3 NA 3
4  4  1 4
5  5  3 5
6  6  8 6


问:
MYSQL Table Times Out During Drop
I have a table with several hundred million rows of data.  I want to delete the table, but every operation I perform on the table loses connection after running for 50,000+ seconds (about 16 hours), which is under the 60,000 second time out condition I have set in the database.  I've tried creating a stored procedure with the Drop Table code thinking that if I send the info to the DB to perform the operation it will not need a connection to process it, but it does the same thing.  Is it just timing out?  Or do I need to do something else?</p>

答:
Instead do TRUNCATE TABLE.  Internally it creates an equivalent, but empty, table, then swaps.  This technique might take a second, even for a very big table.

If you are deleting most of a table, then it is usually faster (sometimes a lot faster), to do

```<code>CREATE TABLE new LIKE real;
INSERT INTO new
    SELECT ... FROM real
        WHERE ... -- the rows you want to keep
</code>```

Why do you need to delete everything?

For other techniques in massive deletes, including big chunks out of a huge table, see https://mariadb.com/kb/en/mariadb/big-deletes/

Title: MYSQL Table Times Out During Drop

Body:
Instead do TRUNCATE TABLE.  Internally it creates an equivalent, but empty, table, then swaps.  This technique might take a second, even for a very big table.

If you are deleting most of a table, then it is usually faster (sometimes a lot faster), to do

CREATE TABLE new LIKE real;
INSERT INTO new
    SELECT ... FROM real
        WHERE ... -- the rows you want to keep

Why do you need to delete everything?

For other techniques in massive deletes, including big chunks out of a huge table, see https://mariadb.com/kb/en/mariadb/big-deletes/


问:
Detect touch Cocos2d-x
I'm using Cocos2d-x and trying to detect touches in my HelloWorld project. Though I'm having no luck.

.h

```<code>class HelloWorld : public CCLayer{

private:
    CCSpriteBatchNode * _batchNode;
    CCSprite *_turkey;
    virtual void ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
</code>```

.ccp

```<code>void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event){
    CCLog("this");
}
</code>```

but the thing is that when I click the screen 'this' never shows up in the log. What am i missing here?

thanks!

Edit,

Im using this tutorial.
http://www.raywenderlich.com/11338/cocos2d-x-for-ios-and-android-space-game

答:
Here in below method I am applying touch on Sprite , If you want to apply touch event on TextField , Node , Background , or in any component just Pass that ComponentType into this method and It will work ....

OK LETS BEGIN!!!!

```<code>void YourClassName::YourListnerMethodName(cocos2d::Sprite* object)
{
   auto listener = cocos2d::EventListenerTouchOneByOne::create();
   listener->setSwallowTouches(false);

    listener->onTouchBegan = [=](cocos2d::Touch* touch, cocos2d::Event* event)
    {
       auto target = event->getCurrentTarget();
       Point locationInNode = target->convertToNodeSpace(touch->getLocation());

       // Suppose your sprite or any component is inside in any parent object then use this line instead of above line ...
       //just uncomment below line and it will work fine in this case
       //Point locationInNode = target->getParent()->convertToNodeSpace(touch->getLocation());

        if (target->getBoundingBox().containsPoint(locationInNode)) {

           // CODE FOR RESPONSE AFTER TOUCH

            return true;
        }
        return false;
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, object);
}
</code>```

Here the target is your component , where you want to apply touch on it

Just don't forget to call this method from ctor or anywhere according to your requirement

Title: Detect touch Cocos2d-x

Body:
I'm using Cocos2d-x and trying to detect touches in my HelloWorld project. Though I'm having no luck.

.h

class HelloWorld : public CCLayer{

private:
    CCSpriteBatchNode * _batchNode;
    CCSprite *_turkey;
    virtual void ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event);

.ccp

void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event){
    CCLog("this");
}

but the thing is that when I click the screen 'this' never shows up in the log. What am i missing here?

thanks!

Edit,

Im using this tutorial.
http://www.raywenderlich.com/11338/cocos2d-x-for-ios-and-android-space-game

Body:
Here in below method I am applying touch on Sprite , If you want to apply touch event on TextField , Node , Background , or in any component just Pass that ComponentType into this method and It will work ....

OK LETS BEGIN!!!!

void YourClassName::YourListnerMethodName(cocos2d::Sprite* object)
{
   auto listener = cocos2d::EventListenerTouchOneByOne::create();
   listener->setSwallowTouches(false);

    listener->onTouchBegan = [=](cocos2d::Touch* touch, cocos2d::Event* event)
    {
       auto target = event->getCurrentTarget();
       Point locationInNode = target->convertToNodeSpace(touch->getLocation());

       // Suppose your sprite or any component is inside in any parent object then use this line instead of above line ...
       //just uncomment below line and it will work fine in this case
       //Point locationInNode = target->getParent()->convertToNodeSpace(touch->getLocation());

        if (target->getBoundingBox().containsPoint(locationInNode)) {

           // CODE FOR RESPONSE AFTER TOUCH

            return true;
        }
        return false;
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, object);
}

Here the target is your component , where you want to apply touch on it

Just don't forget to call this method from ctor or anywhere according to your requirement


问:
matlab: How to convert a vector of complex double elements to a vector of 24bit (each element)?
matlab: How to convert a vector of complex double elements to a vector of 24bit (each element)?
(using the fact that the real part is 12 bit and the imaginary part 12 bit)

My try:

```<code>fileOpen=fopen('newFile.txt');
fprintf(fileOpen, '%d,\r\n', real(complexNum)+((imag(complexNum))*(2^12))));
fclose(fileOpen);
</code>```

答:
See here for data types: https://www.mathworks.com/help/matlab/numeric-types.html

It appears that there is no support for 24bit operations. Of course, this is to be expected as Matlab is one of those "very" high level languages.

From what you have described. Would you not be better off just doing it from scratch with C language?

Alternatively, check out this link: parse text file in MATLAB

Body:
matlab: How to convert a vector of complex double elements to a vector of 24bit (each element)?
(using the fact that the real part is 12 bit and the imaginary part 12 bit)

My try:

fileOpen=fopen('newFile.txt');
fprintf(fileOpen, '%d,\r\n', real(complexNum)+((imag(complexNum))*(2^12))));
fclose(fileOpen);


问:
VSCode run ruby file from terminal
The VSCode python extension has a feature to right click and run a file from the terminal. Is there a way that I can use a similar feature to quickly execute a ruby file from the terminal? Perhaps a hot key to start a new terminal session and run the current file within the ruby install directory.</p>

答:
You can install the code-runner package opening the command palette:

command + shift + p (Mac)

control + shift + p (Windows/Linux)

Find and install it:

```<code>ext install code-runner
</code>```

Then it'll ask you to reload the window, and depending which file type you're working in, you can type the ctrl + alt + n keybinding and your file output will be in the output tab.

Title: VSCode run ruby file from terminal

Body:
You can install the code-runner package opening the command palette:

command + shift + p (Mac)

control + shift + p (Windows/Linux)

Find and install it:

ext install code-runner

Then it'll ask you to reload the window, and depending which file type you're working in, you can type the ctrl + alt + n keybinding and your file output will be in the output tab.


问:
Conditional looping with ADO Recordset in VBA
In the past, I've always generated reports by querying a database, dropping it on a worksheet, sorting, reading into an array, and then looping through to create the documents.  What I'm trying to do now is generate the reports directly from the recordset.

The problem I have though is when using arrays I had an absolute record number, so I could check if a field in the previous record was the same as in the current record.

What is the best way of going about doing this with a recordset?  Store the field value in a variable?  Use nested While loops?  Get a total record count and use absolute positions to move back and forth (which doesn't seem like a good idea)?

UPDATE
The recordset contains multiple records from 20 different companies. I sort the query by the company name and then start loop through it. I then need to check each record to see if it's from the same company as the previous and if not create a new worksheet for that company.

答: I usually do the sort in the query using an "Order By" clause. Then just loop through the sorted records using a variable to track the current sort order name and detect the name change by comparing the current record name field to the variable value.</p>


问:
Where should I set UINavigationController's delegate property?
I'm working with some custom controller transitions, which make use of UINavigationController's delegate property. If I set it in viewDidLoad(), self.navigationController?.delegate gets deallocated at some point after the push. Setting it in viewWillAppear() works, but I'm wondering why that property gets deallocated in the first place, and where people typically set this property.

```<code>    // The first time you push, it will work correctly, and the delegate function below is called. After you pop back to this controller, delegate is nil (has been deallocated)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.delegate = self
    }

    // Brute force works
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationControllerOperation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        if operation == .push {
            return WTPPushAnimator()
        }
        if operation == .pop {
            return WTPPopAnimator()
        }
        return nil;
    }
</code>```

答: If the ViewController you are pushing also sets navigationController?.delegate = self, then when that ViewController is popped, that ViewController will be deallocated and the weak var delegate will be set to nil.  viewDidLoad() only runs when the ViewController is first created, so when returning to the first ViewController, viewDidLoad() will not run again. viewWillAppear() is always called when a ViewController is pushed or when it is returned to on a pop, so viewWillAppear() is the right place to set this delegate.

Body:
I'm working with some custom controller transitions, which make use of UINavigationController's delegate property. If I set it in viewDidLoad(), self.navigationController?.delegate gets deallocated at some point after the push. Setting it in viewWillAppear() works, but I'm wondering why that property gets deallocated in the first place, and where people typically set this property.

    // The first time you push, it will work correctly, and the delegate function below is called. After you pop back to this controller, delegate is nil (has been deallocated)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.delegate = self
    }

    // Brute force works
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationControllerOperation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        if operation == .push {
            return WTPPushAnimator()
        }
        if operation == .pop {
            return WTPPopAnimator()
        }
        return nil;
    }


问:
Java parse String containing integers and multiple delimiters
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

```<code>"1,25,3-6,14,16-19"
</code>```

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

```<code>1,3,4,5,6,14,16,17,18,19,25
</code>```

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

```<code>List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}
</code>```

答:
To ensure there are no duplicates and in order as you expect, use Set:</p>

```<code>    String inputData = "1,25,3-6,14,16-19";
    String[] numberRanges = inputData.split(",");
    Set<Integer> set = new TreeSet<>();

    for (String numberRange : numberRanges) {
        if (numberRange.contains("-")) {
            String[] range = numberRange.split("-");
            int startIndex = Integer.valueOf(range[0]);
            int endIndex = Integer.valueOf(range[1]);
            for (int i = startIndex; i <= endIndex; ++i) {
                set.add(i);
            }
        } else {
            set.add(Integer.valueOf(numberRange));
        }
    }
    System.out.println(set);
</code>```

Body:
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

"1,25,3-6,14,16-19"

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

1,3,4,5,6,14,16,17,18,19,25

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}

Body:
To ensure there are no duplicates and in order as you expect, use Set:

    String inputData = "1,25,3-6,14,16-19";
    String[] numberRanges = inputData.split(",");
    Set<Integer> set = new TreeSet<>();

    for (String numberRange : numberRanges) {
        if (numberRange.contains("-")) {
            String[] range = numberRange.split("-");
            int startIndex = Integer.valueOf(range[0]);
            int endIndex = Integer.valueOf(range[1]);
            for (int i = startIndex; i <= endIndex; ++i) {
                set.add(i);
            }
        } else {
            set.add(Integer.valueOf(numberRange));
        }
    }
    System.out.println(set);


问:
AWS Lambda integration with SQS
Does AWS lambda provide support for listening to SQS queue? I found some examples which says one can do that but I am not sure if AWS lambda explicity provide support for that. When I create the lambda function, then I found one blueprint for SQS. So,</p>

答: You can make your lambda function poll the queue using the SQS API. You could use SNS to trigger the Lambda function. </p>

Title: AWS Lambda integration with SQS


问:
echo outputs -e parameter in bash scripts. How can I prevent this?
I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

```<code>$ echo -e 'foo\nbar'
</code>```

into an interactive bash shell, I get the expected output:

```<code>foo
bar
</code>```

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

```<code>-e foo
 bar
</code>```

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?

答:
Different implementations of echo behave in annoyingly different ways.  Some don't take options (i.e. will simply echo -e as you describe) and automatically interpret escape sequences in their parameters.  Some take flags, and don't interpret escapes unless given the -e flag.  Some take flags, and interpret different escape sequences depending on whether the -e flag was passed.  Some will cause you to tear your hair out if you try to get them to behave in a predictable manner... oh, wait, that's all of them.

What you're probably seeing here is a difference between the version of echo built into bash vs /bin/echo or maybe vs. some other shell's builtin.  This bit me when Mac OS X v10.5 shipped with a bash builtin echo that echoed flags, unlike what all my scripts expected...

In any case, there's a solution: use printf instead.  It always interprets escape sequences in its first argument (the format string).  The problems are that it doesn't automatically add a newline (so you have to remember do that explicitly), and it also interprets % sequences in its first argument (it is, after all, a format string).  Generally, you want to put all the formatting stuff in the format string, then put variable strings in the rest of the arguments so you can control how they're interpreted by which % format you use to interpolate them into the output.  Some examples:

```<code>printf "foo\nbar\n"      # this does what you're trying to do in the example
printf "%s\n" "$var"     # behaves like 'echo "$var"', except escapes will never be interpreted
printf "%b\n" "$var"     # behaves like 'echo "$var"', except escapes will always be interpreted
printf "%b\n" "foo\nbar" # also does your example
</code>```

Body:
I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

$ echo -e 'foo\nbar'

into an interactive bash shell, I get the expected output:

foo
bar

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

-e foo
 bar

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?

Body:
Different implementations of echo behave in annoyingly different ways.  Some don't take options (i.e. will simply echo -e as you describe) and automatically interpret escape sequences in their parameters.  Some take flags, and don't interpret escapes unless given the -e flag.  Some take flags, and interpret different escape sequences depending on whether the -e flag was passed.  Some will cause you to tear your hair out if you try to get them to behave in a predictable manner... oh, wait, that's all of them.

What you're probably seeing here is a difference between the version of echo built into bash vs /bin/echo or maybe vs. some other shell's builtin.  This bit me when Mac OS X v10.5 shipped with a bash builtin echo that echoed flags, unlike what all my scripts expected...

In any case, there's a solution: use printf instead.  It always interprets escape sequences in its first argument (the format string).  The problems are that it doesn't automatically add a newline (so you have to remember do that explicitly), and it also interprets % sequences in its first argument (it is, after all, a format string).  Generally, you want to put all the formatting stuff in the format string, then put variable strings in the rest of the arguments so you can control how they're interpreted by which % format you use to interpolate them into the output.  Some examples:

printf "foo\nbar\n"      # this does what you're trying to do in the example
printf "%s\n" "$var"     # behaves like 'echo "$var"', except escapes will never be interpreted
printf "%b\n" "$var"     # behaves like 'echo "$var"', except escapes will always be interpreted
printf "%b\n" "foo\nbar" # also does your example


问:
plot logistic regression line over heat plot
My data is binary with two linear independent variables. For both predictors, as they get bigger, there are more positive responses. I have plotted the data in a heatplot showing density of positive responses along the two variables. There are the most positive responses in the top right corner and negative responses in the bottom left, with a gradient change visible along both axes.

I would like to plot a line on the heatplot showing where a logistic regression model predicts that positive and negative responses are equally likely. (My model is of the form response~predictor1*predictor2+(1|participant).)

My question: How can I figure out the line based on this model at which the positive response rate is 0.5?

I tried using predict(), but that works the opposite way; I have to give it values for the factor rather than giving the response rate I want. I also tried using a function that I used before when I had only one predictor (function(x) (log(x/(1-x))-fixef(fit)[1])/fixef(fit)[2]), but I can only get single values out of that, not a line, and I can only get values for one predictor at a time.

答:
Using a simple example logistic regression model fitted to the mtcars dataset, and the algebra described here, I can produce a heatmap with a decision boundary using:

```<code>library(ggplot2)
library(tidyverse)
data("mtcars")

m1 = glm(am ~ hp + wt, data = mtcars, family = binomial)

# Generate combinations of hp and wt across their observed range. Only
#   generating 50 values of each here, which is not a lot but since each
#   combination is included, you get 50 x 50 rows
pred_df = expand.grid(
    hp = seq(min(mtcars$hp), max(mtcars$hp), length.out = 50),
    wt = seq(min(mtcars$wt), max(mtcars$wt), length.out = 50)
)
pred_df$pred_p = predict(m1, pred_df, type = "response")

# For a given value of hp (predictor1), find the value of
#   wt (predictor2) that will give predicted p = 0.5
find_boundary = function(hp_val, coefs) {
    beta_0 = coefs['(Intercept)']
    beta_1 = coefs['hp']
    beta_2 = coefs['wt']
    boundary_wt =  (-beta_0 - beta_1 * hp_val) / beta_2
}

# Find the boundary value of wt for each of the 50 values of hp
# Using the algebra in the linked question you can instead find
# the slope and intercept of the boundary, so you could potentially
# skip this step
boundary_df = pred_df %>%
    select(hp) %>%
    distinct %>%
    mutate(wt = find_boundary(hp, coef(m1)))

ggplot(pred_df, aes(x = hp, y = wt)) +
    geom_tile(aes(fill = pred_p)) +
    geom_line(data = boundary_df)
</code>```

Producing:

Note that this only takes into account the fixed effects from the model, so if you want to somehow take into account random effects this could be more complex.

Body:
Using a simple example logistic regression model fitted to the mtcars dataset, and the algebra described here, I can produce a heatmap with a decision boundary using:

library(ggplot2)
library(tidyverse)
data("mtcars")

m1 = glm(am ~ hp + wt, data = mtcars, family = binomial)

# Generate combinations of hp and wt across their observed range. Only
#   generating 50 values of each here, which is not a lot but since each
#   combination is included, you get 50 x 50 rows
pred_df = expand.grid(
    hp = seq(min(mtcars$hp), max(mtcars$hp), length.out = 50),
    wt = seq(min(mtcars$wt), max(mtcars$wt), length.out = 50)
)
pred_df$pred_p = predict(m1, pred_df, type = "response")

# For a given value of hp (predictor1), find the value of
#   wt (predictor2) that will give predicted p = 0.5
find_boundary = function(hp_val, coefs) {
    beta_0 = coefs['(Intercept)']
    beta_1 = coefs['hp']
    beta_2 = coefs['wt']
    boundary_wt =  (-beta_0 - beta_1 * hp_val) / beta_2
}

# Find the boundary value of wt for each of the 50 values of hp
# Using the algebra in the linked question you can instead find
# the slope and intercept of the boundary, so you could potentially
# skip this step
boundary_df = pred_df %>%
    select(hp) %>%
    distinct %>%
    mutate(wt = find_boundary(hp, coef(m1)))

ggplot(pred_df, aes(x = hp, y = wt)) +
    geom_tile(aes(fill = pred_p)) +
    geom_line(data = boundary_df)

Producing:

Note that this only takes into account the fixed effects from the model, so if you want to somehow take into account random effects this could be more complex.


问:
Finding the frequency of object key VALUES in an array of objects
I have an array of objects (police data, each one is a crime). The array of objects is 1000 in length.

Every object has a key/value such as community_area: 22.

I am trying to iterate over the array of objects to find the top three community areas that exist in the array. So if community areas 22, 70 and 1 had the most crime (each object occurrence) it would return those three.

What is an efficient way of doing this other than creating arrays of the 77 different community areas with the crimes then comparing the length?

答:
Pattern for this sort of thing is fairly simple.

Create an object , iterate the array and use the common property of data objects as keys in new object and values will be incremental counts.

Then iterate the new object and compare those counts

var data = [
 {community_area:22},
 {community_area:22},
 {community_area:9},
 {community_area:9},
 {community_area:9},
 {community_area:5},
 {community_area:5},
 {community_area:5},
 {community_area:5},
 {community_area:1},
 {community_area:2},
 {community_area:3},

];

var countObj = data.reduce((a,c)=>{
   a[c.community_area] =  (a[c.community_area] || 0 ) + 1;
   return a
},{});

console.log('Community counts', countObj)

var top3 = Object.keys(countObj)
                  .sort((a,b) => countObj[b] - countObj[a] )
                  .slice(0,3)
                  .map(Number);//optional if need number vs string

console.log('Top 3', top3)```


问:
Returning words from a string array with symbols between them in java?
```<code>public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}
</code>```

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

答:
By using Arrays.toString and replace you can achieve the result you want

```<code>String array[] = {"please", "help", "me"};
String output = "https://www.google.com/#q=" + Arrays.toString(array).
                    replace("[", "").
                    replace("]", "").
                    replace(", ", "+");
System.out.println(output);
</code>```

output

```<code> https://www.google.com/#q=please+help+me
</code>```

Body:
public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

Body:
By using Arrays.toString and replace you can achieve the result you want

String array[] = {"please", "help", "me"};
String output = "https://www.google.com/#q=" + Arrays.toString(array).
                    replace("[", "").
                    replace("]", "").
                    replace(", ", "+");
System.out.println(output);

output

 https://www.google.com/#q=please+help+me


答:
You can use the below method :

```<code>public static String join(String[] array, String separator) {
    if (array == null) {
        return null;
    } else {
        if (separator == null) {
            separator = "";
        }

        if (array.length <= 0) {
            return "";
        } else {
            StringBuilder buf = new StringBuilder(array.length * 16);

            for (int i = 0; i < array.length; ++i) {
                if (i > 0) {
                    buf.append(separator);
                }

                if (array[i] != null) {
                    buf.append(array[i]);
                }
            }

            return buf.toString();
        }
    }
}
</code>```

It's actually imported from org.apache.commons.lang3; package

Example :

```<code>public static String onGoogleCommand(String[] args) {
    if (args.length == 0) {
        return "Type in a question after the google command!";
    }
    if (args.length >= 1) {
        return "https://www.google.com/#q=" + join(args, "+");
    }
    return "What?";
}
</code>```

Title: Returning words from a string array with symbols between them in java?

Body:
You can use the below method :

public static String join(String[] array, String separator) {
    if (array == null) {
        return null;
    } else {
        if (separator == null) {
            separator = "";
        }

        if (array.length <= 0) {
            return "";
        } else {
            StringBuilder buf = new StringBuilder(array.length * 16);

            for (int i = 0; i < array.length; ++i) {
                if (i > 0) {
                    buf.append(separator);
                }

                if (array[i] != null) {
                    buf.append(array[i]);
                }
            }

            return buf.toString();
        }
    }
}

It's actually imported from org.apache.commons.lang3; package

Example :

public static String onGoogleCommand(String[] args) {
    if (args.length == 0) {
        return "Type in a question after the google command!";
    }
    if (args.length >= 1) {
        return "https://www.google.com/#q=" + join(args, "+");
    }
    return "What?";
}