问:
Using for each to compare multiple columns in each workbooks and copy a third colum over to one of the workbooks
I am matching two columns in a new workbook with two columns in Workbook 2, and then retrieving column B from Workbook2 and copying it to column B in the new workbook.  Some cells will be empty.  Running the following code results in nothing being copied over. I'm not sure if I am using the right approach to retrieve the information. </p>

```<code>    Sub InsertDeviceName_NewBook()

      Dim w1 As Worksheet, w2 As Worksheet, wsnew As Worksheet
      Dim wbnew As Workbook
      Dim c As Range, FR As Variant
      Dim d As Range
      Dim e As Range, rng1 As Range, rng2 As Range
      Dim lr1 As Long, lr2 As Long

      Application.ScreenUpdating = False

      Set w2 = Workbooks("Book2.xlsx").ActiveSheet
      Set w1 = Workbooks("Book1.xlsx").ActiveSheet

     w1.Range("B:D").Copy
     Set wbnew = Workbooks.Add 'creates new workbook
     Columns("A:A").Select
     ActiveSheet.Paste
     Application.CutCopyMode = False
     ActiveSheet.Name = w1.Name
     Set wsnew = wbnew.ActiveSheet 'sets the active sheet in the new workbook
     lr1 = wsnew.Cells(Rows.count, 1).End(xlUp).Row
     lr2 = w2.Cells(Rows.count, 1).End(xlUp).Row

     wsnew.Sort.SortFields.Add2 Key:=Range("B1"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With wsnew.Sort
        .SetRange Range("A1:C" & lr1)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
   End With

Columns("B:B").Insert Shift:=xlToRight, _
      CopyOrigin:=xlFormatFromLeftOrAbove

      Range("B1").Select
      ActiveCell.FormulaR1C1 = "Device Name"

      Dim lr3 As Long

      lr3 = wsnew.Cells(Rows.count, 1).End(xlUp).Row

      Set rng1 = wsnew.Range("C2:D" & lr3)
      Set rng2 = w2.Range("C2:D" & lr2)

'create a loop to find matches between columns C and D in the new workbook
'and match with columns C and D in workbook 2, upon a match retrieve the information
'in column B in workbook2 and add it to Columns B in the new workbook

For Each d In rng1
    FR = Application.Match(d, rng2)
    If IsNumeric(FR) Then
    d.Offset(, -1).Value = w2.Range("B" & FR).Value
    End If

Next d

Application.ScreenUpdating = True

End Sub
</code>```

答:
Wouldn't an Index Match formula work here? This would capture the values which match each other, then you could basically copy the results and paste as value.

This example uses a single cell as the return, but you could change it to be a row formula and return the proper results for each row.

Index Match With Multiple Criteria Example

Body:
I am matching two columns in a new workbook with two columns in Workbook 2, and then retrieving column B from Workbook2 and copying it to column B in the new workbook.  Some cells will be empty.  Running the following code results in nothing being copied over. I'm not sure if I am using the right approach to retrieve the information.

    Sub InsertDeviceName_NewBook()

      Dim w1 As Worksheet, w2 As Worksheet, wsnew As Worksheet
      Dim wbnew As Workbook
      Dim c As Range, FR As Variant
      Dim d As Range
      Dim e As Range, rng1 As Range, rng2 As Range
      Dim lr1 As Long, lr2 As Long

      Application.ScreenUpdating = False

      Set w2 = Workbooks("Book2.xlsx").ActiveSheet
      Set w1 = Workbooks("Book1.xlsx").ActiveSheet

     w1.Range("B:D").Copy
     Set wbnew = Workbooks.Add 'creates new workbook
     Columns("A:A").Select
     ActiveSheet.Paste
     Application.CutCopyMode = False
     ActiveSheet.Name = w1.Name
     Set wsnew = wbnew.ActiveSheet 'sets the active sheet in the new workbook
     lr1 = wsnew.Cells(Rows.count, 1).End(xlUp).Row
     lr2 = w2.Cells(Rows.count, 1).End(xlUp).Row

     wsnew.Sort.SortFields.Add2 Key:=Range("B1"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With wsnew.Sort
        .SetRange Range("A1:C" & lr1)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
   End With

Columns("B:B").Insert Shift:=xlToRight, _
      CopyOrigin:=xlFormatFromLeftOrAbove

      Range("B1").Select
      ActiveCell.FormulaR1C1 = "Device Name"

      Dim lr3 As Long

      lr3 = wsnew.Cells(Rows.count, 1).End(xlUp).Row

      Set rng1 = wsnew.Range("C2:D" & lr3)
      Set rng2 = w2.Range("C2:D" & lr2)

'create a loop to find matches between columns C and D in the new workbook
'and match with columns C and D in workbook 2, upon a match retrieve the information
'in column B in workbook2 and add it to Columns B in the new workbook

For Each d In rng1
    FR = Application.Match(d, rng2)
    If IsNumeric(FR) Then
    d.Offset(, -1).Value = w2.Range("B" & FR).Value
    End If

Next d

Application.ScreenUpdating = True

End Sub


来源: stackexchange

问:
ISBX/apprtc-ios does not work on iOS 13 - no video not working
I am using apprtc-ios from https://github.com/ISBX/apprtc-ios for our video calling project. It is working fine on iOS 12 & iOS 11.

After upgrading to my device to iOS 13, it seems the front camera does not record video and send it to the other party - If phone A & phone B are having a video calling session, the little video preview square on phone A (iOS 13) turns black. On phone B (iOS 12), there is no video sent by phone A - The whole screen is black, except for the little preview square. The audio conversation is working fine, though.

I checked camera permission - it is on for the app.

And I traced the code. cameraID for the front camera (on iOS 13 phone) is successfully obtained during the video call session.

After several hours of trial and error, I still got no clue. Does anyone know how to fix it?

答:
HeIIO

I suggest you to use stasel instead (https://github.com/stasel/WebRTC-iOS)

I managed to send and receive thanks to this, by the way I had to use RTCEAGLVideoView instead of MTL and VP8 instead of H264 to be able to see the video from simulator (ios 13)

:)

ContentLicense: CC BY-SA 4.0


问:
Says it cannot be used as constant
Visual studio 2019

```<code>const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];
</code>```

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

答:
The how variable is indeed const, but is not a constant expression. Such constant expressions are values and functions that have a known value and result at compile time, something known by the compiler before the program runs.

You can annotate your code to tell the compiler which variable should have a known value at compile time. This is what the constexpr keyword is for.

However, the pow function is not marked as constexpr so it's only useable at runtime and not also at compile time. You must implement your own function there:

```<code>constexpr auto power(int value, int exponent) -> int {
    for (int i = 0 ; i < exponent ; i++) {
        value *= value;
    }

    return value;
}

constexpr int inputs = 1, layers = 2, layerN = 3, output = 1;
constexpr int how = inputs * layerN + power(layerN,layers) + output * layerN;
</code>```

Then it will be useable in a array size:

```<code>float w[how];
</code>```

Live example

Also note that with this power function we created, we can revert back to const and the compiler will still accept it:

```<code>const int how = inputs * layerN + power(layerN, layers) + output * layerN;
float w[how];
</code>```

The difference is that constexpr enforce compile time knowability, and const does not and you get the error later.

Title: Says it cannot be used as constant

Body:
Visual studio 2019

const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

Body:
The how variable is indeed const, but is not a constant expression. Such constant expressions are values and functions that have a known value and result at compile time, something known by the compiler before the program runs.

You can annotate your code to tell the compiler which variable should have a known value at compile time. This is what the constexpr keyword is for.

However, the pow function is not marked as constexpr so it's only useable at runtime and not also at compile time. You must implement your own function there:

constexpr auto power(int value, int exponent) -> int {
    for (int i = 0 ; i < exponent ; i++) {
        value *= value;
    }

    return value;
}

constexpr int inputs = 1, layers = 2, layerN = 3, output = 1;
constexpr int how = inputs * layerN + power(layerN,layers) + output * layerN;

Then it will be useable in a array size:

float w[how];

Live example

Also note that with this power function we created, we can revert back to const and the compiler will still accept it:

const int how = inputs * layerN + power(layerN, layers) + output * layerN;
float w[how];

The difference is that constexpr enforce compile time knowability, and const does not and you get the error later.


问:
React: async change of global state property
What is the best way for below scenario?

There is a Loader component in App.js which is shown, when a property in global state (redux) property, e.g. loaderOn, is set to true

There are couple of async api calls (in different components throughout the app), every which dispatches an action, which shows a loader (loaderOn: true)

Problem: how to hide Loader after the LAST request is completed?

a) The above scenario is not quite good - true / false flag turns false after first request is completed

b) I was trying with a counter flag - +1 for each requested started and then -1 for each when completed - Loader hides at 0. But requests are async (and so is setting state from different places?), so it doesn't work either (setting counter flag depends on prev state and so parallel state changes give wrong final value)

答:
The easiest solution to resolve your problem is defining separate loading flags for different async actions.

So, in redux's initialState, you can have:

```<code>{
  ...
  usersLoading: false,
  productsLoading: false,
  companiesLoading: false,
}
</code>```

Then, you set it to true/false based on the loaded status of each data.

Finally, you can have a selector that evaluates the logical OR of all loading flags like this:

```<code>state.usersLoading || state.productsLoading || state.companiesLoading
</code>```

And in your App component, connect the value of that selector to your prop, say, loading, and render the Loader component based on that:

```<code>{loading && <Loader />}
</code>```

Body:
The easiest solution to resolve your problem is defining separate loading flags for different async actions.

So, in redux's initialState, you can have:

{
  ...
  usersLoading: false,
  productsLoading: false,
  companiesLoading: false,
}

Then, you set it to true/false based on the loaded status of each data.

Finally, you can have a selector that evaluates the logical OR of all loading flags like this:

state.usersLoading || state.productsLoading || state.companiesLoading

And in your App component, connect the value of that selector to your prop, say, loading, and render the Loader component based on that:

{loading && <Loader />}


问:
Using protobuffers instead of Parcelables in Android intent extras?
Would it be a good idea to use protocol buffer objects (serialized to byte arrays) to pass as intent extras between Android activities instead of implementing Parcelable on classic POJOs? How would it affect performance?

Thanks
Markus

答:
To know for sure you'd have to do a test for your particular case.

Things to keep in mind about Parcel:

As you may know, it's a manual process: you have to walk your object tree and call Parcel's various serialization method, e.g. writeFloatArray(..). There is no magic and it is as low-level as it gets.

Parcel.java is a wrapper around native implementation, so it should be pretty optimized already: http://www.google.com/codesearch/p?hl=en#uX1GffpyOZk/libs/binder/Parcel.cpp&q=Parcel.cpp%20package:android&sa=N&cd=1&ct=rc

Don't use Binder, because it creates a proxy (if cross-process).

Probably most important: size the initial buffers properly with setDataCapacity(int size). This way internal array will not need to be grown (= memory alloc + copy).

If you use Parcel multiple times, then give it back to the pool with recycle().

ContentLicense: CC BY-SA 3.0


问:
How to "preselect" UIActivityViewController Icon?
I would like to redirect the user to an app that could be selected in UIActivityViewController.

For example, the "Message" app is often shown in UIActivityViewController. How could I,in advance, directly redirect the user to this app without showing the UIActivityViewController?

I would be glad to know if someone can help me out.

答:
If you need to open the Messages App, it's simple.

```<code>@IBAction func openMessagesApp(sender: UIButton){
    // Swift 3
    UIApplication.sharedApplication().openURL(NSURL(string: "sms:")!)

    // Swift 4
    UIApplication.shared.open(URL(string: "sms:")!, options: [:], completionHandler: nil)
}
</code>```

Body:
If you need to open the Messages App, it's simple.

@IBAction func openMessagesApp(sender: UIButton){
    // Swift 3
    UIApplication.sharedApplication().openURL(NSURL(string: "sms:")!)

    // Swift 4
    UIApplication.shared.open(URL(string: "sms:")!, options: [:], completionHandler: nil)
}


问:
How to handle a basic form submission with http4s?
I can't believe this isn't in the http4s documentation, and the example code I was able to dig up online (after poking around long enough to discover the UrlForm class) is not working for me.

The relevant bit of code looks like this:

```<code>case req @ POST -> Root / "compose" =>
  req.decode[UrlForm] { ps =>
    println("ps.values: " + ps.values)
    val content = ps.getFirstOrElse("content",
      throw new IllegalStateException("No content given!"))
    // Do something with `content`...
  }
</code>```

When submitting the associated form, the IllegalStateException is thrown. ps.values is an empty map (Map()).

I can see (using println) that the Content-Type is application/x-www-form-urlencoded, as expected, and I can see from my browser's Network tab that request "paramaters" (the encoded form values) are being sent properly.

答:
The problem is that I had a filter (javax.servlet.Filter) in place that was calling getParameterMap on the HttpServletRequest. This was draining the InputStream for the request, and it was happening before the request got passed off to the servlet (BlockingHttp4sServlet) instance.

