问:
Loop through a list with an autofilter
I have a list of companies (listA, located in worksheet Workings2) and a list of companies(ListB - each company has multiple entries, located in worksheets data) with data attached, for list A i want to be able to take a company (in a cell in column B) and loop through listB on an Auto filter so that I can check if a certain column (AZ) has a certain count of values in a particular band (100,000-500,000). once I have the count of numbers I want to add it to a worksheet workings. After each company in ListB, I want to reset the filter and aplly the filter for the next company

I have the code below, which i have scrambled together, but it gives out a wacky number that makes no sense (in the order of 30,000, when I'm looking at around 100)

```<code>Sub calculate1()

Dim wsCriteria As Worksheet, wsData As Worksheet, wsDest As Worksheet
Dim CompanyListLocation
Dim lr As Long, dlr As Long
Application.ScreenUpdating = False
Set wsCriteria = Sheets("Dashboard")
Set wsData = Sheets("Data")
Set wsDest2 = Sheets("Workings2")

Dim rCell As Range
Dim rRng As Range
Set rRng = wsData.Range("B3: B418")

For i = 0 To 419

   With wsData.Rows(1)
        .AutoFilter Field:=5, Criteria1:=i

lr = wsData.UsedRange.Rows.Count
dlr = wsDest2.Cells(Rows.Count, 1).End(xlUp).Row + 1
'wsData.AutoFilterMode = False

With wsData.Rows(1)
.AutoFilter Field:=3, Criteria1:="Forward", Operator:=xlOr, Criteria2:="NDF"
  If wsDest2.Range("C1:C" & lr).SpecialCells(xlCellTypeVisible).Cells.Count
> 1 Then
  ff = Application.WorksheetFunction.CountIfs(wsData.Range("AZ:AZ"), ">" &
100000, wsData.Range("AZ:AZ"), "<" & 500000)
wsDest2.Range("C3").Value = ff
     End If
.AutoFilter
End With
End With

Next i
End Sub
</code>```

It would be amazing if anyone could help out

答:
I'm still unclear on why this is not what you want to do. It seems a much more succinct solution. You need to add the company filter (e.g. .AutoFilter Field:=5, Criteria1:=i) into the COUNTIFS to get the correct result. COUNTIFS is not filtered by .AutoFilter.

```<code>=SUM(COUNTIFS(E:E, BB2, AZ:AZ, ">="&BC2, AZ:AZ, "<="&BD2, C:C, {"forward","ndf"}))
</code>```

Title: Loop through a list with an autofilter

Body:
I have a list of companies (listA, located in worksheet Workings2) and a list of companies(ListB - each company has multiple entries, located in worksheets data) with data attached, for list A i want to be able to take a company (in a cell in column B) and loop through listB on an Auto filter so that I can check if a certain column (AZ) has a certain count of values in a particular band (100,000-500,000). once I have the count of numbers I want to add it to a worksheet workings. After each company in ListB, I want to reset the filter and aplly the filter for the next company

I have the code below, which i have scrambled together, but it gives out a wacky number that makes no sense (in the order of 30,000, when I'm looking at around 100)

Sub calculate1()

Dim wsCriteria As Worksheet, wsData As Worksheet, wsDest As Worksheet
Dim CompanyListLocation
Dim lr As Long, dlr As Long
Application.ScreenUpdating = False
Set wsCriteria = Sheets("Dashboard")
Set wsData = Sheets("Data")
Set wsDest2 = Sheets("Workings2")

Dim rCell As Range
Dim rRng As Range
Set rRng = wsData.Range("B3: B418")

For i = 0 To 419

   With wsData.Rows(1)
        .AutoFilter Field:=5, Criteria1:=i

lr = wsData.UsedRange.Rows.Count
dlr = wsDest2.Cells(Rows.Count, 1).End(xlUp).Row + 1
'wsData.AutoFilterMode = False

With wsData.Rows(1)
.AutoFilter Field:=3, Criteria1:="Forward", Operator:=xlOr, Criteria2:="NDF"
  If wsDest2.Range("C1:C" & lr).SpecialCells(xlCellTypeVisible).Cells.Count
> 1 Then
  ff = Application.WorksheetFunction.CountIfs(wsData.Range("AZ:AZ"), ">" &
100000, wsData.Range("AZ:AZ"), "<" & 500000)
wsDest2.Range("C3").Value = ff
     End If
.AutoFilter
End With
End With

Next i
End Sub

It would be amazing if anyone could help out

Body:
I'm still unclear on why this is not what you want to do. It seems a much more succinct solution. You need to add the company filter (e.g. .AutoFilter Field:=5, Criteria1:=i) into the COUNTIFS to get the correct result. COUNTIFS is not filtered by .AutoFilter.

=SUM(COUNTIFS(E:E, BB2, AZ:AZ, ">="&BC2, AZ:AZ, "<="&BD2, C:C, {"forward","ndf"}))


来源: stackexchange

问:
Is there a working real world project using Clojure that take advantage of multi-core system that I can take a look?
Is there a working real world project using Clojure that take advantage of multi-core system that I can take a look?

I want to if Clojure is still in a toy-language phrase or it's really "happening soon".

答:
You should look at the many examples posted up in the Google discussion group.  They are interesting and a couple of them non-trivial in another language.  I think those examples are more than enough proof about whether Clojure is a "toy" language or not.

The designer, Rich Hickey, uses the language himself for his work so I wouldn't be surprised if you find it very production ready.  The API at this point isn't changing much since things are headed toward a 1.0 release, so you don't really have to worry too much about hte rug being pulled out under your feet.  Probably the least stable part right now, if you're going to do your Lisping in Emacs, is SLIME and swank-clojure.  It's pretty imperative that you use latest versions of both directly from their repositories (I use the GitHub mirrors).

Get it while it's hot.

OwnerDisplayName: Seymour Cakes

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Seymour Cakes

OwnerDisplayName: dnolen


问:
Google App Script custom error on .withFailureHandler
I would like to throw a custom error in a function called with google.script.run from code.gs so I could display adequate information in a side bar. So far I've tested the following code with no luck:

code.gs

```<code>function UserException(type, text) {
  this.type = type;
  this.text = text;
  //this.stack = (new Error()).stack;
}
UserException.prototype = Object.create(Error.prototype);
UserException.prototype.constructor = UserException;

function assignRangeToTechnician(technician)
{
   if(technician!=null)
   {
    //some code
   }else
    throw new UserException("Error","Technician was not selected");
}
</code>```

sidebar.html

```<code>...
<script>
function btnSelectTech()
{
  google.script.run
   .withSuccessHandler(rangeSelected)
   .withFailureHandler(techniciansMessage)
   .assignRangeToTechnician(document.getElementById('selectTechnician').value);
}

function techniciansMessage(Message)
{
  var outputMessage = document.getElementById('message');

  //here is where I log the Message value
  google.script.run.myLog("In techniciansMessage() - Message: " + Message);

  if (Message == null)
   outputMessage.innerHTML = "<p style='color:red;'>Error occured</p>";
  else
    if (Message.type == "Error")
      outputMessage.innerHTML = "<p style='color:red;'>" + Message.text + "</p>";
    else if (Message.type == "Message")
      outputMessage.innerHTML = "<p style='color:#f3f3f3;'>" + Message.text + "</p>";
}
</script>
...
</code>```

When I run the code the .withFailureHandler is called but the Message doesn't hold the proper value. When I log that message I read "Error: " as a content of a 'Message' parameter.

Could you please help?
Thank you.

答:
You may refer with this SO thread. Try adding an error parameter to your function. Example:

```<code>google.script.run.withFailureHandler(function (error) {
  showError(error, 'getMe');
}).getMe();
</code>```

Additional reference which might help: https://github.com/google/google-apps-script-samples/blob/master/translate/Sidebar.js.html

ContentLicense: CC BY-SA 3.0

Body:
I would like to throw a custom error in a function called with google.script.run from code.gs so I could display adequate information in a side bar. So far I've tested the following code with no luck:

code.gs

function UserException(type, text) {
  this.type = type;
  this.text = text;
  //this.stack = (new Error()).stack;
}
UserException.prototype = Object.create(Error.prototype);
UserException.prototype.constructor = UserException;

function assignRangeToTechnician(technician)
{
   if(technician!=null)
   {
    //some code
   }else
    throw new UserException("Error","Technician was not selected");
}

sidebar.html

...

...

When I run the code the .withFailureHandler is called but the Message doesn't hold the proper value. When I log that message I read "Error: " as a content of a 'Message' parameter.

Could you please help?
Thank you.

Body:
You may refer with this SO thread. Try adding an error parameter to your function. Example:

google.script.run.withFailureHandler(function (error) {
  showError(error, 'getMe');
}).getMe();

Additional reference which might help: https://github.com/google/google-apps-script-samples/blob/master/translate/Sidebar.js.html


问:
How should i solve this error:bad operand types for binary operator '&&'
I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'

```<code>  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }
</code>```

答:
Greater than is just >, not >>, which is a shift operator. Same for less than and < vs <<.

The shift operator returns an integral type and && expects both sides to be of type boolean. For more information on the shift operators, see this question: How do shift operators work in Java?

Body:
I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'

  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }


问:
What happens if I send integers to a BigQuery field "string"?
One of the columns I send (in my code) to BigQuery is integers. I added the columns to BigQuery and I was too fast and added them as type string.

Will they be automatically converted? Or will the data be totally corrupted (= I cannot trust at all the resulting string)?

答:
Data shouldn't be automatically converted as this would destroy the purpose of having a table schema.

What I've seen people doing is saving a whole json line as string and then processing this string inside of BigQuery. Other than that, if you try to save values not correspondent to the field schema definition, you should see an error being thrown, like so:

If you need to change a table schema's definition, you can check this tutorial on updating a table schema.


问:
BizTalk is not submitting required credentials to ASP.Net Core Web.API service
We are trying to use Biztalk as a client to a Web.API service which is written using ASP.net Core w/ .Net Framework 4.6.2. The service uses Windows Authentication and does not allow anonymous access. At this point we are unable to send the Windows Credentials with our request from Biztalk.
We are able to get the Windows credentials when addressing another test service written without .Net Core. It uses .Net Framework 4.5.2.
We've thought that we could write a kind of adapter service, something that would forward the needed credentials on behalf of the Biztalk server, but that seems kludgey.
The Biztalk developer tells me he is using a WCF-WebHttp adapter.

WCF-WebHttp Transport Properties:

```<code>HTTP Method and URL Mapping
    <BtsHttpUrlMapping>
    <Operation   Method="POST" Url=""  />
    EndPoint Identity (Default settings)
    Binding Tab settings (Default settings )
    Security Mode:  TransportCredentialOnly
    Transport client credential type: Windows
    Behavior Tab (Default Settings)
    Proxy:  Use Send handler proxy settings
    Outbound HTTP Headers:  Content-Type: application/json
    Outbound Message: GET

Send Pipeline: XmlToJSONSendPipeline
    RemoveOuterEnvelope: True
Receive Pipeline: JSONToXmlReceivePipeline
    RootNode: Response
    Allow UnrecognizedMessage: False
    REcoveraleInterchangeProcessing: False
    ValidateDocument: False
</code>```

答:
In WCF-WebHttp Behavior->EndpointBehavior add clientCredentials->Windows->allowedImpersonationLevel change Identity to Impersonation

Here is a reference link: Using IIS Authentication with ASP.NET Impersonation

Body:
We are trying to use Biztalk as a client to a Web.API service which is written using ASP.net Core w/ .Net Framework 4.6.2. The service uses Windows Authentication and does not allow anonymous access. At this point we are unable to send the Windows Credentials with our request from Biztalk.
We are able to get the Windows credentials when addressing another test service written without .Net Core. It uses .Net Framework 4.5.2.
We've thought that we could write a kind of adapter service, something that would forward the needed credentials on behalf of the Biztalk server, but that seems kludgey.
The Biztalk developer tells me he is using a WCF-WebHttp adapter.

WCF-WebHttp Transport Properties:

HTTP Method and URL Mapping
    <BtsHttpUrlMapping>
    <Operation   Method="POST" Url=""  />
    EndPoint Identity (Default settings)
    Binding Tab settings (Default settings )
    Security Mode:  TransportCredentialOnly
    Transport client credential type: Windows
    Behavior Tab (Default Settings)
    Proxy:  Use Send handler proxy settings
    Outbound HTTP Headers:  Content-Type: application/json
    Outbound Message: GET

Send Pipeline: XmlToJSONSendPipeline
    RemoveOuterEnvelope: True
Receive Pipeline: JSONToXmlReceivePipeline
    RootNode: Response
    Allow UnrecognizedMessage: False
    REcoveraleInterchangeProcessing: False
    ValidateDocument: False


问:
Format SQL output in Powershell ISE
Using Invoke-SQLCMD and running a saved query, Is there a way to see the output as a table? Currently, All output is printed sequentially, such as Name newline state newline is_encrypted for each item returned from the query rather than a row-column table where name, state, is_encrypted, etc. are the column headers.

The end goal is to output all the results of the query into a text or excel file.

答:
Try this:</p>

```<code>Invoke-Sqlcmd -query $sql | Export-Csv -Path c:\temp\excelfile.csv -NoTypeInformation
</code>```

Title: Format SQL output in Powershell ISE

Body:
Try this:

Invoke-Sqlcmd -query $sql | Export-Csv -Path c:\temp\excelfile.csv -NoTypeInformation


问:
log Mysql connect to remote rsyslog
I need to log the users that logs on mysql.

With the imfile module I read from the local mysql log

```<code>input(type="imfile"
    File="/var/log/mysql/mysql.log"
    Tag="mysql-general"
    Severity="warning"
    Facility="local1")
</code>```

I send it to the remote server (it's work).

But I need only to send the line with the word "Connect", and not all the messages.

I try:

```<code>if $syslogtag == 'mysql-general' and $msg contains 'Connect' then @*.*.*.*
</code>```

it's still loggin anythings. Any ideas?

答:
Ok, I found one possible solution.
We can add a ruleset:

```<code>ruleset(name="mysql_rule"){
    if $syslogtag == 'mysql-general' and $msg contains 'Connect' then @*.*.*.*
}
</code>```

And change a little bit the input:

```<code>input(type="imfile"
    File="/var/log/mysql/mysql.log"
    Tag="mysql-general"
    stateFile="statefile-mysql-general"
    Severity="warning"
    Facility="local1"
    ruleset="mysql_rule"
    reopenOnTruncate="on"
)
</code>```

Title: log Mysql connect to remote rsyslog

Body:
I need to log the users that logs on mysql.

With the imfile module I read from the local mysql log

input(type="imfile"
    File="/var/log/mysql/mysql.log"
    Tag="mysql-general"
    Severity="warning"
    Facility="local1")

I send it to the remote server (it's work).

But I need only to send the line with the word "Connect", and not all the messages.

I try:

if $syslogtag == 'mysql-general' and $msg contains 'Connect' then @*.*.*.*

it's still loggin anythings. Any ideas?

Body:
Ok, I found one possible solution.
We can add a ruleset:

ruleset(name="mysql_rule"){
    if $syslogtag == 'mysql-general' and $msg contains 'Connect' then @*.*.*.*
}

And change a little bit the input:

input(type="imfile"
    File="/var/log/mysql/mysql.log"
    Tag="mysql-general"
    stateFile="statefile-mysql-general"
    Severity="warning"
    Facility="local1"
    ruleset="mysql_rule"
    reopenOnTruncate="on"
)


问:
How to animate GradientStop color?
I've tried code below, but there's something wrong in line "Storyboard.SetTargetProperty(ca1, new PropertyPath("GradientStop.ColorProperty"));

sb.Begin(this) threw an InvalidOperationException and couldn't resolve „gradStop1.ColorProperty”.

How to properly animate GradientStop colors?

```<code>private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        LinearGradientBrush lgb = new LinearGradientBrush(
           (Color)ColorConverter.ConvertFromString("#FF1E2838"),
           (Color)ColorConverter.ConvertFromString("#FF2B364F"),
           new Point(0.5, 0),
           new Point(0.5, 1));
        UCBody.Background = lgb;

        ColorAnimation ca1 = new ColorAnimation(
            (Color)ColorConverter.ConvertFromString("#FF1E2838"),
            (Color)ColorConverter.ConvertFromString("#FF1E1E1E"),
            TimeSpan.FromMilliseconds(600));

        ColorAnimation ca2 = new ColorAnimation(
            (Color)ColorConverter.ConvertFromString("#FF2B364F"),
            (Color)ColorConverter.ConvertFromString("#FF2B2B38"),
            TimeSpan.FromMilliseconds(600));

        Storyboard sb = new Storyboard();
        sb.Children.Add(ca1);
        sb.Children.Add(ca2);
        Storyboard.SetTargetName(ca1, "gradStop1");
        Storyboard.SetTargetProperty(ca1, new PropertyPath("GradientStop.ColorProperty"));
        Storyboard.SetTargetName(ca2, "gradStop2");
        Storyboard.SetTargetProperty(ca2, new PropertyPath("GradientStop.ColorProperty"));

        sb.Begin(this);
    }
}
</code>```

答:
You have no objects named "gradStop1" or "gradStop2" but you could animate the gradient stops of the LinearGradientBrush using the BeginAnimation method:

```<code>private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    LinearGradientBrush lgb = new LinearGradientBrush(
       (Color)ColorConverter.ConvertFromString("#FF1E2838"),
       (Color)ColorConverter.ConvertFromString("#FF2B364F"),
       new Point(0.5, 0),
       new Point(0.5, 1));
    UCBody.Background = lgb;

    ColorAnimation ca1 = new ColorAnimation(
        (Color)ColorConverter.ConvertFromString("#FF1E2838"),
        (Color)ColorConverter.ConvertFromString("#FF1E1E1E"),
        TimeSpan.FromMilliseconds(600));

    ColorAnimation ca2 = new ColorAnimation(
        (Color)ColorConverter.ConvertFromString("#FF2B364F"),
        (Color)ColorConverter.ConvertFromString("#FF2B2B38"),
        TimeSpan.FromMilliseconds(600));

    lgb.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca1);
    lgb.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca2);
}
</code>```

Title: How to animate GradientStop color?

Body:
I've tried code below, but there's something wrong in line "Storyboard.SetTargetProperty(ca1, new PropertyPath("GradientStop.ColorProperty"));

sb.Begin(this) threw an InvalidOperationException and couldn't resolve „gradStop1.ColorProperty”.

How to properly animate GradientStop colors?

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        LinearGradientBrush lgb = new LinearGradientBrush(
           (Color)ColorConverter.ConvertFromString("#FF1E2838"),
           (Color)ColorConverter.ConvertFromString("#FF2B364F"),
           new Point(0.5, 0),
           new Point(0.5, 1));
        UCBody.Background = lgb;

        ColorAnimation ca1 = new ColorAnimation(
            (Color)ColorConverter.ConvertFromString("#FF1E2838"),
            (Color)ColorConverter.ConvertFromString("#FF1E1E1E"),
            TimeSpan.FromMilliseconds(600));

        ColorAnimation ca2 = new ColorAnimation(
            (Color)ColorConverter.ConvertFromString("#FF2B364F"),
            (Color)ColorConverter.ConvertFromString("#FF2B2B38"),
            TimeSpan.FromMilliseconds(600));

        Storyboard sb = new Storyboard();
        sb.Children.Add(ca1);
        sb.Children.Add(ca2);
        Storyboard.SetTargetName(ca1, "gradStop1");
        Storyboard.SetTargetProperty(ca1, new PropertyPath("GradientStop.ColorProperty"));
        Storyboard.SetTargetName(ca2, "gradStop2");
        Storyboard.SetTargetProperty(ca2, new PropertyPath("GradientStop.ColorProperty"));

        sb.Begin(this);
    }
}

Body:
You have no objects named "gradStop1" or "gradStop2" but you could animate the gradient stops of the LinearGradientBrush using the BeginAnimation method:

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    LinearGradientBrush lgb = new LinearGradientBrush(
       (Color)ColorConverter.ConvertFromString("#FF1E2838"),
       (Color)ColorConverter.ConvertFromString("#FF2B364F"),
       new Point(0.5, 0),
       new Point(0.5, 1));
    UCBody.Background = lgb;

    ColorAnimation ca1 = new ColorAnimation(
        (Color)ColorConverter.ConvertFromString("#FF1E2838"),
        (Color)ColorConverter.ConvertFromString("#FF1E1E1E"),
        TimeSpan.FromMilliseconds(600));

    ColorAnimation ca2 = new ColorAnimation(
        (Color)ColorConverter.ConvertFromString("#FF2B364F"),
        (Color)ColorConverter.ConvertFromString("#FF2B2B38"),
        TimeSpan.FromMilliseconds(600));

    lgb.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca1);
    lgb.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca2);
}


问:
How to make individual items in a table selectable in angularjs
I have a table using ng-repeat... I want to be able to allow the users to select an item in the table using the key 'enter' which is equal to the keydown event 13. When a user clicks enter, I want to be able to focus in on the specific table row and make the variable 'selected' to true. When the user clicks on enter the second time, I want the 'selected' field to be set to false.

Here is what I have so far, any ideas?

html:

```<code><tbody ng-model="educators">
    <tr ng-keydown="keydownevt()" tabindex="0" class="inventor-row"
        ng-repeat="ed in educators">
        <td class="inventor-col">
          <div><strong>{{ed.lastName}}, {{ed.firstName}}</strong></div>
          <div>{{ed.address}}</div>
          <div>{{ed.country}}</div>
        </td>
    </tr>
</tbody>
</code>```

JS:

```<code>$scope.keydownevt = function () {
  $scope.keydownkeycode = event.keyCode;
  var selected = false;
  if (event.keyCode === 13) {
    // add focus
    return !selected;
  }
};
</code>```

答:
Well, you didn't show where you want to store that selected value and an ng-model in tbody tag is really awkward, let me try to help

```<code><tr ng-keydown="keydownevt(ed)" tabindex="0" ng-class="{selected: ed.selected}" class="inventor-row" ng-repeat="ed in educators">
        <td class="inventor-col">
          <div><strong>{{ed.lastName}}, {{ed.firstName}}</strong></div>
          <div>{{ed.address}}</div>
          <div>{{ed.country}}</div>
        </td>
      </tr>

$scope.keydownevt = function (ed) {
          $scope.keydownkeycode = event.keyCode;
          var selected = ed.selected || false;
          if (event.keyCode === 13) {
            // add focus
            return !selected;
          }
      };
</code>```