It seems to me the BlockingHttp4sServlet should raise an IllegalStateException (or something more descriptive) when it receives an InputStream with isFinished returning true. (I've filed an issue with the http4s project on Github.)

Body:
I can't believe this isn't in the http4s documentation, and the example code I was able to dig up online (after poking around long enough to discover the UrlForm class) is not working for me.

The relevant bit of code looks like this:

case req @ POST -> Root / "compose" =>
  req.decode[UrlForm] { ps =>
    println("ps.values: " + ps.values)
    val content = ps.getFirstOrElse("content",
      throw new IllegalStateException("No content given!"))
    // Do something with `content`...
  }

When submitting the associated form, the IllegalStateException is thrown. ps.values is an empty map (Map()).

I can see (using println) that the Content-Type is application/x-www-form-urlencoded, as expected, and I can see from my browser's Network tab that request "paramaters" (the encoded form values) are being sent properly.


问:
Vue CLI ESLint injects additional whitespace into multi-line spans
I'm outputting a list with a project set up using the VUE CLI and all the defaults it provides and working in VSCode.

I've got a list I want to put at the end of a string. If I write the code like:

({{fruit}}, )

then it shows up like (orange, banana, strawberry) which is exactly what I want.

But when I apply the ESLint formatter, it wants to turn the code into this:

```<code><span v-if="fruits">
  (
  <span v-for="(fruit,index) in fruits" :key="index">
    {{fruit}}
    <span v-if="index != (fruits.length - 1)">, </span>
  </span>)
</span>
</code>```

This is far more readable and I like it, except that the result turns it into ( orange , banana , strawberry ) which is very much not what I want.

How do I remove those extra spaces being inserted while not disabling ESLint and keeping the formatting it applies?

I'm relatively new to web development and I'm pretty sure this is a duplicate, but all the other answers I've found on this topic are to apply CSS rules that change the margin on the text, and I just want to delete the extra space.

I initially switched to the javascript .join method, but realized I will need to wrap each fruit with it's own span to apply a css class.

答:
You can switch to the Prettier formatter which will preserve your whitespace but create this mess:

  ({{ fruit }}, )
```

<p>Or you can escape the format rules by ignoring the single-line loop:</p>

<pre class="lang-html prettyprint-override"><code><!-- eslint-ignore-next-line -->
<span v-if="fruits">(<span v-for="(fruit,index) in fruits" :key="index">{{fruit}}<span v-if="index != (fruits.length - 1)">, </span></span>)</span>
</code>```

Body:
I'm outputting a list with a project set up using the VUE CLI and all the defaults it provides and working in VSCode.

I've got a list I want to put at the end of a string. If I write the code like:

({{fruit}}, )

then it shows up like (orange, banana, strawberry) which is exactly what I want.

But when I apply the ESLint formatter, it wants to turn the code into this:

  (

    {{fruit}}
    ,
  )

This is far more readable and I like it, except that the result turns it into ( orange , banana , strawberry ) which is very much not what I want.

How do I remove those extra spaces being inserted while not disabling ESLint and keeping the formatting it applies?

I'm relatively new to web development and I'm pretty sure this is a duplicate, but all the other answers I've found on this topic are to apply CSS rules that change the margin on the text, and I just want to delete the extra space.

I initially switched to the javascript .join method, but realized I will need to wrap each fruit with it's own span to apply a css class.

Body:
You can switch to the Prettier formatter which will preserve your whitespace but create this mess:

  <span v-if="fruit"
    >(<span v-for="(fruit, index) in fruit" :key="index"
      >{{ fruit }}<span v-if="index != fruit.length - 1">, </span></span
    >)</span
  >

Or you can escape the format rules by ignoring the single-line loop:

<!-- eslint-ignore-next-line -->
<span v-if="fruits">(<span v-for="(fruit,index) in fruits" :key="index">{{fruit}}<span v-if="index != (fruits.length - 1)">, </span></span>)</span>


问:
Pyshark - Determine protocol from IPV6
I am trying to obtain the protocol number from an IPV6 packet. Which one fo these fields do I have to use in order to achieve this.</p>

```<code>print(cap[36].ipv6.field_names)

['version', 'ip_version', 'tclass', 'tclass_dscp', 'tclass_ecn', 'flow', 'plen', 'nxt', 'hlim', 'src', 'addr', 'src_host', 'host', 'dst', 'dst_host']
</code>```

答:
I'm unsure if this is the correct answer for your question.  If it isn't please let me know and I will rework my answer.

```<code>capture = pyshark.FileCapture(pcap_file)
for packet in capture:
    if hasattr(packet, 'ipv6') and hasattr(packet, 'tcp'):

       source_address = packet.ipv6.src
       source_port = packet[packet.transport_layer].srcport
       print(f'TCP packet -- Source Address: {source_address} -- Source Port: {source_port}')

       destination_address = packet.ipv6.dst
       destination_port = packet[packet.transport_layer].dstport
       print(f'TCP packet -- Destination Address: {destination_address } -- Destination Port: {destination_port }')

    elif hasattr(packet, 'ipv6') and hasattr(packet, 'udp'):

       source_address = packet.ipv6.src
       source_port = packet[packet.transport_layer].srcport
       print(f'UDP packet -- Source Address: {source_address} -- Source Port: {source_port}')

       destination_address = packet.ipv6.dst
       destination_port = packet[packet.transport_layer].dstport
       print(f'UDP packet -- Destination Address: {destination_address} -- Destination Port: {destination_port}')
</code>```

UPDATE:

I apologize for the delay in my response. Here is an updated answer, which hopefully solves the issue raised by Ron Maupin.

```<code>capture = pyshark.FileCapture(pcap_file)
for packet in capture:
    if "IPV6" in str(packet.layers):
       next_header_info = regex.findall(r'(Next Header:)\s(\w.+)\s(\W\d{0,3}\W)', str(packet.layers[1]))
       print(next_header_info)
       # Output
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'IPv6 Hop-by-Hop Option', '(0)'), ('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'UDP', '(17)')]
       ...truncated

</code>```

Title: Pyshark - Determine protocol from IPV6

Body:
I am trying to obtain the protocol number from an IPV6 packet. Which one fo these fields do I have to use in order to achieve this.

print(cap[36].ipv6.field_names)

['version', 'ip_version', 'tclass', 'tclass_dscp', 'tclass_ecn', 'flow', 'plen', 'nxt', 'hlim', 'src', 'addr', 'src_host', 'host', 'dst', 'dst_host']

Body:
I'm unsure if this is the correct answer for your question.  If it isn't please let me know and I will rework my answer.

capture = pyshark.FileCapture(pcap_file)
for packet in capture:
    if hasattr(packet, 'ipv6') and hasattr(packet, 'tcp'):

       source_address = packet.ipv6.src
       source_port = packet[packet.transport_layer].srcport
       print(f'TCP packet -- Source Address: {source_address} -- Source Port: {source_port}')

       destination_address = packet.ipv6.dst
       destination_port = packet[packet.transport_layer].dstport
       print(f'TCP packet -- Destination Address: {destination_address } -- Destination Port: {destination_port }')

    elif hasattr(packet, 'ipv6') and hasattr(packet, 'udp'):

       source_address = packet.ipv6.src
       source_port = packet[packet.transport_layer].srcport
       print(f'UDP packet -- Source Address: {source_address} -- Source Port: {source_port}')

       destination_address = packet.ipv6.dst
       destination_port = packet[packet.transport_layer].dstport
       print(f'UDP packet -- Destination Address: {destination_address} -- Destination Port: {destination_port}')

UPDATE:

I apologize for the delay in my response. Here is an updated answer, which hopefully solves the issue raised by Ron Maupin.

capture = pyshark.FileCapture(pcap_file)
for packet in capture:
    if "IPV6" in str(packet.layers):
       next_header_info = regex.findall(r'(Next Header:)\s(\w.+)\s(\W\d{0,3}\W)', str(packet.layers[1]))
       print(next_header_info)
       # Output
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'IPv6 Hop-by-Hop Option', '(0)'), ('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'ICMPv6', '(58)')]
       [('Next Header:', 'UDP', '(17)')]
       ...truncated


问:
DELPHI - Extra semi-colons in except blocks, any purpose? Optional semi-colon before except or end, What's better with or without?
Working in a Delphi 10.3.3 application with a ton of extra & missing semi-colons. The app compiles if they are dropped prior to any block ending statement.

Does a floating semi-colon between [except] and [end] serve any purpose in the code, such as faster run time or throw some default exception, or some other purpose?

Could this throw a random compile or runtime error?

Does leaving a semi-colon off the last line before an end or except speed up runtime?

Is one way, more error-prone than another or subject to random compile or runtime errors?

Here is code that can be dropped into any test project with a form having an edit box, a button and a memo box created with drag-n-drop default settings.

```<code>function TForm1.isThisUseful(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except
    ;
  end;
  result := (i > 0)
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if isThisUseful(Edit1.Text)
  then
    Memo1.Text := 'Yes, it is useful'
  else
    Memo1.Text := 'This is a waste of time.'
end;
</code>```

答:
tl;dr: No difference whatsoever.

```<code>try
  // do stuff
except
  ;
end;
</code>```

This semicolon can be removed. It has absolutely no effect whatsoever. It does no good, and it does no harm (except, possibly, it makes the source code look strange, which you should avoid1).

```<code>begin
  DoThis;
  DoThat;
end;
</code>```

Since in Delphi, semicolons separate statements, the final semicolon before end is not necessary. It has absolutely no effect whatsoever. It is mainly a matter of taste if you want it or not (and personally, I sometimes have it and sometimes not).

One benefit of having this semicolon might be that you then can move or copy this line, without modification, to a different place where it isn't the final statement in its block. Similarly, you can also insert a new statement immediately after this line of code without needing to add the semicolon. IMHO, these are very minor benefits; it's not hard to add the semicolon if and when it becomes necessary.

Bonus comment: However, result := (i > 0) does look strange to me. I'd expect Result := i > 0, without the unnecessary parentheses. (This might be because I have programmed in Delphi almost daily for more than 20 years.)

Bonus comment 2: Notice that the compiler happily accepts

```<code>begin
  DoThis;;
  DoThat;
end;
</code>```

as well. It simply ignores redundant semicolons. But the snippet above looks very ugly to me, and I always find it strange that developers choose to commit code without reading it first.

Bonus comment 3: Ken Bourassa wrote an answer giving an example of a scenario in which the presence or absense of a semicolon does affect the program. But there is an even scarier example:

```<code>case i of
  0:
    DoA;
  1:
    DoB;
  2:
    if j = 0 then
      DoC{;}
else
  DoD;
end;
</code>```

1 In this case, you could also argue that the semicolon serves a purpose: it "highlights" the empty except block, making it slightly easier to spot quickly. Hence, it might be intentional. But one might argue that a better way to highlight it would be to include a comment like // Do nothing or // Just carry on. (And, in many, if not most, cases, empty except blocks are not good at all.)

Body:
Working in a Delphi 10.3.3 application with a ton of extra & missing semi-colons. The app compiles if they are dropped prior to any block ending statement.

Does a floating semi-colon between [except] and [end] serve any purpose in the code, such as faster run time or throw some default exception, or some other purpose?

Could this throw a random compile or runtime error?

Does leaving a semi-colon off the last line before an end or except speed up runtime?

Is one way, more error-prone than another or subject to random compile or runtime errors?

Here is code that can be dropped into any test project with a form having an edit box, a button and a memo box created with drag-n-drop default settings.

function TForm1.isThisUseful(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except
    ;
  end;
  result := (i > 0)
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if isThisUseful(Edit1.Text)
  then
    Memo1.Text := 'Yes, it is useful'
  else
    Memo1.Text := 'This is a waste of time.'
end;

Body:
tl;dr: No difference whatsoever.

try
  // do stuff
except
  ;
end;

This semicolon can be removed. It has absolutely no effect whatsoever. It does no good, and it does no harm (except, possibly, it makes the source code look strange, which you should avoid1).

begin
  DoThis;
  DoThat;
end;

Since in Delphi, semicolons separate statements, the final semicolon before end is not necessary. It has absolutely no effect whatsoever. It is mainly a matter of taste if you want it or not (and personally, I sometimes have it and sometimes not).

One benefit of having this semicolon might be that you then can move or copy this line, without modification, to a different place where it isn't the final statement in its block. Similarly, you can also insert a new statement immediately after this line of code without needing to add the semicolon. IMHO, these are very minor benefits; it's not hard to add the semicolon if and when it becomes necessary.

Bonus comment: However, result := (i > 0) does look strange to me. I'd expect Result := i > 0, without the unnecessary parentheses. (This might be because I have programmed in Delphi almost daily for more than 20 years.)

Bonus comment 2: Notice that the compiler happily accepts

begin
  DoThis;;
  DoThat;
end;

as well. It simply ignores redundant semicolons. But the snippet above looks very ugly to me, and I always find it strange that developers choose to commit code without reading it first.

Bonus comment 3: Ken Bourassa wrote an answer giving an example of a scenario in which the presence or absense of a semicolon does affect the program. But there is an even scarier example:

case i of
  0:
    DoA;
  1:
    DoB;
  2:
    if j = 0 then
      DoC{;}
else
  DoD;
end;

1 In this case, you could also argue that the semicolon serves a purpose: it "highlights" the empty except block, making it slightly easier to spot quickly. Hence, it might be intentional. But one might argue that a better way to highlight it would be to include a comment like // Do nothing or // Just carry on. (And, in many, if not most, cases, empty except blocks are not good at all.)


问:
How can I implement a boolean tag search in SQL?
Given a table of items, a table of tags and a join table between them, what is a good and efficient way to implement queries of the form:

p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk

I am using SQL. So to find all items that match all tags p1...pn and none of n1...nk?

Is there a good "standard" solution for this?

答:
```<code>SELECT DISTINCT itemID FROM ItemsTags it, Tags t
WHERE it.tagID = t.ID AND t.tag IN ('p1','p2','p3') AND t.tag NOT IN ('p4','p5','p6')
</code>```

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B


问:
Time since in php dateTime object in seconds

Possible Duplicate:

  Date to timestamp (PHP)?

How do I get the current time in seconds since 1st january 1970 in php?

does the dateTime object support anything since as

```<code>$date1 = new DateTime("01/01/1970");
$return = since($date1, date.now());
</code>```

The problem I get here is I could just do something like ((minutes=hours *60)*60)

Is there a nicer way?

答: $_SERVER['REQUEST_TIME']; is a pretty light way to do it, if your server supports it. Otherwise you have the usual time() / strtotime() functions. Also, why is there javascript in your PHP?

Body:
Possible Duplicate:

  Date to timestamp (PHP)?

How do I get the current time in seconds since 1st january 1970 in php?

does the dateTime object support anything since as

$date1 = new DateTime("01/01/1970");
$return = since($date1, date.now());

The problem I get here is I could just do something like ((minutes=hours *60)*60)

Is there a nicer way?


问:
ReferenceError: Item Is Not Defined In NodeJs Route
I define my API routes in Nodejs but when I run it, it gives this error message.

Error Message

ReferenceError: Item is not defined

```<code>at D:\shoppinglist\serverside\route\routes.js:7:5
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at Function.handle (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:174:3)
at router (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:317:13)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\shoppinglist\serverside\node_modules\body-parser\lib\types\json.js:110:7)
</code>```

My Route.js code is

```<code>var express = require('express');

var router = express.Router();

router.get('/items', (req, res, next)=>{
    Item.find(function(err, items){
        if(err){
            res.json(err);
        }
        else{
            res.json(items);
        }
    });
});
router.post('/item', (req, res, next)=>{
    let newShoppingItem = new Item({
        itemName: req.body.itemName,
        itemQuantity: req.body.itemQuantity,
        itemBought: req.body.itemBought
    });
    newShoppingItem.save((err, item)=>{
        if(err){
            res.json(err)
        }
        else{
            res.json({msg: 'Item has been added to db'});
        }
    });
});
router.put('/put_test', (req, res, next)=>{
  // do later
});

router.delete('/delete_test', (req, res, next)=>{
  // do later
});

module.exports = router;
</code>```

Here is my shoopingitem.js code

shoppingitem.js

```<code>const mongoose = require('mongoose');

const shoppingItemSchema = mongoose.Schema({

    itemName:{
        type: String,
        require:true
    },

    itemQuantity:{
        type: Number,
        require:true
    },

    itemBought:{
        type: Boolean,
        require:true
    },

});
const Item = module.exports = mongoose.model('Item', shoppingItemSchema);
</code>```

Please suggest me the solution. I'm new in nodejs. So please help

Thanks in advance

答:
As mentioned by Matthew Weeks, be sure to import the mongoose Item model into your Route.js file.

Also if you're trying to query all items from a collection, be sure to include an empty query object as the first parameter in the find function. Including Matthew Weeks solution, the first part of Route.js should look something like:

```<code>const Item = require('../path/to/item/shoppingItem.js');
var express = require('express');
var router = express.Router();

router.get('/items', (req, res, next)=>{
Item.find({}, function(err, items){
    if(err){
        res.json(err);
    }
    else{
        res.json(items);
    }
});
</code>```

Body:
I define my API routes in Nodejs but when I run it, it gives this error message.

Error Message

ReferenceError: Item is not defined

at D:\shoppinglist\serverside\route\routes.js:7:5
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at Function.handle (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:174:3)
at router (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:317:13)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\shoppinglist\serverside\node_modules\body-parser\lib\types\json.js:110:7)

My Route.js code is

var express = require('express');

var router = express.Router();

router.get('/items', (req, res, next)=>{
    Item.find(function(err, items){
        if(err){
            res.json(err);
        }
        else{
            res.json(items);
        }
    });
});
router.post('/item', (req, res, next)=>{
    let newShoppingItem = new Item({
        itemName: req.body.itemName,
        itemQuantity: req.body.itemQuantity,
        itemBought: req.body.itemBought
    });
    newShoppingItem.save((err, item)=>{
        if(err){
            res.json(err)
        }
        else{
            res.json({msg: 'Item has been added to db'});
        }
    });
});
router.put('/put_test', (req, res, next)=>{
  // do later
});

router.delete('/delete_test', (req, res, next)=>{
  // do later
});

module.exports = router;

Here is my shoopingitem.js code

shoppingitem.js

const mongoose = require('mongoose');

const shoppingItemSchema = mongoose.Schema({

    itemName:{
        type: String,
        require:true
    },

    itemQuantity:{
        type: Number,
        require:true
    },

    itemBought:{
        type: Boolean,
        require:true
    },

});
const Item = module.exports = mongoose.model('Item', shoppingItemSchema);

Please suggest me the solution. I'm new in nodejs. So please help

Thanks in advance

Body:
As mentioned by Matthew Weeks, be sure to import the mongoose Item model into your Route.js file.

Also if you're trying to query all items from a collection, be sure to include an empty query object as the first parameter in the find function. Including Matthew Weeks solution, the first part of Route.js should look something like:

const Item = require('../path/to/item/shoppingItem.js');
var express = require('express');
var router = express.Router();

router.get('/items', (req, res, next)=>{
Item.find({}, function(err, items){
    if(err){
        res.json(err);
    }
    else{
        res.json(items);
    }
});


问:
Why I can't refer to a key in an object's another key?
Why I cant refer to a key in an object that is already placed in another object's key while mapping like this:

```<code>var object = {
  "allStudents": [
    {
      "name": "John",
      "hobbies": {
        "sport": "Football",
        "music": "Piano"
      } ,
    },
    {
      "name": "Julyo",
      "hobbies": {
        "sport": "Vollyball",
        "music": "Guitar"
      } ,
    },
  ],
};

class Student {
  String name;
  dynamic hobbies;
  Student({this.name, this.hobbies});
}

class Hobbies {
  String sport;
  String music;
  Hobbies({this.sport, this.music});
}

List<Student> studentsList = [];

void getStudentsList () {
  studentsList = object["allStudents"].map((stu)=>
  Student(
    name: stu["name"] ,
    hobbies: Hobbies(
      sport: stu['hobbies']['sport'] ,
        music:stu['hobbies']['music'],
    ) ,
  )
  ).toList();
}

</code>```

everything is working very well until I add the second operator ['sport'] or ['music']  as the IDE keeps telling me:

The operator '[]' is not defined for the class 'Object'.
  Try defining the operator '[]'.

see screenshot:
can't refer to a key's value in another object's key

答:
That's because your var object is of type Map<String,Object>, and when you access the using first [], you have Object as a return, soon Object is not a map or iterable, the second [] canot be aplied. You have to explicit tells that your object is of type Map<String, dynamic>, like example below:

```<code>Map<String, dynamic> object = {
  "allStudents": [
    {
      "name": "John",
      "hobbies": {"sport": "Football", "music": "Piano"},
    },
    {
      "name": "Julyo",
      "hobbies": {"sport": "Vollyball", "music": "Guitar"},
    },
  ],
};
</code>```

and change your parse code to explicit map to work with second []:

```<code>void getStudentsList() {
    final test = (object["allStudents"] as List)
        .map<Student>(
          (stu) => Student(
            name: stu["name"],
            hobbies: Hobbies(
              sport: stu['hobbies']['sport'],
              music: stu['hobbies']['music'],
            ),
          ),
        )
        .toList();

    print(test);
  }
</code>```

Now it works!

Note: Dynamic can be every possible value type, diferent of Object type, for more info, see the discussion What is the difference between dynamic and Object in dart?

Body:
Why I cant refer to a key in an object that is already placed in another object's key while mapping like this:

var object = {
  "allStudents": [
    {
      "name": "John",
      "hobbies": {
        "sport": "Football",
        "music": "Piano"
      } ,
    },
    {
      "name": "Julyo",
      "hobbies": {
        "sport": "Vollyball",
        "music": "Guitar"
      } ,
    },
  ],
};

class Student {
  String name;
  dynamic hobbies;
  Student({this.name, this.hobbies});
}

class Hobbies {
  String sport;
  String music;
  Hobbies({this.sport, this.music});
}

List<Student> studentsList = [];

void getStudentsList () {
  studentsList = object["allStudents"].map((stu)=>
  Student(
    name: stu["name"] ,
    hobbies: Hobbies(
      sport: stu['hobbies']['sport'] ,
        music:stu['hobbies']['music'],
    ) ,
  )
  ).toList();
}

everything is working very well until I add the second operator ['sport'] or ['music']  as the IDE keeps telling me:

The operator '[]' is not defined for the class 'Object'.
  Try defining the operator '[]'.

see screenshot:
can't refer to a key's value in another object's key

Body:
That's because your var object is of type Map<String,Object>, and when you access the using first [], you have Object as a return, soon Object is not a map or iterable, the second [] canot be aplied. You have to explicit tells that your object is of type Map<String, dynamic>, like example below:

Map<String, dynamic> object = {
  "allStudents": [
    {
      "name": "John",
      "hobbies": {"sport": "Football", "music": "Piano"},
    },
    {
      "name": "Julyo",
      "hobbies": {"sport": "Vollyball", "music": "Guitar"},
    },
  ],
};

and change your parse code to explicit map to work with second []:

void getStudentsList() {
    final test = (object["allStudents"] as List)
        .map<Student>(
          (stu) => Student(
            name: stu["name"],
            hobbies: Hobbies(
              sport: stu['hobbies']['sport'],
              music: stu['hobbies']['music'],
            ),
          ),
        )
        .toList();

    print(test);
  }

Now it works!

Note: Dynamic can be every possible value type, diferent of Object type, for more info, see the discussion What is the difference between dynamic and Object in dart?


问:
cmake does not find openssl library on mac os x (despite manually adding )
I'm trying to compile https://github.com/dmikushin/binance-cxx-api on osx 10.13.6
(since code is written for linux i had to adjust things a little)

I get following errors (which are openssl related as far as i see):

```<code>Undefined symbols for architecture x86_64:
  "_EVP_sha256", referenced from:
      binance::hmac_sha256(char const*, char const*) in binance_utils.cpp.o
  "_HMAC", referenced from:
      binance::hmac_sha256(char const*, char const*) in binance_utils.cpp.o
  "_SHA256_Final", referenced from:
      binance::sha256(char const*) in binance_utils.cpp.o
  "_SHA256_Init", referenced from:
      binance::sha256(char const*) in binance_utils.cpp.o
  "_SHA256_Update", referenced from:
      binance::sha256(char const*) in binance_utils.cpp.o
ld: symbol(s) not found for architecture x86_64
</code>```

The project is cmake based and does not find or link against openssl (installed with homebrew)

I added include and lib dirs directly in the cmake GUI -> compiler, linker flag
(took the include dir, still gave me the errors)

Also applied several combinations of below and alike => didn't make the error go away

```<code>cmake -DOPENSSL_INCLUDE_DIR=/usr/local/Cellar/openssl/1.0.2d_1/include  -DOPENSSL_CRYPTO_LIBRARY=/usr/local/Cellar/openssl/1.0.2d_1/lib/libcrypto.dylib -DOPENSSL_SSL_LIBRARY=/usr/local/Cellar/openssl/1.0.2d_1/lib/libssl.dylib
</code>```

googling did not bring up new ideas (most of these errors seem to be fixed by the cmake -DOPENSSL.. option)

Does anyone have an idea?

答:
Did you consider editing the cmake project ?

Adding the following lines in the CMakeLists.txt:

```<code>FIND_PACKAGE(OpenSSL)
if(${OpenSSL_FOUND})
  INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
endif()
</code>```

And editing the following line to link to OpenSSL

```<code>target_link_libraries(${PROJECT_NAME} jsoncpp curl websockets ssl crypto)
</code>```

Body:
I'm trying to compile https://github.com/dmikushin/binance-cxx-api on osx 10.13.6
(since code is written for linux i had to adjust things a little)

I get following errors (which are openssl related as far as i see):

Undefined symbols for architecture x86_64:
  "_EVP_sha256", referenced from:
      binance::hmac_sha256(char const*, char const*) in binance_utils.cpp.o
  "_HMAC", referenced from:
      binance::hmac_sha256(char const*, char const*) in binance_utils.cpp.o
  "_SHA256_Final", referenced from:
      binance::sha256(char const*) in binance_utils.cpp.o
  "_SHA256_Init", referenced from:
      binance::sha256(char const*) in binance_utils.cpp.o
  "_SHA256_Update", referenced from:
      binance::sha256(char const*) in binance_utils.cpp.o
ld: symbol(s) not found for architecture x86_64

The project is cmake based and does not find or link against openssl (installed with homebrew)

I added include and lib dirs directly in the cmake GUI -> compiler, linker flag
(took the include dir, still gave me the errors)

Also applied several combinations of below and alike => didn't make the error go away

cmake -DOPENSSL_INCLUDE_DIR=/usr/local/Cellar/openssl/1.0.2d_1/include  -DOPENSSL_CRYPTO_LIBRARY=/usr/local/Cellar/openssl/1.0.2d_1/lib/libcrypto.dylib -DOPENSSL_SSL_LIBRARY=/usr/local/Cellar/openssl/1.0.2d_1/lib/libssl.dylib

googling did not bring up new ideas (most of these errors seem to be fixed by the cmake -DOPENSSL.. option)

Does anyone have an idea?

Body:
Did you consider editing the cmake project ?

Adding the following lines in the CMakeLists.txt:

FIND_PACKAGE(OpenSSL)
if(${OpenSSL_FOUND})
  INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
endif()

And editing the following line to link to OpenSSL

target_link_libraries(${PROJECT_NAME} jsoncpp curl websockets ssl crypto)


问:
SOLVED - Select2 attr "selected" stop working when set false
The goal is to select users according to the option chosen in the first select.
It works fine the first time you select that type of user. But when I change the user type and go back to the previous one, it doesn't show the options in the select. But through the inspect element it appears that the option has the "selected" attribute

```<code><label for="UserType" class="col-md-2 control-label">User Type nbsp;<span class="text-danger small">*</span></label> <div class="col-md-4">
<select class="select2_demo_1 form-control" id="UserType" name="UserType">
    <option value='0' selected disabled hidden>-- Selecionar --</option>
    <option value="1">Boss</option>
    <option value="2">Admin</option>
    <option value="3">User</option>
</select>
</code>```

```<code><label for="Users" class="col-md-2 control-label">Users <span class="text-danger small">*</span></label><div class="col-md-10">
<select id="Users" name="Users" class="select2_demo_1 form-control" multiple  style="width:100%">
    <option data-type='1' value="1" >User Boss</option>
    <option data-type='2' value="2" >User Admin</option>
    <option data-type='2' value="3" >User Admin 2</option>
    <option data-type='3' value="4" >User</option>
</select>
</code>```

```<code>$('#UserType').on('change', function() {
    var UserType = $(this).val();
    $("select#Users option:selected").attr("selected",false);
    $("select#Users option[data-type="+ UserType +"]").attr("selected","selected");
    $("#Users").select2();
});
$('#UserType').trigger('change');
</code>```

------ Solution ------

Change the code segment

```<code>$("select#Users option:selected").attr("selected",false);
    $("select#Users option[data-type="+ UserType +"]").attr("selected","selected");
    $("#Users").select2();
</code>```

by the following

```<code>$('#UserType').select2('destroy').find('option').prop('selected', false).end().select2();
$('#UserType').select2('destroy').find('option[data-type='+ UserType+']').prop('selected', 'selected').end().select2();
</code>```

答: You may think to add selected="true" and then change it to false when you apply the function attr()

Body:
The goal is to select users according to the option chosen in the first select.
It works fine the first time you select that type of user. But when I change the user type and go back to the previous one, it doesn't show the options in the select. But through the inspect element it appears that the option has the "selected" attribute

User Type nbsp;*

<select class="select2_demo_1 form-control" id="UserType" name="UserType">
    <option value='0' selected disabled hidden>-- Selecionar --</option>
    <option value="1">Boss</option>
    <option value="2">Admin</option>
    <option value="3">User</option>
</select>

Users *

<select id="Users" name="Users" class="select2_demo_1 form-control" multiple  style="width:100%">
    <option data-type='1' value="1" >User Boss</option>
    <option data-type='2' value="2" >User Admin</option>
    <option data-type='2' value="3" >User Admin 2</option>
    <option data-type='3' value="4" >User</option>
</select>

$('#UserType').on('change', function() {
    var UserType = $(this).val();
    $("select#Users option:selected").attr("selected",false);
    $("select#Users option[data-type="+ UserType +"]").attr("selected","selected");
    $("#Users").select2();
});
$('#UserType').trigger('change');

------ Solution ------

Change the code segment

$("select#Users option:selected").attr("selected",false);
    $("select#Users option[data-type="+ UserType +"]").attr("selected","selected");
    $("#Users").select2();

by the following

$('#UserType').select2('destroy').find('option').prop('selected', false).end().select2();
$('#UserType').select2('destroy').find('option[data-type='+ UserType+']').prop('selected', 'selected').end().select2();


问:
Pygame's window opens than closes immediately, why?
When i run this on Pycharm it opens than closes immediately. Whereas in the video tutorial it just stays open, why?

```<code>import pygame

pygame.init()

win = pygame.display.set_mode((500, 500))

pygame.display.set_caption("hello")
</code>```

i am using windows os, python version 3.7.2, and pygame 1.9.4

答:
I had the same problem as you (and I was following the same tutorial) and i found that if you enclose the whole thing in a while loop (excluding import pygame, pygame.init() and the variable you use for the while loop) it works quite well.

import pygame

pygame.init()

Game = True

while Game is True:
    window1 = pygame.display.set_mode((500, 500))
    pygame.display.set_caption("First Game")
```

I have just started learning Python so this might not be the best way to do it but I hope it helps in some way :)

Body:
When i run this on Pycharm it opens than closes immediately. Whereas in the video tutorial it just stays open, why?

import pygame

pygame.init()

win = pygame.display.set_mode((500, 500))

pygame.display.set_caption("hello")

i am using windows os, python version 3.7.2, and pygame 1.9.4

Body:
I had the same problem as you (and I was following the same tutorial) and i found that if you enclose the whole thing in a while loop (excluding import pygame, pygame.init() and the variable you use for the while loop) it works quite well.

import pygame

pygame.init()

Game = True

while Game is True:
    window1 = pygame.display.set_mode((500, 500))
    pygame.display.set_caption("First Game")

I have just started learning Python so this might not be the best way to do it but I hope it helps in some way :)


问:
flutter - android back button does not call onWillPop of WillPopScope
I would like to exit my application. I have implemented a WillPopScope, but it looks like the onWillPop function is not being called at all. I tried many things like swap WillPopScope with Scaffold, changing the return value of the function, but it just looks like it is not working as expected.

My code:

```<code>Future<bool> _willPopCallback() async {
  exit(0);
  // await showDialog or Show add banners or whatever
  // then
  return true; // return true if the route to be popped
}

return Scaffold(
    appBar: MyAppBar(
      leading: DrawerAction(),
      title: Text(AppLocalizations.of(context).textCapitalized('home_page')),
      onSearch: (searchTerms) => this.search(searchTerms, context),
    ),
    body: new WillPopScope(
      onWillPop: _willPopCallback, // Empty Function.
      child: //my screen widgets
</code>```

I am not sure if this is a bug I should report to flutter or I am doing something wrong. Happy to provide more code on request.

I have tried:

```<code>exit(0);
Navigator.of(context).pop();
SystemChannels.platform.invokeMethod('SystemNavigator.pop');
</code>```

Thanks in advance!

答:
First of all do not ever use exit(0). It may be fine in Android environment, but apple won't allow the app on app store if it programmatically shuts down itself.

Here in the docs of onWillPop it clearly mentions that function should resolves to a boolean value.

```<code>Future<bool> _willPopCallback() async {
   // await showDialog or Show add banners or whatever
   // then
   return Future.value(true);
}
</code>```

This only works if your current page is the root of navigation stack.

Body:
I would like to exit my application. I have implemented a WillPopScope, but it looks like the onWillPop function is not being called at all. I tried many things like swap WillPopScope with Scaffold, changing the return value of the function, but it just looks like it is not working as expected.

My code:

Future<bool> _willPopCallback() async {
  exit(0);
  // await showDialog or Show add banners or whatever
  // then
  return true; // return true if the route to be popped
}

return Scaffold(
    appBar: MyAppBar(
      leading: DrawerAction(),
      title: Text(AppLocalizations.of(context).textCapitalized('home_page')),
      onSearch: (searchTerms) => this.search(searchTerms, context),
    ),
    body: new WillPopScope(
      onWillPop: _willPopCallback, // Empty Function.
      child: //my screen widgets

I am not sure if this is a bug I should report to flutter or I am doing something wrong. Happy to provide more code on request.

I have tried:

exit(0);
Navigator.of(context).pop();
SystemChannels.platform.invokeMethod('SystemNavigator.pop');

Thanks in advance!

Body:
First of all do not ever use exit(0). It may be fine in Android environment, but apple won't allow the app on app store if it programmatically shuts down itself.

Here in the docs of onWillPop it clearly mentions that function should resolves to a boolean value.

Future<bool> _willPopCallback() async {
   // await showDialog or Show add banners or whatever
   // then
   return Future.value(true);
}

This only works if your current page is the root of navigation stack.


答:
Dart is not aware of what your structure is like, therefore, you have to make it aware by providing a cast.

```<code>void getStudentsList () {
  studentsList = (object["allStudents"] as List<Map<String,dynamic>>)
      .map((stu)=>
  Student(
    name: stu["name"] ,
    hobbies: Hobbies(
      sport: stu['hobbies']['sport'] ,
        music:stu['hobbies']['music'],
    ) ,
  )
  ).toList();
}
</code>```

I tried it on this dartPad draft and this worked..
https://dartpad.dev/b338f2a46bcb361de5e05c5ea6b8c74f

Title: Why I can't refer to a key in an object's another key?

Body:
Dart is not aware of what your structure is like, therefore, you have to make it aware by providing a cast.

void getStudentsList () {
  studentsList = (object["allStudents"] as List<Map<String,dynamic>>)
      .map((stu)=>
  Student(
    name: stu["name"] ,
    hobbies: Hobbies(
      sport: stu['hobbies']['sport'] ,
        music:stu['hobbies']['music'],
    ) ,
  )
  ).toList();
}

I tried it on this dartPad draft and this worked..
https://dartpad.dev/b338f2a46bcb361de5e05c5ea6b8c74f


问:
Why does my execve() only works when arguments include /bin/?
execve() only works when /bin/ is a prefix to the first argument

e.g. ./test.out ls finds nothing while ./test.out /bin/ls works

execve(argv[1], args, getenv("PATH"))

答:
execve does not search the PATH directories. The first parameter needs to refer to an actual file reachable from the current directory, so needs to contain / characters if the file is not in the current directory.

Linux supports execvpe as a GNU extension which is a cross between the execve and execvp POSIX functions. The p means it will search the PATH for the file as long as it contains no / characters.  (If it does contain / characters, it will the same as the non-p version.) The e means that a new environment is passed to the function in the third parameter.

OP's code passes an environment to the execve function that contains only the PATH environment variable from the original environment. If that is the intention, the same effect can be performed in a POSIX compliant manner by stripping the environment before calling execvp. This makes use of the extern char **environ; variable declared by #include <unistd.h>:

```<code>char *env_p = getenv("PATH");
char *args[] = {argv[1], argv[2], NULL};

if (environ[0]) {
    environ[0] = env_p;
    environ[1] = NULL;
}

if (execvp(argv[1], args) < 0) {
    perror("execvp");
    exit(EXIT_FAILURE);
}
</code>```

Body:
execve does not search the PATH directories. The first parameter needs to refer to an actual file reachable from the current directory, so needs to contain / characters if the file is not in the current directory.

Linux supports execvpe as a GNU extension which is a cross between the execve and execvp POSIX functions. The p means it will search the PATH for the file as long as it contains no / characters.  (If it does contain / characters, it will the same as the non-p version.) The e means that a new environment is passed to the function in the third parameter.

OP's code passes an environment to the execve function that contains only the PATH environment variable from the original environment. If that is the intention, the same effect can be performed in a POSIX compliant manner by stripping the environment before calling execvp. This makes use of the extern char **environ; variable declared by #include <unistd.h>:

char *env_p = getenv("PATH");
char *args[] = {argv[1], argv[2], NULL};

if (environ[0]) {
    environ[0] = env_p;
    environ[1] = NULL;
}

if (execvp(argv[1], args) < 0) {
    perror("execvp");
    exit(EXIT_FAILURE);
}


问:
How can I deal with a massive delete from Django Admin?
I'm working with Django 2.2.10.

I have a model called Site, and a model called Record.
Each record is associated with a single site (Foreign Key).

After my app runs for a few days/weeks/months, each site can have thousands of records associated with it. I use the database efficiently, so this isn't normally a problem.

In Django Admin, when I try to delete a site however, Django Admin tries to figure out every single associated object that will also be deleted, and because my ForeignKey uses on_delete=models.CASCADE, which is what I want, it tries to generate a page that lists thousands, possibly millions of records that will be deleted. Sometimes this succeeds, but takes a few seconds. Sometimes the browser just gives up waiting.

How can I have Django Admin not list every single record it intends to delete? Maybe just say something like "x number of records will be deleted" instead.

Update: Should I be overriding Django admin's delete_confirmation.html? It looks like the culprit might be this line:

```<code><ul>{{ deleted_objects|unordered_list }}</ul>
</code>```

Or is there an option somewhere that can be enabled to automatically not list every single object to be deleted, perhaps if the object count is over X number of objects?

Update 2: Removing the above line from delete_confirmation.html didn't help. I think it's the view that generates the deleted_objects variable that is taking too long. Not quite sure how to override a Django Admin view

答:
Add this to your admin class, and than you can delete with this action without warning

```<code>  actions = ["silent_delete"]

  def silent_delete(self, request, queryset):
    queryset.delete()
</code>```

If you want to hide default delete action, add this to your admin class

```<code>  def get_actions(self, request):
    actions = super().get_actions(request)
    if 'delete_selected' in actions:
      del actions['delete_selected']
    return actions
</code>```

Body:
I'm working with Django 2.2.10.

I have a model called Site, and a model called Record.
Each record is associated with a single site (Foreign Key).

After my app runs for a few days/weeks/months, each site can have thousands of records associated with it. I use the database efficiently, so this isn't normally a problem.

In Django Admin, when I try to delete a site however, Django Admin tries to figure out every single associated object that will also be deleted, and because my ForeignKey uses on_delete=models.CASCADE, which is what I want, it tries to generate a page that lists thousands, possibly millions of records that will be deleted. Sometimes this succeeds, but takes a few seconds. Sometimes the browser just gives up waiting.

How can I have Django Admin not list every single record it intends to delete? Maybe just say something like "x number of records will be deleted" instead.

Update: Should I be overriding Django admin's delete_confirmation.html? It looks like the culprit might be this line:

{{ deleted_objects|unordered_list }}

Or is there an option somewhere that can be enabled to automatically not list every single object to be deleted, perhaps if the object count is over X number of objects?

Update 2: Removing the above line from delete_confirmation.html didn't help. I think it's the view that generates the deleted_objects variable that is taking too long. Not quite sure how to override a Django Admin view

Body:
Add this to your admin class, and than you can delete with this action without warning

  actions = ["silent_delete"]

  def silent_delete(self, request, queryset):
    queryset.delete()

If you want to hide default delete action, add this to your admin class

  def get_actions(self, request):
    actions = super().get_actions(request)
    if 'delete_selected' in actions:
      del actions['delete_selected']
    return actions


问:
I am unable to create this variable
How do I create a variable in R, which takes a value
of 0 60% of the time and a value of 1 otherwise?</p>

答:
This should probably be on StackOverflow. Anyway, </p>

```<code>sample(0:1, 1, prob=c(0.6, 0.4))
</code>```

OwnerDisplayName: John Smith

Title: I am unable to create this variable

Body:
This should probably be on StackOverflow. Anyway,

sample(0:1, 1, prob=c(0.6, 0.4))

OwnerDisplayName: alan ocallaghan


答:
R offers a series of functions that produce random samples from common distributions. They are all named "r" followed by an abbreviation of the distribution; "rnorm" - random normal, "rpois" - random poisson, "runif" - random uniform (not run-if), etc. You're looking for "rbinom" - random binomial.

e.g.

```<code>rbinom(1, 1, 0.4)
</code>```

We use 0.4 instead of 0.6 because the function wants the probability of a 1 as the third argument.

Title: I am unable to create this variable

Body:
How do I create a variable in R, which takes a value
of 0 60% of the time and a value of 1 otherwise?

Body:
R offers a series of functions that produce random samples from common distributions. They are all named "r" followed by an abbreviation of the distribution; "rnorm" - random normal, "rpois" - random poisson, "runif" - random uniform (not run-if), etc. You're looking for "rbinom" - random binomial.

e.g.

rbinom(1, 1, 0.4)

We use 0.4 instead of 0.6 because the function wants the probability of a 1 as the third argument.

OwnerDisplayName: CFD


问:
Way to differ TypeScript object type from class type
Let's have class definition in typescript:

```<code>class User {
  public id: number;
  public name: string;
  public toString(): string{
    return name + id;
  }
}
</code>```

How to differ class from plain object in TypeScript?

```<code>const user1: User = new User();
const user2: User = {id: 1, name: 'John'};
</code>```

Those both are valid in TypeScript, but user1 is class instance and user2 is object.

I am asking that because I am expiriencing problems with TypeORM package where I am mixing objects and entity instances and it is starting to be very messy and I am not always sure if I have class instance or object.

答:
Method 1:

You can use instanceof User to check if its an instance of the class or not.

Method 2:

I'm using class-transformer to handle such scenarios, convert the instance to a class using plainToClass method before sending data to the repository.

Body:
Let's have class definition in typescript:

class User {
  public id: number;
  public name: string;
  public toString(): string{
    return name + id;
  }
}

How to differ class from plain object in TypeScript?

const user1: User = new User();
const user2: User = {id: 1, name: 'John'};

Those both are valid in TypeScript, but user1 is class instance and user2 is object.

I am asking that because I am expiriencing problems with TypeORM package where I am mixing objects and entity instances and it is starting to be very messy and I am not always sure if I have class instance or object.


问:
Null point Exception error in MapBlocks Android
I am trying to follow This tutorial
and I am getting an error
This is the stack trace

```<code>Process: com.example.mapp, PID: 7624
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mapp/com.example.mapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.mapboxsdk.maps.MapView.onCreate(android.os.Bundle)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.mapboxsdk.maps.MapView.onCreate(android.os.Bundle)' on a null object reference
        at com.example.mapp.MainActivity.onCreate(MainActivity.java:21)
</code>```

This the mapview part of activity_main.xml

```<code>    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="37.7747"
        mapbox:mapbox_cameraTargetLng="-122.4443"
        mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
        mapbox:mapbox_cameraZoom="12"
        />
</code>```

and this is complete MainActivity.Java ( Removed all the imports + few more functions of map box)

```<code>public class MainActivity extends AppCompatActivity {

    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Mapbox.getInstance(this, getString(R.string.access_token) );
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
</code>```

I tried the following links but they didn't work link 1 link 2 link 4

Thanks in advance.

答:
That YouTube video you're following is a bit old. Setting up a simple MapView is now done differently. For example, you can't set a map style URL via XML anymore.

https://docs.mapbox.com/android/maps/examples/create-a-simple-map-view shows the basic way to set up a Mapbox map.

Body:
I am trying to follow This tutorial
and I am getting an error
This is the stack trace

Process: com.example.mapp, PID: 7624
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mapp/com.example.mapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.mapboxsdk.maps.MapView.onCreate(android.os.Bundle)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.mapboxsdk.maps.MapView.onCreate(android.os.Bundle)' on a null object reference
        at com.example.mapp.MainActivity.onCreate(MainActivity.java:21)

This the mapview part of activity_main.xml

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="37.7747"
        mapbox:mapbox_cameraTargetLng="-122.4443"
        mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
        mapbox:mapbox_cameraZoom="12"
        />

and this is complete MainActivity.Java ( Removed all the imports + few more functions of map box)

public class MainActivity extends AppCompatActivity {

    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Mapbox.getInstance(this, getString(R.string.access_token) );
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}

I tried the following links but they didn't work link 1 link 2 link 4

Thanks in advance.


问:
RoomDatabase_Impl does not exist
I when try to implement a Room Database, I get the following error:

```<code>java.lang.RuntimeException: cannot find implementation for com.udacity.gradle.builditbigger.Database.HilarityUserDatabase. HilarityUserDatabase_Impl does not exist
                                                 at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:92)
</code>```

I tried adding the relevant kotlin dependencies to my gradle file (shown below) but when I do, all of my Databinding classes that would normally be generated with any issues are now generating errors in my gradle console. Is there way for me to use the DataBinding library and the Room Pesistence Library?

```<code>apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
...
dependencies{
    kapt "android.arch.persistence.room:compiler:1.0.0"
}
</code>```

答:
For the newer version of the room compiler don't need to add both dependencies, Just do the following -</p>

```<code>kapt 'android.arch.persistence.room:compiler:2.2.3'
</code>```

Title: RoomDatabase_Impl does not exist

Body:
I when try to implement a Room Database, I get the following error:

java.lang.RuntimeException: cannot find implementation for com.udacity.gradle.builditbigger.Database.HilarityUserDatabase. HilarityUserDatabase_Impl does not exist
                                                 at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:92)

I tried adding the relevant kotlin dependencies to my gradle file (shown below) but when I do, all of my Databinding classes that would normally be generated with any issues are now generating errors in my gradle console. Is there way for me to use the DataBinding library and the Room Pesistence Library?

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
...
dependencies{
    kapt "android.arch.persistence.room:compiler:1.0.0"
}

Body:
For the newer version of the room compiler don't need to add both dependencies, Just do the following -

kapt 'android.arch.persistence.room:compiler:2.2.3'


问:
WHERE DATE_COLUMN = '9999-12-31' statements causes query to return no results
I have a very odd problem with a query I was given to convert from Access to SQL Server.

The query works as expected until I add a condition in the WHERE clause to check for a specific date.

I was not sure that the date fields were compatible due to the SQL Server query needing to talk to a linked DB2 mainframe. So to test this to make sure the date is being read correctly I used DATEDIFF(). I also reduced the select statement to only the date field that is having the issue to try and figure out what is going on but I still have had no luck. I have tried ever way I can think of to filter the date.

I tried a HAVING clause.

```<code>HAVING TERM_DT = '9999-12-31'
</code>```

I tried a WHERE clause.

```<code>WHERE TERM_DT = '9999-12-31'
</code>```

I tried to compare the date in the JOIN.

```<code>INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'
</code>```

I tried to CAST and CONVERT the field to DATE thinking maybe the date fields were incompatible.

```<code>CAST(TERM_DT AS DATE) = CAST('9999-12-31' AS DATE)
CONVERT(DATE, TERM_DT) = CONVERT(DATE, '9999-12-31')
</code>```

In each of the above I also tried TERM_DT >= '9990-12-31' because nothing else worked and for some reason that column has a few typos like 9998-12-31 and 9999-11-31 so I figured checking from 9990 on should catch everything. Still nothing returned.

The last thing I tried was DATEDIFF(). And that didn't work either.

```<code>DATEDIFF(day, '9990-12-31', TERM_DT) >= 0
</code>```

Except when I placed the DATEDIFF() in the select statement and do not use anything in the WHERE section I get the values I expect...

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
</code>```

Data returned:

```<code>DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30
3287        9999-12-31
3287        9999-12-31
</code>```

But when I add the where statement in:

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) >= 0
</code>```

I get no results:

```<code>DIFF        DT
</code>```

Then I tried to flip the comparison with <= and the odd thing is I got all the values below 9999-12-31 as expected, so then why can I not get the values at 9999-12-31 to return? This is a very odd situation.

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) <= 0
</code>```

Oddly enough that worked as it should have:

```<code>WHERE TERM_DT = '9999-12-31'
</code>```0

So I can get the dates below 9999-12-31 but cannot get the dates at 9999-12-31.
Once I realized that checking for dates lower than 9999-12-31 worked in the DATEDIFF() function I went back and tried to do my original comparison and check for those lesser dates. It worked...

```<code>WHERE TERM_DT = '9999-12-31'
</code>```1

Results:

```<code>WHERE TERM_DT = '9999-12-31'
</code>```2

With the above results there is no reason for me to think that WHERE TERM_DT = '9999-12-31' would not return:

```<code>DIFF        DT
3287        9999-12-31
3287        9999-12-31
</code>```

But I don't get that. I get no results at all.

Update:

I tried DATEDIFF(day, '9990-12-31', DH230.DH230_TERM_DT) <> 0 as @Ziad Mehmood mentioned and strangely I get all the negative values but none of the positive values.

```<code>DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30
</code>```

2nd Update:

When I take my WHERE statement and move it to a CASE in the SELECT It clearly works. The Comparisons is correct. But just doesn't work in the WHERE section.

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
,CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end
FROM ...
JOIN ...
</code>```

Results:

```<code>DIFF        DT  (No column name)
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2912261    2017-07-01  False
-2912352    2017-04-01  False
3287        9999-12-31  True
3287        9999-12-31  True
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2911852    2018-08-14  False
-2911852    2018-08-14  False
</code>```

So another shot in the dark I ran the CASE statement in the WHERE clause.

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'True'
</code>```

But no results:

```<code>DIFF        DT
</code>```

Now here is where it gets odd again:

```<code>WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'False'
</code>```

Returns:

```<code>INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'
</code>```0

Absolutely bizarre!

Is there some issue between SQL Server and a linked DB2 mainframe that could cause this?

Is there any know reason for something like this to happen?

I did create a local SQL Server table from a select statement to check the data type of the field.

The field is the DATE data type according to SSMS.

For a reference I have added my full query below with some obfuscation. Maybe something about the JOIN's is causing the problem.

```<code>INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'
</code>```1

答:
Why not just use something like this?

```<code>where term_dt > '2100-01-01'
</code>```

I'd be surprised if you had real dates even that far in the future.

Also, you have your arguments to date_diff() backwards, which is why the number is negative.

Body:
I have a very odd problem with a query I was given to convert from Access to SQL Server.

The query works as expected until I add a condition in the WHERE clause to check for a specific date.

I was not sure that the date fields were compatible due to the SQL Server query needing to talk to a linked DB2 mainframe. So to test this to make sure the date is being read correctly I used DATEDIFF(). I also reduced the select statement to only the date field that is having the issue to try and figure out what is going on but I still have had no luck. I have tried ever way I can think of to filter the date.

I tried a HAVING clause.

HAVING TERM_DT = '9999-12-31'

I tried a WHERE clause.

WHERE TERM_DT = '9999-12-31'

I tried to compare the date in the JOIN.

INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'

I tried to CAST and CONVERT the field to DATE thinking maybe the date fields were incompatible.

CAST(TERM_DT AS DATE) = CAST('9999-12-31' AS DATE)
CONVERT(DATE, TERM_DT) = CONVERT(DATE, '9999-12-31')

In each of the above I also tried TERM_DT >= '9990-12-31' because nothing else worked and for some reason that column has a few typos like 9998-12-31 and 9999-11-31 so I figured checking from 9990 on should catch everything. Still nothing returned.

The last thing I tried was DATEDIFF(). And that didn't work either.

DATEDIFF(day, '9990-12-31', TERM_DT) >= 0

Except when I placed the DATEDIFF() in the select statement and do not use anything in the WHERE section I get the values I expect...

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...

Data returned:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30
3287        9999-12-31
3287        9999-12-31

But when I add the where statement in:

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) >= 0

I get no results:

DIFF        DT

Then I tried to flip the comparison with <= and the odd thing is I got all the values below 9999-12-31 as expected, so then why can I not get the values at 9999-12-31 to return? This is a very odd situation.

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) <= 0

Oddly enough that worked as it should have:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30

So I can get the dates below 9999-12-31 but cannot get the dates at 9999-12-31.
Once I realized that checking for dates lower than 9999-12-31 worked in the DATEDIFF() function I went back and tried to do my original comparison and check for those lesser dates. It worked...

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE TERM_DT < '9999-12-31'

Results:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30

With the above results there is no reason for me to think that WHERE TERM_DT = '9999-12-31' would not return:

DIFF        DT
3287        9999-12-31
3287        9999-12-31

But I don't get that. I get no results at all.

Update:

I tried DATEDIFF(day, '9990-12-31', DH230.DH230_TERM_DT) <> 0 as @Ziad Mehmood mentioned and strangely I get all the negative values but none of the positive values.

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30

2nd Update:

When I take my WHERE statement and move it to a CASE in the SELECT It clearly works. The Comparisons is correct. But just doesn't work in the WHERE section.

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
,CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end
FROM ...
JOIN ...

Results:

DIFF        DT  (No column name)
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2912261    2017-07-01  False
-2912352    2017-04-01  False
3287        9999-12-31  True
3287        9999-12-31  True
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2911852    2018-08-14  False
-2911852    2018-08-14  False

So another shot in the dark I ran the CASE statement in the WHERE clause.

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'True'

But no results:

DIFF        DT

Now here is where it gets odd again:

WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'False'

Returns:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911624    2019-03-30
-2911532    2019-06-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911852    2018-08-14
-2911852    2018-08-14

Absolutely bizarre!

Is there some issue between SQL Server and a linked DB2 mainframe that could cause this?

Is there any know reason for something like this to happen?

I did create a local SQL Server table from a select statement to check the data type of the field.

The field is the DATE data type according to SSMS.

For a reference I have added my full query below with some obfuscation. Maybe something about the JOIN's is causing the problem.

SELECT DATEDIFF(day, '9990-12-31', linked_db2_tbl11.linked_db2_tbl11_TERM_DT) AS "DIFF"
,linked_db2_tbl11.linked_db2_tbl11_TERM_DT AS "DT"

FROM local_database.dbo.local_table1 IR
RIGHT JOIN linked_db2_tbl1
INNER JOIN linked_db2_tbl2
INNER JOIN linked_db2_tbl3
INNER JOIN linked_db2_tbl4
INNER JOIN linked_db2_tbl5
INNER JOIN linked_db2_tbl6
INNER JOIN linked_db2_tbl7
INNER JOIN linked_db2_tbl8
INNER JOIN linked_db2_tbl9
ON linked_db2_tbl8.linked_db2_tbl8_SUB_SVC_TYP = linked_db2_tbl9.linked_db2_tbl9_SUB_SVC_TYP
INNER JOIN linked_db2_tbl10
ON linked_db2_tbl9.linked_db2_tbl9_PACKAGE_ID = linked_db2_tbl10.linked_db2_tbl10_PACKAGE_ID
ON linked_db2_tbl7.linked_db2_tbl7_PACKAGE_ID = linked_db2_tbl10.linked_db2_tbl10_PACKAGE_ID
INNER JOIN linked_db2_tbl11
ON linked_db2_tbl9.linked_db2_tbl9_SVC_TYP = linked_db2_tbl11.linked_db2_tbl11_SVC_TYP
AND linked_db2_tbl9.linked_db2_tbl9_PACKAGE_ID = linked_db2_tbl11.linked_db2_tbl11_PACKAGE_ID
ON linked_db2_tbl6.linked_db2_tbl6_COMP_ID = linked_db2_tbl7.linked_db2_tbl7_COMP_ID
AND linked_db2_tbl6.linked_db2_tbl6_COMP_ID = linked_db2_tbl11.linked_db2_tbl11_COMP_ID
ON linked_db2_tbl5.linked_db2_tbl5_COMP_ID = linked_db2_tbl6.linked_db2_tbl6_COMP_ID
ON linked_db2_tbl4.linked_db2_tbl4_ELEMENT_ID = linked_db2_tbl5.linked_db2_tbl5_ELEMENT_ID
AND linked_db2_tbl4.linked_db2_tbl4_ELEMENT_ID = linked_db2_tbl11.linked_db2_tbl11_ELEMENT_ID
ON linked_db2_tbl3.linked_db2_tbl3_ELEMENT_ID = linked_db2_tbl4.linked_db2_tbl4_ELEMENT_ID
AND linked_db2_tbl3.linked_db2_tbl3_CHG_CD = linked_db2_tbl11.linked_db2_tbl11_CHG_CD
ON linked_db2_tbl2.linked_db2_tbl2_CHG_CD = linked_db2_tbl3.linked_db2_tbl3_CHG_CD
ON linked_db2_tbl1.linked_db2_tbl1_SUB_SVC_TYP = linked_db2_tbl8.linked_db2_tbl8_SUB_SVC_TYP
AND linked_db2_tbl1.linked_db2_tbl1_HWIR_SVC_TYP = linked_db2_tbl8.linked_db2_tbl8_HWIR_SVC_TYP
AND linked_db2_tbl1.linked_db2_tbl1_SVC_ID = linked_db2_tbl11.linked_db2_tbl11_LEVEL_ID
INNER JOIN linked_db2_tbl12
INNER JOIN linked_db2_tbl13
ON linked_db2_tbl12.linked_db2_tbl12_RATE_PLAN = linked_db2_tbl13.linked_db2_tbl13_RATE_PLAN
ON linked_db2_tbl1.linked_db2_tbl1_SVC_ID = linked_db2_tbl13.linked_db2_tbl13_SVC_ID
INNER JOIN linked_db2_tbl14
ON linked_db2_tbl1.linked_db2_tbl1_UPPER_ID = linked_db2_tbl14.linked_db2_tbl14_CORP_ID
ON IR.CHG_CD = linked_db2_tbl11.linked_db2_tbl11_CHG_CD
LEFT JOIN linked_db2_tbl15
ON linked_db2_tbl14.linked_db2_tbl14_CORP_ID = linked_db2_tbl15.linked_db2_tbl15_INT_ID
INNER JOIN linked_db2_tbl18
ON linked_db2_tbl1.linked_db2_tbl1_CNTL_LOCN_ID = linked_db2_tbl18.linked_db2_tbl18_COMS_LOCN_ID
JOIN local_database.dbo.local_table2 OT
ON linked_db2_tbl14.linked_db2_tbl14_CORP_ID = OT.CORP_ID
WHERE OT.USER_ID = 'SOMEID'
AND DATEDIFF(day, '9990-12-31', linked_db2_tbl11.linked_db2_tbl11_TERM_DT) >= 0

Body:
Why not just use something like this?

where term_dt > '2100-01-01'

I'd be surprised if you had real dates even that far in the future.

Also, you have your arguments to date_diff() backwards, which is why the number is negative.


问:
Upload data from file with Python requests (like @file in curl)
I'm trying to set user's avatar in bitbucket using bitbucket API - https://docs.atlassian.com/bitbucket-server/rest/5.16.0/bitbucket-rest.html#idm8283193008. Curl example from docs works for me, but I have no idea how to get my python requests working with given endpoint. The response is always 415, which means "wrong content type". Besides that, I believe, everything works fine, looks like the only problem is json parameter in requests.post method. My question is what should I write in json={'avatar': } to make it equal to @image.png in curl.</p>

答: @furas answered my question. curl.trillworks.com is a great website to convert curl to python. In my case I shouldn't have used json={}, instead I should've used file={filename, file_binary}</p>