Then you create a css class called ".selected" that paint that row or something

ContentLicense: CC BY-SA 4.0

Body:
I have a table using ng-repeat... I want to be able to allow the users to select an item in the table using the key 'enter' which is equal to the keydown event 13. When a user clicks enter, I want to be able to focus in on the specific table row and make the variable 'selected' to true. When the user clicks on enter the second time, I want the 'selected' field to be set to false.

Here is what I have so far, any ideas?

html:

{{ed.lastName}}, {{ed.firstName}}

{{ed.address}}

{{ed.country}}

JS:

$scope.keydownevt = function () {
  $scope.keydownkeycode = event.keyCode;
  var selected = false;
  if (event.keyCode === 13) {
    // add focus
    return !selected;
  }
};

Body:
Well, you didn't show where you want to store that selected value and an ng-model in tbody tag is really awkward, let me try to help

<tr ng-keydown="keydownevt(ed)" tabindex="0" ng-class="{selected: ed.selected}" class="inventor-row" ng-repeat="ed in educators">
        <td class="inventor-col">
          <div><strong>{{ed.lastName}}, {{ed.firstName}}</strong></div>
          <div>{{ed.address}}</div>
          <div>{{ed.country}}</div>
        </td>
      </tr>

$scope.keydownevt = function (ed) {
          $scope.keydownkeycode = event.keyCode;
          var selected = ed.selected || false;
          if (event.keyCode === 13) {
            // add focus
            return !selected;
          }
      };

Then you create a css class called ".selected" that paint that row or something


问:
Is this PHP opendir() very taxing on the server?
```<code>if (is_dir($dir)) {
  if($handle = opendir($dir)) {
        while($file = readdir($handle)) {
        // Break the filename by period; if there's more than one piece, grab the last piece.
        $parts = explode(".", $file);
        if (is_array($parts) && count($parts) > 1) {
            $ext = end($parts);
            // If it's an image that we want, echo the code.
          if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
            echo "<img src=\"$path/$file\" />";
      }
    }
    closedir($handle);
  }
...
</code>```

I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.

答:
Well you could make it more efficient:

```<code>$extension = strtoupper(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($extension(array('PNG', 'JPG', 'JPEG', 'GIF'))) {
    echo '<img src="$path/$file" />';
}
</code>```

or even using glob() rather than opendir/readdir/closedir... because you can give it a pattern of file extensions.

But there's nothing inherently slow about it

Body:
if (is_dir($dir)) {
  if($handle = opendir($dir)) {
        while($file = readdir($handle)) {
        // Break the filename by period; if there's more than one piece, grab the last piece.
        $parts = explode(".", $file);
        if (is_array($parts) && count($parts) > 1) {
            $ext = end($parts);
            // If it's an image that we want, echo the code.
          if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
            echo "";
      }
    }
    closedir($handle);
  }
...

I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.

Body:
Well you could make it more efficient:

$extension = strtoupper(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($extension(array('PNG', 'JPG', 'JPEG', 'GIF'))) {
    echo '<img src="$path/$file" />';
}

or even using glob() rather than opendir/readdir/closedir... because you can give it a pattern of file extensions.

But there's nothing inherently slow about it


问:
Having cursor, how to insert (not append) a paragraph in Google Doc
I'm coding a simple google script for a Google Doc sidebar and I'm facing the following problem: I have to insert some text where cursor is located

That text needs to be a paragraph as it is an specific code that must be separated from other text. Next is the code (working)

```<code>function insertText(actionObject) {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\nblablabla";

  cursor.insertText(stringToInsert);
}
</code>```

Problem is that Google replaces \n with \r, so it is just a break line, but not a paragraph. This means, that my code works, but not as expected from technical point of view.

I cannot use appendParagraph function as it always adds it at the end of the file (and it could be needed to add that paragraph in the middle of the file).

SO, I have to use the insertParagraph(childIndex, paragraph) method available for Body object. But having the cursor, I'm not able to find a way that allows me to find out my current paragraph position and insert a new one just before...

Could anybody help me on this?

Thanks in advance!!

答:
If you want to be able to put your cursor in the middle of a paragraph and then have the text you insert become a new paragraph you could try:

```<code>function insertText() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\n\nWords to enter\n\n";

  cursor.insertText(stringToInsert);
}
</code>```

which would create a new paragraph containing "Words to enter" with a blank line before and after it.

Body:
I'm coding a simple google script for a Google Doc sidebar and I'm facing the following problem: I have to insert some text where cursor is located

That text needs to be a paragraph as it is an specific code that must be separated from other text. Next is the code (working)

function insertText(actionObject) {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\nblablabla";

  cursor.insertText(stringToInsert);
}

Problem is that Google replaces \n with \r, so it is just a break line, but not a paragraph. This means, that my code works, but not as expected from technical point of view.

I cannot use appendParagraph function as it always adds it at the end of the file (and it could be needed to add that paragraph in the middle of the file).

SO, I have to use the insertParagraph(childIndex, paragraph) method available for Body object. But having the cursor, I'm not able to find a way that allows me to find out my current paragraph position and insert a new one just before...

Could anybody help me on this?

Thanks in advance!!

Body:
If you want to be able to put your cursor in the middle of a paragraph and then have the text you insert become a new paragraph you could try:

function insertText() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\n\nWords to enter\n\n";

  cursor.insertText(stringToInsert);
}

which would create a new paragraph containing "Words to enter" with a blank line before and after it.


问:
How to bring to front on activex frame
I insert some frames (microsoft forms 2.0 frame) into the excel sheet. And I wish i could click one then bring it to front of all other frames. but it is not working. with the belowing code. frame1 still under the frame2,3,4... msobringtofront works well on normal inserted shapes, but not with the frame</p>

```<code>Private Sub Frame1_Click()
ActiveSheet.Shapes("frame1").ZOrder msoBringtofront
End Sub
</code>```

答:
Try this

```<code>Sub Sample()
    Dim oleObj As OLEObject

    Set oleObj = ActiveSheet.OLEObjects("frame1")

    oleObj.BringToFront
End Sub
</code>```

Title: How to bring to front on activex frame

Body:
I insert some frames (microsoft forms 2.0 frame) into the excel sheet. And I wish i could click one then bring it to front of all other frames. but it is not working. with the belowing code. frame1 still under the frame2,3,4... msobringtofront works well on normal inserted shapes, but not with the frame

Private Sub Frame1_Click()
ActiveSheet.Shapes("frame1").ZOrder msoBringtofront
End Sub

Body:
Try this

Sub Sample()
    Dim oleObj As OLEObject

    Set oleObj = ActiveSheet.OLEObjects("frame1")

    oleObj.BringToFront
End Sub


问:
Passing closure/ blocks in array as parameter iOS
I am trying to pass alert actions in array to a function that is used to simplify the UIAlertController configuration into one single line.
Am able to successfully pass button titles but not the alert actions.
Here is what i am doing.

```<code>+(void)showAlertWithTitle:(NSString*)title
                  message:(NSString*)alertmessage
             buttonTitles:(NSArray*)buttonTitles
            buttonActions:(NSArray*)buttonActions
         inViewController:(UIViewController*)viewController {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:alertmessage preferredStyle:UIAlertControllerStyleAlert];

    [buttonTitles enumerateObjectsUsingBlock:^(NSString* buttonTitle,NSUInteger idx,BOOL *stop){
         UIAlertAction *action = [UIAlertAction actionWithTitle:buttonTitle style:UIAlertActionStyleDefault handler: [[buttonActions objectAtIndex:idx] copy]]; //blocks should always be copied to heap from stack else they will crash
        [alert addAction:action];
    }];

    [viewController presentViewController:alert animated:YES completion:nil];

}
</code>```

The above code file was written long back so its in objective c.
I have written some new files which are in swift and i am calling the above method in swift as below.

```<code> CommonManager.showAlert(withTitle: "", message: "Feedback Sent",
       buttonTitles: ["Ok"], buttonActions: [ { (action: UIAlertAction) in

                    print("you pressed Ok alert button");

                    // call method whatever u need
                }], in: self)
</code>```

If i dont pass the closure it works fine, if passing the closure when clicking on Ok it crashes.
I also found that we need to copy a block when its passed as a collection and i did that but something is still not right which am not able to figure out. Can you tell me what i need to do here.

Thanks

答:
Rather than dealing with conversion weirdness, why not just make a native swift version?

Here's my version of the same functionality:

```<code>extension UIViewController {

    func presentAlert(title: String, message: String, actions: [UIAlertAction] = [UIAlertAction(title: "OK", style: .cancel, handler: nil)], iPadOrigin: CGRect? = nil, style: UIAlertControllerStyle = .alert, animated: Bool = true, completion: (() -> ())? = nil) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach(alert.addAction)
        alert.popoverPresentationController?.sourceView = self.view
        if let iPadOrigin = iPadOrigin {
            alert.popoverPresentationController?.sourceRect = iPadOrigin
        }

        present(alert, animated: animated, completion: completion)
    }

    func presentAlert(title: String, message: String, actions: [UIAlertAction] = [UIAlertAction(title: "OK", style: .cancel, handler: nil)], iPadButtonOrigin: UIBarButtonItem? = nil, style: UIAlertControllerStyle = .alert, animated: Bool = true, completion: (() -> ())? = nil) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach(alert.addAction)
        alert.view.tintColor = Color.BlueDarker
        alert.popoverPresentationController?.barButtonItem = iPadButtonOrigin

        present(alert, animated: animated, completion: completion)
    }
}
</code>```

It also handles iPad differences and some nice defaults so you could just do viewController.presentAlert(title: "Error", message: "Something broke") if you want a simple alert on iPhone.

Body:
I am trying to pass alert actions in array to a function that is used to simplify the UIAlertController configuration into one single line.
Am able to successfully pass button titles but not the alert actions.
Here is what i am doing.

+(void)showAlertWithTitle:(NSString*)title
                  message:(NSString*)alertmessage
             buttonTitles:(NSArray*)buttonTitles
            buttonActions:(NSArray*)buttonActions
         inViewController:(UIViewController*)viewController {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:alertmessage preferredStyle:UIAlertControllerStyleAlert];

    [buttonTitles enumerateObjectsUsingBlock:^(NSString* buttonTitle,NSUInteger idx,BOOL *stop){
         UIAlertAction *action = [UIAlertAction actionWithTitle:buttonTitle style:UIAlertActionStyleDefault handler: [[buttonActions objectAtIndex:idx] copy]]; //blocks should always be copied to heap from stack else they will crash
        [alert addAction:action];
    }];

    [viewController presentViewController:alert animated:YES completion:nil];

}

The above code file was written long back so its in objective c.
I have written some new files which are in swift and i am calling the above method in swift as below.

 CommonManager.showAlert(withTitle: "", message: "Feedback Sent",
       buttonTitles: ["Ok"], buttonActions: [ { (action: UIAlertAction) in

                    print("you pressed Ok alert button");

                    // call method whatever u need
                }], in: self)

If i dont pass the closure it works fine, if passing the closure when clicking on Ok it crashes.
I also found that we need to copy a block when its passed as a collection and i did that but something is still not right which am not able to figure out. Can you tell me what i need to do here.

Thanks

Body:
Rather than dealing with conversion weirdness, why not just make a native swift version?

Here's my version of the same functionality:

extension UIViewController {

    func presentAlert(title: String, message: String, actions: [UIAlertAction] = [UIAlertAction(title: "OK", style: .cancel, handler: nil)], iPadOrigin: CGRect? = nil, style: UIAlertControllerStyle = .alert, animated: Bool = true, completion: (() -> ())? = nil) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach(alert.addAction)
        alert.popoverPresentationController?.sourceView = self.view
        if let iPadOrigin = iPadOrigin {
            alert.popoverPresentationController?.sourceRect = iPadOrigin
        }

        present(alert, animated: animated, completion: completion)
    }

    func presentAlert(title: String, message: String, actions: [UIAlertAction] = [UIAlertAction(title: "OK", style: .cancel, handler: nil)], iPadButtonOrigin: UIBarButtonItem? = nil, style: UIAlertControllerStyle = .alert, animated: Bool = true, completion: (() -> ())? = nil) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach(alert.addAction)
        alert.view.tintColor = Color.BlueDarker
        alert.popoverPresentationController?.barButtonItem = iPadButtonOrigin

        present(alert, animated: animated, completion: completion)
    }
}

It also handles iPad differences and some nice defaults so you could just do viewController.presentAlert(title: "Error", message: "Something broke") if you want a simple alert on iPhone.


问:
Angular - How to correctly import md5 hash in Angular 2 typescript file?
I tried to use md5 hash for hashing user password in Angular 2, but for some reason when I run my application Md5 module is not recognized.

I have also imported it in typescript file like this:
import { Md5 } from 'ts-md5/dist/md5';

For me it's weird that Md5 is recognized in Visual Studio, but in Google Chrome I get error as you can see on picture. So my question is where is the mistake and how to fix it?

答:
If you are using systemJS (systemjs.config) then in that file you will need to include:

```<code>map:   {
          'ts-md5': 'node_modules/ts-md5',
       }
packages: {
          'ts-md5': {main: '/md5.js'},
       }
</code>```

Look for both 'map' and 'packages' inside of systemjs.config and then include 'ts-md5' in them. This will tell the app where to look for those files.

Also make sure that you have installed it first using npm install ts-md5 --save

Body:
If you are using systemJS (systemjs.config) then in that file you will need to include:

map:   {
          'ts-md5': 'node_modules/ts-md5',
       }
packages: {
          'ts-md5': {main: '/md5.js'},
       }

Look for both 'map' and 'packages' inside of systemjs.config and then include 'ts-md5' in them. This will tell the app where to look for those files.

Also make sure that you have installed it first using npm install ts-md5 --save


问:
Django newsletter by subscribed tags
I have some Django app, in which you can add tagged objects. There's sth like

```<code>auto_tags = TagAutocompleteField(_(u'Tags'), default='', blank=True)
</code>```

in models.py file.

How can I create a newsletter which will send an e-mail notification when a new object tagged with one of subscribed tags is created?
Thanks in advance :D

答:
I would do this using django's built-in signals. You can register a function to be called when an object is saved, and then send emails to subscibers in that function. The code would looks something like this</p>

```<code>from django.db.signals import post_save
from my_app.models import MyModel

def my_function(sender, instance, created, *args, **kwargs):
    if not created:
        return  # break if it's being edited
    # check tags for subscribers
    # send email to subscribers

post_save.connect(my_function, sender=MyModel)
</code>```

Title: Django newsletter by subscribed tags

Body:
I have some Django app, in which you can add tagged objects. There's sth like

auto_tags = TagAutocompleteField(_(u'Tags'), default='', blank=True)

in models.py file.

How can I create a newsletter which will send an e-mail notification when a new object tagged with one of subscribed tags is created?
Thanks in advance :D

Body:
I would do this using django's built-in signals. You can register a function to be called when an object is saved, and then send emails to subscibers in that function. The code would looks something like this

from django.db.signals import post_save
from my_app.models import MyModel

def my_function(sender, instance, created, *args, **kwargs):
    if not created:
        return  # break if it's being edited
    # check tags for subscribers
    # send email to subscribers

post_save.connect(my_function, sender=MyModel)


问:
Event notifications Twilio Video
Is it possible to receive notifications on events from Twilio Video on client side through the token the same way as for the Twilio Voice, aka as room.on('participantConnected'), or every event is coming through the status callback URL set in the Room settings? Through the webhook, the events are arriving as soon as i take an action through the client, but otherwise, no notification appears as per the example from the Twilio Video website:

```<code>Twilio.Video.connect('$TOKEN', {name:'my-new-room'}).then(function(room) {
  console.log('Successfully joined a Room: ', room);
  room.on('participantConnected', function(participant) {
    console.log('A remote Participant connected: ', participant);
  })
}, function(error) {
    console.error('Unable to connect to Room: ' +  error.message);
});
</code>```

Right now i am using a webhook of form

```<code>app.post('/video',(req, res) => {
    room = req.body;
room.on('disconnected', function (room, error) {
    console.log('a');
});
});
</code>```

答: Well i kinda figured it out and it's a bit wtf... so apparently if you are a local participant, your events won't appear in the room _events to be picked up by room.on('event'). They will appear in the room->localParticipant-> _events room.localParticipant.on('event') which is a bit weird in my opinion, but i'm ok with that... not quite straight forward, but it does the job once you figure it out. Hope this will help someone :)</p>

Title: Event notifications Twilio Video

Body:
Is it possible to receive notifications on events from Twilio Video on client side through the token the same way as for the Twilio Voice, aka as room.on('participantConnected'), or every event is coming through the status callback URL set in the Room settings? Through the webhook, the events are arriving as soon as i take an action through the client, but otherwise, no notification appears as per the example from the Twilio Video website:

Twilio.Video.connect('$TOKEN', {name:'my-new-room'}).then(function(room) {
  console.log('Successfully joined a Room: ', room);
  room.on('participantConnected', function(participant) {
    console.log('A remote Participant connected: ', participant);
  })
}, function(error) {
    console.error('Unable to connect to Room: ' +  error.message);
});

Right now i am using a webhook of form

app.post('/video',(req, res) => {
    room = req.body;
room.on('disconnected', function (room, error) {
    console.log('a');
});
});


问:
Auto-resizing UITableViewCell shadow is off
I have a custom UITableViewCell with a self sizing UILabel and a shadow.

```<code>class CustomCell: UITableViewCell {

  @IBOutlet weak var titleLabel: UILabel!
  @IBOutlet weak var cellBackgroundView: UIView!
  @IBOutlet weak var creationDateLabel: UILabel!

  override func layoutSubviews() {
    super.layoutSubviews()
    self.cellBackgroundView.layer.cornerRadius = 12

    self.cellBackgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(1.0).cgColor
    self.cellBackgroundView.layer.shadowOffset = CGSize.zero
    self.cellBackgroundView.layer.shadowRadius = 9
    self.cellBackgroundView.layer.shadowOpacity = 0.8
    self.cellBackgroundView.layer.shadowPath = UIBezierPath(rect: self.cellBackgroundView.bounds).cgPath
    self.cellBackgroundView.layer.masksToBounds = false
    self.cellBackgroundView.layer.shouldRasterize = true

    self.cellBackgroundView.layer.rasterizationScale = UIScreen.main.scale
  }
}
</code>```

I've tried to implement this code in layoutSubviews(), cellForRowAt: indexPath and willDisplay cell but it is always off and not centered:

What's the correct way to implement it?

Edit: It works when I start scrolling in the tableView.

Edit 2: This is how it should look like:

Thanks!

答:
Try the code you posted without the line:

```<code>self.cellBackgroundView.layer.shadowPath = UIBezierPath(rect: self.cellBackgroundView.bounds).cgPath
</code>```

That should do the trick.

Body:
I have a custom UITableViewCell with a self sizing UILabel and a shadow.

class CustomCell: UITableViewCell {

  @IBOutlet weak var titleLabel: UILabel!
  @IBOutlet weak var cellBackgroundView: UIView!
  @IBOutlet weak var creationDateLabel: UILabel!

  override func layoutSubviews() {
    super.layoutSubviews()
    self.cellBackgroundView.layer.cornerRadius = 12

    self.cellBackgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(1.0).cgColor
    self.cellBackgroundView.layer.shadowOffset = CGSize.zero
    self.cellBackgroundView.layer.shadowRadius = 9
    self.cellBackgroundView.layer.shadowOpacity = 0.8
    self.cellBackgroundView.layer.shadowPath = UIBezierPath(rect: self.cellBackgroundView.bounds).cgPath
    self.cellBackgroundView.layer.masksToBounds = false
    self.cellBackgroundView.layer.shouldRasterize = true

    self.cellBackgroundView.layer.rasterizationScale = UIScreen.main.scale
  }
}

I've tried to implement this code in layoutSubviews(), cellForRowAt: indexPath and willDisplay cell but it is always off and not centered:

What's the correct way to implement it?

Edit: It works when I start scrolling in the tableView.

Edit 2: This is how it should look like:

Thanks!

Body:
Try the code you posted without the line:

self.cellBackgroundView.layer.shadowPath = UIBezierPath(rect: self.cellBackgroundView.bounds).cgPath

That should do the trick.


问:
Xpath - How to select related cousin data
```<code><html>
    <table border="1">
        <tbody>
            <tr>
                <td>
                    <table border="1">
                        <tbody>
                            <tr>
                                <th>aaa</th>
                                <th>bbb</th>
                                <th>ccc</th>
                                <th>ddd</th>
                                <th>eee</th>
                                <th>fff</th>
                            </tr>
                            <tr>
                                <td>111</td>
                                <td>222</td>
                                <td>333</td>
                                <td>444</td>
                                <td>555</td>
                                <td>666</td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>
</html>
</code>```

How can i select specific related cousin data using xpath, The desired output would be be:

```<code><th>aaa</th>
<th>ccc</th>
<th>fff</th>
<td>111</td>
<td>333</th>
<td>666</td>
</code>```

The most important aspect of the xpath is that i am looking to be able to include or exclude certain  tags and their corresponding tags

So based on the answers so far the closest I have is:

```<code>//th[not(contains(text(), "ddd"))] | //tr[2]/td[not(position()=4)]
</code>```

Is there any way of not explicitly using position()=4 but instead reference the corresponding th tag

答:
Using XPath 3.0 you can structure that into</p>

```<code>let $th := //table/tbody/tr[1]/th,
$filteredTh := $th[not(. = ("bbb", "ddd", "eee"))],
$pos := $filteredTh!index-of($th, .)
return ($filteredTh, //table/tbody/tr[position() gt 1]/td[position() = $pos])
</code>```

Body:
                                aaa
                                bbb
                                ccc
                                ddd
                                eee
                                fff

                                111
                                222
                                333
                                444
                                555
                                666

How can i select specific related cousin data using xpath, The desired output would be be:

aaa
ccc
fff
111
333
666

The most important aspect of the xpath is that i am looking to be able to include or exclude certain  tags and their corresponding tags

So based on the answers so far the closest I have is:

//th[not(contains(text(), "ddd"))] | //tr[2]/td[not(position()=4)]

Is there any way of not explicitly using position()=4 but instead reference the corresponding th tag

Body:
Using XPath 3.0 you can structure that into

let $th := //table/tbody/tr[1]/th,
$filteredTh := $th[not(. = ("bbb", "ddd", "eee"))],
$pos := $filteredTh!index-of($th, .)
return ($filteredTh, //table/tbody/tr[position() gt 1]/td[position() = $pos])


问:
what creates the default ObjectID in mongodb?
Quite new to MongoDB. Going through the documentation.

From https://docs.mongodb.com/manual/reference/method/db.collection.insert/#id-field

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

Here it says MongoDB will create the _id.

From https://docs.mongodb.com/manual/reference/method/db.collection.save/?_ga=2.24854906.1181826191.1496665143-146886871.1493019056#save-a-new-document-without-specifying-an-id-field

During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document.

And here, it says Mongo shell.

Is it the mongo shell that creates the default ObjectID or mongod? Hope someone can clarify!

答: If the client doesn't provide the _id, the MongoDB server will do it. The shell is just another type of client; it provides the _id for inserted documents, so the server doesn't need to. But other drivers/clients may not, so in those cases the server does.


问:
Facebook Flow - how to return a type casted property from deeply nested object?
I have a flow type that's a deeply nested object.  I want to create a function that extracts a specific property, if that property exists on an object of that type, and that property value is of that type:

Viewable on try flow here

```<code>/* @flow */

type DeeplyNested = {
  [string]: string | DeeplyNested
};

function getDogs(deeplyNested: DeeplyNested): ?DeeplyNested {
  return (deeplyNested.dogs: DeeplyNested);
}

let someThingWithDogs = {
  dogs: {
    somethingElse: 'yes'
  }
}

let result = getDogs(someThingWithDogs);
</code>```

I get the error:

return (deeplyNested.dogs: DeeplyNested);
               ^ string.

This type is incompatible with return (deeplyNested.dogs: DeeplyNested);
                                  ^ object type

Is there a way to check first if the property is of that type, then cast and return that property?

答:
Figured it out, just need to check if it's an object:</p>

```<code>function getDogs(deeplyNested: DeeplyNested): ?DeeplyNested {
  if (typeof deeplyNested.dogs === 'object') return deeplyNested.dogs;
}
</code>```

Body:
I have a flow type that's a deeply nested object.  I want to create a function that extracts a specific property, if that property exists on an object of that type, and that property value is of that type:

Viewable on try flow here

/* @flow */

type DeeplyNested = {
  [string]: string | DeeplyNested
};

function getDogs(deeplyNested: DeeplyNested): ?DeeplyNested {
  return (deeplyNested.dogs: DeeplyNested);
}

let someThingWithDogs = {
  dogs: {
    somethingElse: 'yes'
  }
}

let result = getDogs(someThingWithDogs);

I get the error:

return (deeplyNested.dogs: DeeplyNested);
               ^ string.

This type is incompatible with return (deeplyNested.dogs: DeeplyNested);
                                  ^ object type

Is there a way to check first if the property is of that type, then cast and return that property?

Body:
Figured it out, just need to check if it's an object:

function getDogs(deeplyNested: DeeplyNested): ?DeeplyNested {
  if (typeof deeplyNested.dogs === 'object') return deeplyNested.dogs;
}


问:
How should i solve this error:bad operand types for binary operator '&&'
I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'

```<code>  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }
</code>```

答:
Here >> is a signed shift right operator. For example

```<code>  int x = -4;
  System.out.println(x>>1);
  int y = 4;
  System.out.println(y>>1);
</code>```

will give you

```<code>-2
2
</code>```

The same applies for shift Left  << operator.

You want to check greater than or less than. So for that purpose you need '>' or '<' operator.
so the correct conditional checking will be like

```<code>  if((n%2==0) && (n>6) && (n<20)) {
       ans = "Not Weird"
   }
</code>```

Body:
I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'

  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }

Body:
Here >> is a signed shift right operator. For example

  int x = -4;
  System.out.println(x>>1);
  int y = 4;
  System.out.println(y>>1);

will give you

-2
2

The same applies for shift Left  << operator.

You want to check greater than or less than. So for that purpose you need '>' or '<' operator.
so the correct conditional checking will be like

  if((n%2==0) && (n>6) && (n<20)) {
       ans = "Not Weird"
   }


问:
How to obtain a list of numbers that are divided by a certain number using the filter function in Python?
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

```<code>filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]
</code>```

So I thought about creating a function called is_factor:

```<code>def is_factor(a, b):
    return a % b == 0
</code>```

Then, I wanted to call the function this way:

```<code>def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))
</code>```

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

答:
You can try this without using filter:</p>

```<code>def is_factor(a, b):
   return [i for i in a if i%b == 0]

print(is_factor([1, 2, 3, 4, 5], 2))
</code>```

Body:
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]

So I thought about creating a function called is_factor:

def is_factor(a, b):
    return a % b == 0

Then, I wanted to call the function this way:

def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

Body:
You can try this without using filter:

def is_factor(a, b):
   return [i for i in a if i%b == 0]

print(is_factor([1, 2, 3, 4, 5], 2))


问:
How do I load multiple XML nodes with two attributes as key-value pairs?
I have a XML file which is like this;

```<code><?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>
</code>```

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

```<code>        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }
</code>```

I'm trying to get values as key-value pairs like these;

```<code>BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть
</code>```

But I get these;

```<code>BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть
</code>```

If someone writes the code and explains the exact logic, i would be very appreciated.

答:
I'd recommend an alternative to XmlDocument:use linq XDocument instead and transform it to Dictionary:

```<code>var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Data>
 <StringMaps>
  <Menu>
   <String Target=""BtnFile"" Link=""Файл"" />
   <String Target=""BtnOpen"" Link=""Открыто"" />
   <String Target=""BtnSave"" Link=""Сохранить"" />
   <String Target=""BtnClose"" Link=""Закрыть"" />
  </Menu>
 </StringMaps>
</Data>";

XDocument xdoc = XDocument.Parse(xml);

var dict = xdoc
    .Descendants("String")
    .ToDictionary(n => n.Attribute("Target").Value, n => n.Attribute("Link").Value);

foreach (var keyValuePair in dict)
{
    MessageBox.Show($"{keyValuePair.Key} = {keyValuePair.Value}");
}
</code>```

Body:
I have a XML file which is like this;

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }

I'm trying to get values as key-value pairs like these;

BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть

But I get these;

BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть

If someone writes the code and explains the exact logic, i would be very appreciated.

Body:
I'd recommend an alternative to XmlDocument:use linq XDocument instead and transform it to Dictionary:

var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Data>
 <StringMaps>
  <Menu>
   <String Target=""BtnFile"" Link=""Файл"" />
   <String Target=""BtnOpen"" Link=""Открыто"" />
   <String Target=""BtnSave"" Link=""Сохранить"" />
   <String Target=""BtnClose"" Link=""Закрыть"" />
  </Menu>
 </StringMaps>
</Data>";

XDocument xdoc = XDocument.Parse(xml);

var dict = xdoc
    .Descendants("String")
    .ToDictionary(n => n.Attribute("Target").Value, n => n.Attribute("Link").Value);

foreach (var keyValuePair in dict)
{
    MessageBox.Show($"{keyValuePair.Key} = {keyValuePair.Value}");
}


问:
C++ list with array of strings
I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful

My input must be something like:

Peter Evens 4.86

*other people**

*average result of the group**

*the one with the heighest grade**

*the one with lowest grade**

This is what I have done for now:

```<code>#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            for (int p = 0; p < n; p++)
                cin >> list[i][j][p];
        }
}
int main() {
    char list[31][MAXN][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}
</code>```

答:
You don't need to run the third iteration since you don't have to store the input character by character. The third dimension can be used for storing the entire string.

Try the following way. Observe the corrections i have made in your snippet.

```<code>#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][3][MAXM], int n) {
    for (int i = 0; i < n; i++) //number of entries
        for (int j = 0; j < 3; j++) { //3 fields - fname, lname and marks
                cin >> list[i][j];
        }
}
int main() {
    char list[31][3][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}
</code>```

Title: C++ list with array of strings

Body:
I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful

My input must be something like:

Peter Evens 4.86

*other people**

*average result of the group**

*the one with the heighest grade**

*the one with lowest grade**

This is what I have done for now:

#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            for (int p = 0; p < n; p++)
                cin >> list[i][j][p];
        }
}
int main() {
    char list[31][MAXN][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}

Body:
You don't need to run the third iteration since you don't have to store the input character by character. The third dimension can be used for storing the entire string.

Try the following way. Observe the corrections i have made in your snippet.

#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][3][MAXM], int n) {
    for (int i = 0; i < n; i++) //number of entries
        for (int j = 0; j < 3; j++) { //3 fields - fname, lname and marks
                cin >> list[i][j];
        }
}
int main() {
    char list[31][3][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}


问:
How to reading out ListView using MultiThreading
I want to read out a listview in a form.

My goal is to let the program read the first 3 lines, then it have to sleep some millisecons (Random) and then it has to use the next 3 lines until all listviewitems are used.

I've tried it like this, but the program always checked the whole list after the delay of the first 3 lines.

```<code>List<Task> Tasklist = new List<Task>();
            List<ListViewItem> lit = new List<ListViewItem>();

int aktuellethreads = 0;
int maximalethreads = 3;

            this.Invoke(new Action(() =>
            {
                foreach (ListViewItem itt in listView1.Items)
                {
                    lit.Add(itt);
                }
            }));

            foreach (ListViewItem i in lit)
            {
                if (aktuellethreads < maximalethreads)
                {
                    Task t = Task.Run(() =>
                    {
                        Random rnd = new Random();
                        Thread.Sleep(rnd.Next(300, 10000));
                    });
                    Tasklist.Add(t);
                    aktuellethreads++;
                }
                    if(aktuellethreads >= maximalethreads)
                    {
                    Task.WaitAny(Tasklist.ToArray());
                    aktuellethreads--;
                     }
             }
</code>```

答:
To make it proper you should change your checking approach.

```<code>List<Task> tasklist = new List<Task>();
List<ListViewItem> lit = new List<ListViewItem>();

int maximalethreads = 3;

this.Invoke(new Action(() =>
{
    foreach (ListViewItem itt in listView1.Items)
    {
        lit.Add(itt);
    }
}));

foreach (ListViewItem i in lit)
{
    Task t = Task.Run(() =>
    {
        Random rnd = new Random();
        Thread.Sleep(rnd.Next(300, 10000));
    });
    tasklist.Add(t);

    if(tasklist.Count >= maximalethreads)
    {
        Task.WaitAll(tasklist.ToArray());
        tasklist.Clear();
    }
}
</code>```

It should work, I am not 100% sure of syntax, as I wrote this code in SO answer box, but I think it works.

Body:
I want to read out a listview in a form.

My goal is to let the program read the first 3 lines, then it have to sleep some millisecons (Random) and then it has to use the next 3 lines until all listviewitems are used.

I've tried it like this, but the program always checked the whole list after the delay of the first 3 lines.

List<Task> Tasklist = new List<Task>();
            List<ListViewItem> lit = new List<ListViewItem>();

int aktuellethreads = 0;
int maximalethreads = 3;

            this.Invoke(new Action(() =>
            {
                foreach (ListViewItem itt in listView1.Items)
                {
                    lit.Add(itt);
                }
            }));

            foreach (ListViewItem i in lit)
            {
                if (aktuellethreads < maximalethreads)
                {
                    Task t = Task.Run(() =>
                    {
                        Random rnd = new Random();
                        Thread.Sleep(rnd.Next(300, 10000));
                    });
                    Tasklist.Add(t);
                    aktuellethreads++;
                }
                    if(aktuellethreads >= maximalethreads)
                    {
                    Task.WaitAny(Tasklist.ToArray());
                    aktuellethreads--;
                     }
             }

Body:
To make it proper you should change your checking approach.

List<Task> tasklist = new List<Task>();
List<ListViewItem> lit = new List<ListViewItem>();

int maximalethreads = 3;

this.Invoke(new Action(() =>
{
    foreach (ListViewItem itt in listView1.Items)
    {
        lit.Add(itt);
    }
}));

foreach (ListViewItem i in lit)
{
    Task t = Task.Run(() =>
    {
        Random rnd = new Random();
        Thread.Sleep(rnd.Next(300, 10000));
    });
    tasklist.Add(t);

    if(tasklist.Count >= maximalethreads)
    {
        Task.WaitAll(tasklist.ToArray());
        tasklist.Clear();
    }
}

It should work, I am not 100% sure of syntax, as I wrote this code in SO answer box, but I think it works.


问:
accepting keys without loop in quickbasic
I'm working on an program that opens up different programs for each different key inside QuickBasic 4.5 (for a game.) Unfortunately, looping more than one INKEY$ command causes it to not register most of the time.

Is there any library/method to get around this?

Here's what I put in:

```<code>DO
IF INKEY$ = "n" GOTO 2000
IF INKEY$ = "y" GOTO 3000
IF INKEY$ = "e" GOTO 4000
LOOP
</code>```

答:
Something like this should work. But I suggest you start with learning how to save to variables, and you do not need GOTO in Basic, there are other ways which makes the program easier to change in the future.</p>

```<code>DIM KeyPressed AS STRING

INPUT "Please Enter A Key (y,n,e): ", KeyPressed

KeyPressed = LCASE$(KeyPressed)

SELECT CASE KeyPressed
  CASE "n"
     GOTO 2000
  CASE "y"
     GOTO 3000
  CASE "e"
     GOTO 4000
END SELECT
</code>```

Body:
I'm working on an program that opens up different programs for each different key inside QuickBasic 4.5 (for a game.) Unfortunately, looping more than one INKEY$ command causes it to not register most of the time.

Is there any library/method to get around this?

Here's what I put in:

DO
IF INKEY$ = "n" GOTO 2000
IF INKEY$ = "y" GOTO 3000
IF INKEY$ = "e" GOTO 4000
LOOP

Body:
Something like this should work. But I suggest you start with learning how to save to variables, and you do not need GOTO in Basic, there are other ways which makes the program easier to change in the future.

DIM KeyPressed AS STRING

INPUT "Please Enter A Key (y,n,e): ", KeyPressed

KeyPressed = LCASE$(KeyPressed)

SELECT CASE KeyPressed
  CASE "n"
     GOTO 2000
  CASE "y"
     GOTO 3000
  CASE "e"
     GOTO 4000
END SELECT


问:
Python Diff Two Multiline Strings Like GitHub
I want to achieve a diff output like github's commit diff view. And I tried this:

```<code>import difflib

first = """
def
baz
"""

second = """
deff
ba
bar
foo
"""

diff = ''
for text in difflib.unified_diff(first, second):
    for prefix in ('---', '+++', '@@'):
        if text.startswith(prefix):
            break
    else:
        diff += text
</code>```

The output is:

```<code> d e f+f
 b a-z
+b+a+r+
+f+o+o+
</code>```

How can I achieve,

```<code>1 def+f
2 ba-z
+
3 bar
4 foo
# -
# 5 line
# 6 line
</code>```

an output just like this. Thanks.

答:
I'm not quite sure what format you mean with gitlab; I've not seen char-by-char diffs in gitlab like your example. If you want a more standardish line-by-line output, then I think you just have to pass lists to the diff function:

```<code>for text in difflib.unified_diff(first.split("\n"), second.split("\n")):
    if text[:3] not in ('+++', '---', '@@ '):
        print text
</code>```

As every line is different in your example, diff is just going to see each line as having been totally changed and give you an output like:

```<code>-def
-baz
+deff
+ba
+bar
+foo
</code>```

If you want to do something more fancy, you can treat the data as a single string (as you were) and then try and split on new-lines. The return format seems to be "{operation}{char}" (including new line chars), so you can group and detect lines which all have the same operation and apply the correct logic.

I can't quite work out the rules you're trying to apply based on your example (are you grouping all mixed lines, then added lines then removed lines or something else?), so I can't give you an exact example.

Body:
I want to achieve a diff output like github's commit diff view. And I tried this:

import difflib

first = """
def
baz
"""

second = """
deff
ba
bar
foo
"""

diff = ''
for text in difflib.unified_diff(first, second):
    for prefix in ('---', '+++', '@@'):
        if text.startswith(prefix):
            break
    else:
        diff += text

The output is:

 d e f+f
 b a-z
+b+a+r+
+f+o+o+

How can I achieve,

1 def+f
2 ba-z
+
3 bar
4 foo
# -
# 5 line
# 6 line

an output just like this. Thanks.

Body:
I'm not quite sure what format you mean with gitlab; I've not seen char-by-char diffs in gitlab like your example. If you want a more standardish line-by-line output, then I think you just have to pass lists to the diff function:

for text in difflib.unified_diff(first.split("\n"), second.split("\n")):
    if text[:3] not in ('+++', '---', '@@ '):
        print text

As every line is different in your example, diff is just going to see each line as having been totally changed and give you an output like:

-def
-baz
+deff
+ba
+bar
+foo

If you want to do something more fancy, you can treat the data as a single string (as you were) and then try and split on new-lines. The return format seems to be "{operation}{char}" (including new line chars), so you can group and detect lines which all have the same operation and apply the correct logic.

I can't quite work out the rules you're trying to apply based on your example (are you grouping all mixed lines, then added lines then removed lines or something else?), so I can't give you an exact example.


问:
How to do One on One chat in Socket.io using Node JS server?
I am working on a Chat application. I am using this for the chat demo app. But this is not what I want. I want to implement one on one chat in my application. But this is one-to-many chat app(Group chat). Please help me to understand the concept behind one-on-one chat using Node JS server. How to filter it?</p>

答:
Socket.io gives you flexibility to choose who is going to recieve the message. You can explore all ways to emit an event here

The easiest way to implement one-on-one chat is by using rooms.

You can join both users into one room and emit messages to that room.

```<code>io.on('connection',function(socket){
  socket.join(exampleRoom);

  socket.to(exampleRoom).emit('message', "a message to everyone in the room,except me");
})
</code>```

Body:
Socket.io gives you flexibility to choose who is going to recieve the message. You can explore all ways to emit an event here

The easiest way to implement one-on-one chat is by using rooms.

You can join both users into one room and emit messages to that room.

io.on('connection',function(socket){
  socket.join(exampleRoom);

  socket.to(exampleRoom).emit('message', "a message to everyone in the room,except me");
})


问:
Reading formatted text from a file
I'm tring to read the follwing text file with Matlab:

```<code>00000008.jpg 1 2 1
00000001.jpg 1 2 1
00000054.jpg 1 2 1
</code>```

What I want to extract is each column of each line in order to access it.

I've tried the following code:

```<code>fileLabels = fopen('file.txt');
C = textscan(fileLabels,'%s %n %n %n');
celldisp(C)
</code>```

And it returns:

```<code>C{1}{1} =
00000008.jpg

C{1}{2} =
00000001.jpg

C{1}{3} =
00000054.jpg
</code>```

Which is good, because this way I have the first string separated in cells, but, when I try to get the numbers, they appear this way:

```<code>C{2} =
     1
     1
     1

C{3} =
     2
     2
     2

C{4} =
     1
     1
     1
</code>```

Instead of having them separated in cells, they appear all in one cell. If I try to access to one cell of the 2º column, it appears the following error:

```<code>>> C{2}{1}
Cell contents reference from a non-cell array object.
</code>```

Please, anyone knows how to extract each column separately line by line?

答:
The numbers are in an array rather than cell, which should be more convenient for later process. You can access the numbers by

```<code>C{2}(1) % C{2} is 3x1 array, not cell
</code>```

If this does not fit your need, you may try some function like importdata.

Title: Reading formatted text from a file

Body:
I'm tring to read the follwing text file with Matlab:

00000008.jpg 1 2 1
00000001.jpg 1 2 1
00000054.jpg 1 2 1

What I want to extract is each column of each line in order to access it.

I've tried the following code:

fileLabels = fopen('file.txt');
C = textscan(fileLabels,'%s %n %n %n');
celldisp(C)

And it returns:

C{1}{1} =
00000008.jpg

C{1}{2} =
00000001.jpg

C{1}{3} =
00000054.jpg

Which is good, because this way I have the first string separated in cells, but, when I try to get the numbers, they appear this way:

C{2} =
     1
     1
     1

C{3} =
     2
     2
     2

C{4} =
     1
     1
     1

Instead of having them separated in cells, they appear all in one cell. If I try to access to one cell of the 2º column, it appears the following error:

>> C{2}{1}
Cell contents reference from a non-cell array object.

Please, anyone knows how to extract each column separately line by line?

Body:
The numbers are in an array rather than cell, which should be more convenient for later process. You can access the numbers by

C{2}(1) % C{2} is 3x1 array, not cell

If this does not fit your need, you may try some function like importdata.


问:
Show read and not readed notifications
I'm developing a custom notifications system with PHP and MariaDB. I'm struggling with the "read notification" logic.

This is my notifications table:

```<code>|id | title       | content       | uid        | visibility | timestamp |
+------------------------------------------------------------------------+
|11 | Other title | Other content | sz46j86rd  | public     | 0123456789 |
|10 | My title    | My content    | xrgoyyzm27 | private    | 0123456789 |
... And so on ...
</code>```

And this is my notifications_viewed table:

```<code>| id | user_id | notification_uid | timestamp  |
+-----------------------------------------------+
| 2  | 1       | xrgoyyzm27       | 1234567890 |
</code>```

So, what I need is retrieve from the database the notifications and check if that notification has been viewed/readed by the current user.

I'm already showing the notifications (that works just fine) but I don't know how to check if each of the last 5 notifications that I show in the topbar dropdown has been seen/view/read by the current user. Maybe some kinf of SQL join?

答:
Use LEFT JOIN

```<code>SELECT n.*, IF(nv.id IS NULL, 'No', 'Yes') AS viewed
FROM notifications AS n
LEFT JOIN notifications_viewed AS nv ON n.uid = nv.notification_uid AND nv.user_id = :current_user
</code>```

BTW, foreign keys usually refer to the primary key of the parent table.

Title: Show read and not readed notifications

Body:
I'm developing a custom notifications system with PHP and MariaDB. I'm struggling with the "read notification" logic.

This is my notifications table:

|id | title       | content       | uid        | visibility | timestamp |
+------------------------------------------------------------------------+
|11 | Other title | Other content | sz46j86rd  | public     | 0123456789 |
|10 | My title    | My content    | xrgoyyzm27 | private    | 0123456789 |
... And so on ...

And this is my notifications_viewed table:

| id | user_id | notification_uid | timestamp  |
+-----------------------------------------------+
| 2  | 1       | xrgoyyzm27       | 1234567890 |

So, what I need is retrieve from the database the notifications and check if that notification has been viewed/readed by the current user.

I'm already showing the notifications (that works just fine) but I don't know how to check if each of the last 5 notifications that I show in the topbar dropdown has been seen/view/read by the current user. Maybe some kinf of SQL join?

Body:
Use LEFT JOIN

SELECT n.*, IF(nv.id IS NULL, 'No', 'Yes') AS viewed
FROM notifications AS n
LEFT JOIN notifications_viewed AS nv ON n.uid = nv.notification_uid AND nv.user_id = :current_user

BTW, foreign keys usually refer to the primary key of the parent table.


问:
Socket.io client fails to reconnect to server after an abrupt disconnection
I am using the socket.io NodeJs server library and the Swift client library. Majority of the time the client successfully reconnects to the server after a disconnection, however intermittently we are seeing abrupt disconnections and then the client is never able to reconnect.

In the server logs, I see the client sending a connection attempt at the defined re-try interval, however it just never successfully establishes the connection and then we get a ping timeout.

There is surprisingly very little support for Socket.io which makes this extremely difficult to solve.

答:
I figured out a solution to our problem by forcing a new engine to be created in the client upon reconnections. When creating the SocketIOClient object, set the forceNew variable to true which allows the client to create a new engine and thus always successfully establishes the connection.

```<code>return SocketIOClient(socketURL: socketURL, config: [.forceNew(true)])
</code>```

Body:
I figured out a solution to our problem by forcing a new engine to be created in the client upon reconnections. When creating the SocketIOClient object, set the forceNew variable to true which allows the client to create a new engine and thus always successfully establishes the connection.

return SocketIOClient(socketURL: socketURL, config: [.forceNew(true)])


问:
Entity list relationships in Android Room
I'm trying to load entity sublist, but i would like to avoid to do 2 queries.

I'm thinking about do query inside TypeConverter, but i really don't know if it's good idea.

My entities:

```<code>@Entity
class Region(
        @PrimaryKey(autoGenerate = true)
        var id: Int = 0,
        var name: String = "",
        var locales: List<Locale> = listOf())

@Entity(foreignKeys = arrayOf(ForeignKey(
        entity = Region::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("regionId"),
        onDelete = CASCADE,
        onUpdate = CASCADE
)))
class Locale(
        @PrimaryKey(autoGenerate = true)
        var id: Int = 0,
        var regionId: Int = 0,
        var name: String = "")
</code>```

DAOs :

```<code>@Dao
interface RoomRegionDao{
    @Insert
    fun insert(region: Region)

    @Delete
    fun delete(region: Region)

    @Query("select * from region")
    fun selectAll(): Flowable<List<Region>>
}

@Dao
interface RoomLocaleDao{
    @Insert
    fun insert(locale: Locale)

    @Query("select * from locale where regionId = :arg0")
    fun selectAll(regionId: Int): List<Locale>
}
</code>```

Database:

```<code>@Database(entities = arrayOf(Region::class, Locale::class), version = 1)
@TypeConverters(RoomAppDatabase.Converters::class)
abstract class RoomAppDatabase : RoomDatabase() {
    abstract fun regionDao(): RoomRegionDao
    abstract fun localeDao(): RoomLocaleDao

    inner class Converters {
        @TypeConverter
        fun toLocales(regionId: Int): List<Locale> {
            return localeDao().selectAll(regionId)
        }

        @TypeConverter
        fun fromLocales(locales: List<Locale>?): Int {
            locales ?: return 0
            if (locales.isEmpty()) return 0

            return locales.first().regionId
        }
    }
}
</code>```

It's not working because can't use inner class as converter class.

Is it a good way?

How can I load "locales list" automatically in region entity when I do RoomRegionDao.selectAll?

答:
I think that TypeConverter only works for static methods.
I say this based on the example from here and here

From the relationships section here:

"Because SQLite is a relational database, you can specify relationships between objects. Even though most ORM libraries allow entity objects to reference each other, Room explicitly forbids this."

So I guess it's best if you add @Ignore on your locales property and make a method on RoomLocaleDao thats insert List<Locale> and call it after insert Region.

The method that inserts a Region can return the inserted id.

If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.
  (https://developer.android.com/topic/libraries/architecture/room.html#daos-convenience)

Body:
I'm trying to load entity sublist, but i would like to avoid to do 2 queries.

I'm thinking about do query inside TypeConverter, but i really don't know if it's good idea.

My entities:

@Entity
class Region(
        @PrimaryKey(autoGenerate = true)
        var id: Int = 0,
        var name: String = "",
        var locales: List<Locale> = listOf())

@Entity(foreignKeys = arrayOf(ForeignKey(
        entity = Region::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("regionId"),
        onDelete = CASCADE,
        onUpdate = CASCADE
)))
class Locale(
        @PrimaryKey(autoGenerate = true)
        var id: Int = 0,
        var regionId: Int = 0,
        var name: String = "")

DAOs :

@Dao
interface RoomRegionDao{
    @Insert
    fun insert(region: Region)

    @Delete
    fun delete(region: Region)

    @Query("select * from region")
    fun selectAll(): Flowable<List<Region>>
}

@Dao
interface RoomLocaleDao{
    @Insert
    fun insert(locale: Locale)

    @Query("select * from locale where regionId = :arg0")
    fun selectAll(regionId: Int): List<Locale>
}

Database:

@Database(entities = arrayOf(Region::class, Locale::class), version = 1)
@TypeConverters(RoomAppDatabase.Converters::class)
abstract class RoomAppDatabase : RoomDatabase() {
    abstract fun regionDao(): RoomRegionDao
    abstract fun localeDao(): RoomLocaleDao

    inner class Converters {
        @TypeConverter
        fun toLocales(regionId: Int): List<Locale> {
            return localeDao().selectAll(regionId)
        }

        @TypeConverter
        fun fromLocales(locales: List<Locale>?): Int {
            locales ?: return 0
            if (locales.isEmpty()) return 0

            return locales.first().regionId
        }
    }
}

It's not working because can't use inner class as converter class.

Is it a good way?

How can I load "locales list" automatically in region entity when I do RoomRegionDao.selectAll?


答:
You can use a partial function to pass the missing argument

```<code>from functools import partial

def is_factor(a, b):
    return a % b == 0

def filter_list_by_factor(numbers_list, number):
    return list(filter(partial(is_factor, b=number), numbers_list))
</code>```

Or you can capture things inside a lambda

```<code>def filter_list_by_factor(numbers_list, number):
    return list(filter(lambda a: a % number == 0, numbers_list))
</code>```

But as the other answers suggest, a list comprehension is probably simpler to understand.

Title: How to obtain a list of numbers that are divided by a certain number using the filter function in Python?

Body:
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]

So I thought about creating a function called is_factor:

def is_factor(a, b):
    return a % b == 0

Then, I wanted to call the function this way:

def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

Body:
You can use a partial function to pass the missing argument

from functools import partial

def is_factor(a, b):
    return a % b == 0

def filter_list_by_factor(numbers_list, number):
    return list(filter(partial(is_factor, b=number), numbers_list))

Or you can capture things inside a lambda

def filter_list_by_factor(numbers_list, number):
    return list(filter(lambda a: a % number == 0, numbers_list))

But as the other answers suggest, a list comprehension is probably simpler to understand.


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答:
Python is the best choice to start programming, by far. Especially in a modern Xubuntu or similar environment, where packages exist to make GUI-based applications and much more.

There's an interactive editor where you can get the hang of things very quickly.

For a Python IDE, try PyDev or NetBeans or Geany. Me, I'm a recent NetBeans convert and I think it's an excellent IDE, even if I haven't tried it with Python (yet).

Why not try Python online and see if you like it? http://try-python.mired.org/

I like Python most for its lucidity and the ability to very quickly test out solutions.

Title: Tools used for programming in Linux


问:
find last empty string in x value and make new line
I have a string and I want to make new line on a last empty space of a 50 long string.

```<code><?php
$str = "the condition that distinguishes animals and plants from inorganic matter, including the capacity for growth, reproduction, functional activity, and continual change preceding death.";

$a = str_split($str, 50);

foreach ($a as $value) {
    $lastspace = strrpos($value, " ");
    echo chunk_split($value, $lastspace, "<br>");
}
?>
</code>```

Expected result:

the condition that distinguishes animals and

plants from inorganic matter, including the

capacity for growth, reproduction, functional

activity, and continual change preceding death.

答:
It's not always perfect (for better implementations just search wordwrap) but this normally works well:

```<code>echo wordwrap($str, 50, '<br>');
</code>```

Body:
I have a string and I want to make new line on a last empty space of a 50 long string.

<?php
$str = "the condition that distinguishes animals and plants from inorganic matter, including the capacity for growth, reproduction, functional activity, and continual change preceding death.";

$a = str_split($str, 50);

foreach ($a as $value) {
    $lastspace = strrpos($value, " ");
    echo chunk_split($value, $lastspace, "
");
}
?>

Expected result:

the condition that distinguishes animals and

plants from inorganic matter, including the

capacity for growth, reproduction, functional

activity, and continual change preceding death.

Body:
It's not always perfect (for better implementations just search wordwrap) but this normally works well:

echo wordwrap($str, 50, '<br>');


答:
Use xml linq :</p>

```<code>using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication57
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string,string> dict = doc.Descendants("String")
                .GroupBy(x => (string)x.Attribute("Target"), y => (string)y.Attribute("Link"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }

    }

}
</code>```

Title: How do I load multiple XML nodes with two attributes as key-value pairs?

Body:
I have a XML file which is like this;

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }

I'm trying to get values as key-value pairs like these;

BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть

But I get these;

BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть

If someone writes the code and explains the exact logic, i would be very appreciated.

Body:
Use xml linq :

using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication57
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string,string> dict = doc.Descendants("String")
                .GroupBy(x => (string)x.Attribute("Target"), y => (string)y.Attribute("Link"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }

    }

}


问:
Remove git mapping in Visual Studio 2015
This question has nothing to do with git itself; rather, it has to do with removing a binding/mapping to a git repository that Visual Studio 2015 (VS2015) has previously seen.

Here's a screen shot of the problem:

Notice that the remove button is grayed out (disabled). How can I remove this entry from the "Local Git Repositories" list?

答: Removing .git hidden folder worked for me.</p>


问:
Can I use git to version control Adobe Animate project
Am just wondering if Git is appropriate to use as a version control for Adobe Animate projects.

Thanks.

答: You can version all kind of files in Git (binaries too!), so there is no problem to version an Adobe Animate project in theory.</p>


问:
How do I limit the amount of job console log on Jenkins?
From time to time I encounter jobs that end-up putting Jenkins down because they log too much to the console, sometimes due to an more or less endless loop or too much verbosity.

I am looking for a solution that would prevent/stop/kill spamming jobs.

We are using Jenkins pipelines and all these occasional spamming jobs are inside sh(), which makes me think that maybe we should add some kind of smart wrapper.

Please, do not suggest fixing the spamming source instead. I asked this question because I want to prevent this kind of issue from outside the potential spammer script, that's because we have hundreds of jobs and because is impossible to avoid a sooner or later spamming bug caused by a developer mistake.

Shortly: we cannot control what is run inside the shell script, but we can control how the shell is run.

答:
You can add the returnStdout variable to your sh calls like so:

```<code>node(){
    // Eliminates returned output (you can also redirect this to a variable!)
    sh returnStdout: true, script: 'echo hi; echo hi; echo hi; echo hi;'
    // Has the normal output
    sh script: 'echo hi; echo hi; echo hi; echo hi;'
}
</code>```

Which changes to the output like so:

```<code>[Pipeline] node
Running on ***
[Pipeline] {
[Pipeline] sh
[***] Running shell script
+ echo hi
+ echo hi
+ echo hi
+ echo hi
[Pipeline] sh
[***] Running shell script
+ echo hi
hi
+ echo hi
hi
+ echo hi
hi
+ echo hi
hi
[Pipeline] }
[Pipeline] // node
</code>```

If you need to automate this so that everybody does this by default, you should look into building a Groovy Shared Library that is auto loaded in your Jenkins instance (I recommend this for more large users anyways!). Once you have that set up, make a new script for executing shell steps and ask users to use that instead of the normal sh step

Here's a good starting doc for that stuff: https://jenkins.io/doc/book/pipeline/shared-libraries/

Body:
You can add the returnStdout variable to your sh calls like so:

node(){
    // Eliminates returned output (you can also redirect this to a variable!)
    sh returnStdout: true, script: 'echo hi; echo hi; echo hi; echo hi;'
    // Has the normal output
    sh script: 'echo hi; echo hi; echo hi; echo hi;'
}

Which changes to the output like so:

[Pipeline] node
Running on ***
[Pipeline] {
[Pipeline] sh
[***] Running shell script
+ echo hi
+ echo hi
+ echo hi
+ echo hi
[Pipeline] sh
[***] Running shell script
+ echo hi
hi
+ echo hi
hi
+ echo hi
hi
+ echo hi
hi
[Pipeline] }
[Pipeline] // node

If you need to automate this so that everybody does this by default, you should look into building a Groovy Shared Library that is auto loaded in your Jenkins instance (I recommend this for more large users anyways!). Once you have that set up, make a new script for executing shell steps and ask users to use that instead of the normal sh step

Here's a good starting doc for that stuff: https://jenkins.io/doc/book/pipeline/shared-libraries/