问:
How to Create Variable Definitions from Phrases using Regexes (Notepad++)
Suppose we have a list of phrases - words separated by spaces. And suppose we want to define a bunch of variables based on these phrases such that the following hold:

Phrases already exist and are surrounded by quotes (if not, you can easily use a regex to achieve this)

Phrases only contain letters (this actually isn't true for me in practice, but I can handle those cases manually)

Variable name, followed by an equals sign, should precede the phrase

Variable name should be a lowerCamelCase version of the phrase

Example

Input

```<code>"hello World"
"foo bAr"
</code>```

Expected Output

```<code>helloWorld = "hello World"
fooBar = "foo bAr"
</code>```

Use Case

Often in my line of work I am presented with a bunch of constants which come from an Excel spreadsheet and I need to define a bunch of variables in code for them. The phrases have spaces in them, but the variables can't. I'd usually like to keep the variable names as close to the phrases as I can. I'd like a way to do it in bulk, without having to individually type out each variable name.

Notes

I have come up with a way to do this, which I want to record here in case I need it in future and in case others might need it. I also want to post it here because I have a feeling there are optimizations that can be made to my process, or at least alternatives.

答:
I haven't found a single find/replace step that'll do everything for you, but I have managed to do it using a sequence of regexes, applied one after another. The first pulls out the content for the variable name and inserts the "=". The next one does the main heavy lifting and removes spaces and applies the correct casing. The final one ensures all variables begin with lowercase letters. Apply them in sequence to achieve the desired result.

Regex #1

All we're doing here is pulling content out of the quotes and inserting it on the left hand side.

Note: here and below, I need to use this character for whitespace because SO doesn't render it correctly: ␣. So replace that with a space when you use this or other regexes in this answer.

Find: "(.+)"

Replace: ␣\1 = "\1" (note the leading space)

In our example, after this step, we end up with:

```<code>hello World = "hello World"
foo bAr = "foo bAr"
</code>```

Regex #2

Here, we want to match each word on the left hand side, with the goal of removing the whitespace and simultaneously fixing the casing.

Find: ␣(\S)(\S+)(?=.*=) (note the leading space)

Replace: \u\1\L\2 (absence of space in replacement pattern achieves the removal of the space)

After this step, we end up with:

```<code>HelloWorld = "hello World"
FooBar = "foo bAr"
</code>```

Correct, except for the first letter of each variable name.

Regex #3

This fixes the leading characters to be lowercase:

Find: ^(.)

Replace: \l\1

After this step, our output is as desired:

```<code>helloWorld = "hello World"
fooBar = "foo bAr"
</code>```

Optional Regex #4 (Remove Invalid Characters)

Though the requirement assumed all letters, this is often not the case. First, you may want some numbers in there. Second, there may be junk like parentheses. In this case, just do a find/replace with the replace expression empty for the following find expression:

```<code>[^\w\r\n](?!=)(?=.*=)
</code>```

What that does is first matches negatively to anything that's not a letter, a digit, an underscore or an end of line character. It then ensures that the match is followed by an = down the line but not immediately followed by an =, meaning the space before the = is preserved.

As a Macro

Rather than manually do all 4 steps above, you can record them as a macro and save it to your Notepad++. Or just paste the XML below inside the <Macros> XML element in the file shortcuts.xml inside %appdata%\Notepad++. If you do paste, the shortcut is ctrl+alt+shift+V, but you can change that to whatever you want:

```<code><Macro name="DefineVariables" Ctrl="yes" Alt="yes" Shift="yes" Key="86">
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="(.+)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam=' \1 = "\1"' />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam=" (\S)(\S+)(?=.*=)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="\u\1\L\2" />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="^(.)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="\l\1" />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="[^\w\r\n](?!=)(?=.*=)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
</Macro>
</code>```

Body:
Suppose we have a list of phrases - words separated by spaces. And suppose we want to define a bunch of variables based on these phrases such that the following hold:

Phrases already exist and are surrounded by quotes (if not, you can easily use a regex to achieve this)

Phrases only contain letters (this actually isn't true for me in practice, but I can handle those cases manually)

Variable name, followed by an equals sign, should precede the phrase

Variable name should be a lowerCamelCase version of the phrase

Example

Input

"hello World"
"foo bAr"

Expected Output

helloWorld = "hello World"
fooBar = "foo bAr"

Use Case

Often in my line of work I am presented with a bunch of constants which come from an Excel spreadsheet and I need to define a bunch of variables in code for them. The phrases have spaces in them, but the variables can't. I'd usually like to keep the variable names as close to the phrases as I can. I'd like a way to do it in bulk, without having to individually type out each variable name.

Notes

I have come up with a way to do this, which I want to record here in case I need it in future and in case others might need it. I also want to post it here because I have a feeling there are optimizations that can be made to my process, or at least alternatives.

Body:
I haven't found a single find/replace step that'll do everything for you, but I have managed to do it using a sequence of regexes, applied one after another. The first pulls out the content for the variable name and inserts the "=". The next one does the main heavy lifting and removes spaces and applies the correct casing. The final one ensures all variables begin with lowercase letters. Apply them in sequence to achieve the desired result.

Regex #1

All we're doing here is pulling content out of the quotes and inserting it on the left hand side.

Note: here and below, I need to use this character for whitespace because SO doesn't render it correctly: ␣. So replace that with a space when you use this or other regexes in this answer.

Find: "(.+)"

Replace: ␣\1 = "\1" (note the leading space)

In our example, after this step, we end up with:

hello World = "hello World"
foo bAr = "foo bAr"

Regex #2

Here, we want to match each word on the left hand side, with the goal of removing the whitespace and simultaneously fixing the casing.

Find: ␣(\S)(\S+)(?=.*=) (note the leading space)

Replace: \u\1\L\2 (absence of space in replacement pattern achieves the removal of the space)

After this step, we end up with:

HelloWorld = "hello World"
FooBar = "foo bAr"

Correct, except for the first letter of each variable name.

Regex #3

This fixes the leading characters to be lowercase:

Find: ^(.)

Replace: \l\1

After this step, our output is as desired:

helloWorld = "hello World"
fooBar = "foo bAr"

Optional Regex #4 (Remove Invalid Characters)

Though the requirement assumed all letters, this is often not the case. First, you may want some numbers in there. Second, there may be junk like parentheses. In this case, just do a find/replace with the replace expression empty for the following find expression:

[^\w\r\n](?!=)(?=.*=)

What that does is first matches negatively to anything that's not a letter, a digit, an underscore or an end of line character. It then ensures that the match is followed by an = down the line but not immediately followed by an =, meaning the space before the = is preserved.

As a Macro

Rather than manually do all 4 steps above, you can record them as a macro and save it to your Notepad++. Or just paste the XML below inside the <Macros> XML element in the file shortcuts.xml inside %appdata%\Notepad++. If you do paste, the shortcut is ctrl+alt+shift+V, but you can change that to whatever you want:

<Macro name="DefineVariables" Ctrl="yes" Alt="yes" Shift="yes" Key="86">
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="(.+)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam=' \1 = &quot;\1&quot;' />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam=" (\S)(\S+)(?=.*=)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="\u\1\L\2" />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="^(.)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="\l\1" />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="[^\w\r\n](?!=)(?=.*=)" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
    <Action type="3" message="1701" wParam="0" lParam="1609" sParam="" />
</Macro>


来源: stackexchange

问:
Normalisation--2NF vs 3NF
We say 2NF is "the whole key" and 3NF "nothing but the key".

Referencing this answer by Smashery:

What are database normal forms and can you give examples?

The example used for 3NF is exactly the same as 2NF--it's a field which is dependent on only one key attribute. How is the example for 3NF different from the one for 2NF?

答:
Since you ask very specific question about an answer for existing so question here is an explanation of that (and basically I'll say what dportas already said in his answer, but in more words).

The examples of design that is not in 2NF and not in 3NF are not the same.

Yes, the dependency in both cases is on a single field.

However, in non 2NF example:

dependency is on the part of the primary key

while in non 3NF example (which is in 2NF):

dependency is on a field that is not a part of the primary key (and also notice that in that example it does satisfy 2NF; this is to show that even if you check for 2NF you should also check for 3NF)

In both cases to normalize you would create additional table which would not exhibit update anomalies (example of update anomaly: in 2NF example, what happens if you update Coursename for IT101|2009-2, but not for IT101|2009-1? You get inconsistent=meaningless=unusable data).

So, if you memorize the key, the whole key and nothing but the key, which covers both 2NF and 3NF, that should work for you in practice when normalizing. The distinction between 2NF and 3NF might seem subtle to you (question if in the additional dependency the attribute(s) on which the data is dependent are part of candidate key or not) - and, well, it is - so just accept it.

ContentLicense: CC BY-SA 4.0

Title: Normalisation--2NF vs 3NF

ContentLicense: CC BY-SA 3.0


问:
Trying to do Dynamic Equity Split calculations in Google Sheets
new to using javascript in Google Sheets. I am trying to create a sheet that automatically calculates what business partners will receive based upon their dynamic split percentage and the incoming money. The percentage comes from one cell, but each payment made to the partners will be entered in a column. Here's what I have so far:

```<code>/**
* Creates a Date Stamp if a column is edited.
* Also performs dynamic split calculations
*/

//CORE VARIABLES
// The column you want to check if something is entered.
var COLUMNTOCHECK = 13;
// Where you want the date time stamp offset from the input location. [row, column]
var DATETIMELOCATION = [0,-1];
// Where the calculations will be performed for the Partners.
var PARTNERONELOCATION = [0, 1];
var PARTNERTWOLOCATION = [0, 2];
var PARTNERTHREELOCATION = [0, 3];
// Sheet you are working on
var SHEETNAME1 = 'Sheet1'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var partnerOnePercent = sheet.getRange("G2").getValue();
  var partnerOnePaySource = sheet.getRange("M2").getValue();
  var partnerTwoPercent = sheet.getRange("G3").getValue();
  var partnerTwoPaySource = sheet.getRange("M2").getValue();
  var partnerThreePercent = sheet.getRange("G4").getValue();
  var partnerThreePaySource = sheet.getRange("M2").getValue();
  //checks that we're on the correct sheet.
  if(sheet.getSheetName() == SHEETNAME1 ) {
    var selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date and calculations to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK) {
      var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
      dateTimeCell.setValue(new Date());
      var partnerOneCell = selectedCell.offset(PARTNERONELOCATION[0],PARTNERONELOCATION[1]);
      partnerOneCell.setValue((partnerOnePercent/100)*partnerOnePaySource);
      var partnerTwoCell = selectedCell.offset(PARTNERTWOLOCATION[0],PARTNERTWOLOCATION[1]);
      partnerTwoCell.setValue((partnerTwoPercent/100)*partnerTwoPaySource);
      var partnerThreeCell = selectedCell.offset(PARTNERTHREELOCATION[0],PARTNERTHREELOCATION[1]);
      partnerThreeCell.setValue((partnerThreePercent/100)*partnerThreePaySource);
      }
  }
}
</code>```

The thing I would like it to do is when I enter a payment into the column (column 13), Is for the payment to be split into the partner location cells (var partnerOneCell, var partnerTwoCell, var partnerThreeCell) that are offset from the cell that the payment amount is typed in, and I only want it to be calculated by the percentages as they are at the moment the payment amount is entered. Any help would be appreciated.

Right now it is only calculating based upon cell M2 (row 2, column 13). I want it to be able to calculate based upon the amount I enter in any cell within that column, and only the cell I am currently updating. I think that this has something to do with getActiveRange or something, but I'm not familiar enough with these methods.

Edit: Upon testing, it also seems that row 3 column 14 is reflecting a calculation of partnerOnePaySource*partnerOnePercent with PaySource coming from row 3 column 13 (M3), though I'm not sure why.

答:
Alright everyone, after reading over my code, I realized how I could use the getActiveCell method within the PaySource variables.

```<code>var partnerOnePercent = sheet.getRange("G2").getValue();
  var partnerOnePaySource = ss.getActiveCell().getValue();
  var partnerTwoPercent = sheet.getRange("G3").getValue();
  var partnerTwoPaySource = ss.getActiveCell().getValue();
  var partnerThreePercent = sheet.getRange("G4").getValue();
  var partnerThreePaySource = ss.getActiveCell().getValue();
</code>```

With this I was able to fix my problem and it now works.

Body:
new to using javascript in Google Sheets. I am trying to create a sheet that automatically calculates what business partners will receive based upon their dynamic split percentage and the incoming money. The percentage comes from one cell, but each payment made to the partners will be entered in a column. Here's what I have so far:

/**
* Creates a Date Stamp if a column is edited.
* Also performs dynamic split calculations
*/

//CORE VARIABLES
// The column you want to check if something is entered.
var COLUMNTOCHECK = 13;
// Where you want the date time stamp offset from the input location. [row, column]
var DATETIMELOCATION = [0,-1];
// Where the calculations will be performed for the Partners.
var PARTNERONELOCATION = [0, 1];
var PARTNERTWOLOCATION = [0, 2];
var PARTNERTHREELOCATION = [0, 3];
// Sheet you are working on
var SHEETNAME1 = 'Sheet1'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var partnerOnePercent = sheet.getRange("G2").getValue();
  var partnerOnePaySource = sheet.getRange("M2").getValue();
  var partnerTwoPercent = sheet.getRange("G3").getValue();
  var partnerTwoPaySource = sheet.getRange("M2").getValue();
  var partnerThreePercent = sheet.getRange("G4").getValue();
  var partnerThreePaySource = sheet.getRange("M2").getValue();
  //checks that we're on the correct sheet.
  if(sheet.getSheetName() == SHEETNAME1 ) {
    var selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date and calculations to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK) {
      var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
      dateTimeCell.setValue(new Date());
      var partnerOneCell = selectedCell.offset(PARTNERONELOCATION[0],PARTNERONELOCATION[1]);
      partnerOneCell.setValue((partnerOnePercent/100)*partnerOnePaySource);
      var partnerTwoCell = selectedCell.offset(PARTNERTWOLOCATION[0],PARTNERTWOLOCATION[1]);
      partnerTwoCell.setValue((partnerTwoPercent/100)*partnerTwoPaySource);
      var partnerThreeCell = selectedCell.offset(PARTNERTHREELOCATION[0],PARTNERTHREELOCATION[1]);
      partnerThreeCell.setValue((partnerThreePercent/100)*partnerThreePaySource);
      }
  }
}

The thing I would like it to do is when I enter a payment into the column (column 13), Is for the payment to be split into the partner location cells (var partnerOneCell, var partnerTwoCell, var partnerThreeCell) that are offset from the cell that the payment amount is typed in, and I only want it to be calculated by the percentages as they are at the moment the payment amount is entered. Any help would be appreciated.

Right now it is only calculating based upon cell M2 (row 2, column 13). I want it to be able to calculate based upon the amount I enter in any cell within that column, and only the cell I am currently updating. I think that this has something to do with getActiveRange or something, but I'm not familiar enough with these methods.

Edit: Upon testing, it also seems that row 3 column 14 is reflecting a calculation of partnerOnePaySource*partnerOnePercent with PaySource coming from row 3 column 13 (M3), though I'm not sure why.

Body:
Alright everyone, after reading over my code, I realized how I could use the getActiveCell method within the PaySource variables.

var partnerOnePercent = sheet.getRange("G2").getValue();
  var partnerOnePaySource = ss.getActiveCell().getValue();
  var partnerTwoPercent = sheet.getRange("G3").getValue();
  var partnerTwoPaySource = ss.getActiveCell().getValue();
  var partnerThreePercent = sheet.getRange("G4").getValue();
  var partnerThreePaySource = ss.getActiveCell().getValue();

With this I was able to fix my problem and it now works.


问:
Adding Custom Gallery in WIX Code connected to WIX Events
I have been working with WIX for a while but never used the code or CORVID feature.
I want to create a homepage with a gallery of images connected to my WIX events. I have successfully done that with the DATABASE connection and now my event images, title and descriptions show in the gallery.
Now the problem is that I cannot give format to the text, I think I can do this with CORVID but I have no idea how, can anyone help me?
PS I am not a developer so if you can provide a code sample it will make it easier for me.
Thanks!</p>

答: You cannot customize design elements of the gallery using Corvid. Check the documentation for Gallery available here: https://www.wix.com/corvid/reference/$w.Gallery.html</p>


问:
Onscroll function is not working for Chrome
The below code is working fine for Firefox browser. But, not chrome. What is the issue in below code ?

```<code>window.onload = function()
{
   document.body.onscroll =  Test.callFn;
}

var Test = new function()
{
   this.callFn = function()
   {
      console.log("Calling this function");
   }
}
</code>```

Thanks

答:
window.onscroll does not work at times when you style an element using theheight property of css.

try using min-height or max-height instead.

Body:
The below code is working fine for Firefox browser. But, not chrome. What is the issue in below code ?

window.onload = function()
{
   document.body.onscroll =  Test.callFn;
}

var Test = new function()
{
   this.callFn = function()
   {
      console.log("Calling this function");
   }
}

Thanks


问:
Bootstrap not loading styles properly
I'm trying to write a small application using bootstrap but it seems it doesn't load the styles at all, even tho i included all bootstrap references properly, here is some code (i am using PUG, but i can provide the final HTML if needed)

```<code>extends layout

block content
  link(rel='stylesheet', href='/stylesheets/index.css')

  .container
    .row
      .col-md-8
        section
          h1.entry-title
            span Sign Up
          hr
          form#signup.form-horizontal(method='post' name='signup' enctype='multipart/form-data')
            .form-group
              label.control-label.col-sm-3
                | Email ID
                span.text-danger *
              .col-md-8.col-sm-9
                .input-group
                  span.input-group-addon
                    i.fas.fa-envelope-open-text
                  input#emailid.form-control(type='email' name='emailid' placeholder='Enter your Email ID' value='')
            .form-group
              .col-xs-offset-3.col-xs-10
                input.btn.btn-primary(name='Submit' type='submit' value='Sign Up')
</code>```

The code of layout is this

```<code>doctype html
html(lang='en')
  head
    title= title

    meta(charset='utf-8')
    meta(name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no')
    link(href='bootstrap/css/bootstrap.css', rel='stylesheet', media="all")

  body
    block content

    script(src='jquery/jquery-3.4.1.min.js')
    script(src='bootstrap/js/bootstrap.bundle.js')
    script(src='https://kit.fontawesome.com/ae629fb23c.js')
</code>```

I did check all the files and it does load bootstrap css and js, it just doesn't apply any styles, as seen here

Screenshot

答:
The way your templates are setup, the link element loading your custom styles is placed in the body instead of the head where it belongs. Try something like this, which makes use of the prepend and append directives:

layout.pug

```<code>doctype html
html(lang='en')
  head
    block head
      title= title
      meta(charset='utf-8')
      meta(name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no')
      link(href='bootstrap/css/bootstrap.css', rel='stylesheet', media="all")

  body
    block content
      script(src='jquery/jquery-3.4.1.min.js')
      script(src='bootstrap/js/bootstrap.bundle.js')
      script(src='https://kit.fontawesome.com/ae629fb23c.js')
</code>```

page.pug

```<code>extends layout

append head
  link(rel='stylesheet', href='/stylesheets/index.css')

prepend content
  .container
    .row
      .col-md-8
        section
          h1.entry-title
            span Sign Up
          hr
          form#signup.form-horizontal(method='post' name='signup' enctype='multipart/form-data')
            .form-group
              label.control-label.col-sm-3
                | Email ID
                span.text-danger *
              .col-md-8.col-sm-9
                .input-group
                  span.input-group-addon
                    i.fas.fa-envelope-open-text
                  input#emailid.form-control(type='email' name='emailid' placeholder='Enter your Email ID' value='')
            .form-group
              .col-xs-offset-3.col-xs-10
                input.btn.btn-primary(name='Submit' type='submit' value='Sign Up')
</code>```

Title: Bootstrap not loading styles properly

Body:
I'm trying to write a small application using bootstrap but it seems it doesn't load the styles at all, even tho i included all bootstrap references properly, here is some code (i am using PUG, but i can provide the final HTML if needed)

extends layout

block content
  link(rel='stylesheet', href='/stylesheets/index.css')

  .container
    .row
      .col-md-8
        section
          h1.entry-title
            span Sign Up
          hr
          form#signup.form-horizontal(method='post' name='signup' enctype='multipart/form-data')
            .form-group
              label.control-label.col-sm-3
                | Email ID
                span.text-danger *
              .col-md-8.col-sm-9
                .input-group
                  span.input-group-addon
                    i.fas.fa-envelope-open-text
                  input#emailid.form-control(type='email' name='emailid' placeholder='Enter your Email ID' value='')
            .form-group
              .col-xs-offset-3.col-xs-10
                input.btn.btn-primary(name='Submit' type='submit' value='Sign Up')

The code of layout is this

doctype html
html(lang='en')
  head
    title= title

    meta(charset='utf-8')
    meta(name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no')
    link(href='bootstrap/css/bootstrap.css', rel='stylesheet', media="all")

  body
    block content

    script(src='jquery/jquery-3.4.1.min.js')
    script(src='bootstrap/js/bootstrap.bundle.js')
    script(src='https://kit.fontawesome.com/ae629fb23c.js')

I did check all the files and it does load bootstrap css and js, it just doesn't apply any styles, as seen here

Screenshot

Body:
The way your templates are setup, the link element loading your custom styles is placed in the body instead of the head where it belongs. Try something like this, which makes use of the prepend and append directives:

layout.pug

doctype html
html(lang='en')
  head
    block head
      title= title
      meta(charset='utf-8')
      meta(name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no')
      link(href='bootstrap/css/bootstrap.css', rel='stylesheet', media="all")

  body
    block content
      script(src='jquery/jquery-3.4.1.min.js')
      script(src='bootstrap/js/bootstrap.bundle.js')
      script(src='https://kit.fontawesome.com/ae629fb23c.js')

page.pug

extends layout

append head
  link(rel='stylesheet', href='/stylesheets/index.css')

prepend content
  .container
    .row
      .col-md-8
        section
          h1.entry-title
            span Sign Up
          hr
          form#signup.form-horizontal(method='post' name='signup' enctype='multipart/form-data')
            .form-group
              label.control-label.col-sm-3
                | Email ID
                span.text-danger *
              .col-md-8.col-sm-9
                .input-group
                  span.input-group-addon
                    i.fas.fa-envelope-open-text
                  input#emailid.form-control(type='email' name='emailid' placeholder='Enter your Email ID' value='')
            .form-group
              .col-xs-offset-3.col-xs-10
                input.btn.btn-primary(name='Submit' type='submit' value='Sign Up')


问:
google function: accessing firestore database of another project
I would like a Google Cloud project A (project-a-id) to access the firestore data of another Google Cloud project B (project-b-id). For the same I added project A default service account viz. project-a-id@appspot.gserviceaccount.com in the IAM of project B and set the role to Cloud Filestore Editor.

In the cloud function of project A, I am trying to access both project A's (its own) firestore as well as project B's firestore but it keeps showing project A default database for both Apps. The code is:

```<code>var primaryAppConfig = {
  databaseURL: 'https://project-a-id.firebaseio.com'
};
var primaryApp = admin.initializeApp(primaryAppConfig, 'primary');
var primarydb = admin.firestore(primaryApp);

var secondaryAppConfig = {
  databaseURL: 'https://project-b-id.firebaseio.com'
};
var secondaryApp = admin.initializeApp(secondaryAppConfig, 'secondary');
var secondarydb = admin.firestore(secondaryApp);

</code>```

I was under the impression if the default service account of project-a is given rights in project-b it should automatically get rights. At least I found it applicable when I am accessing google cloud storage buckets in this manner.

Is something else to be done? Thanks

答:
You need to create apps within current firebase project.

Firebase Console -> Project Setting -> General -> Add App

These apps will have access to same firestore but will be deployed seperately under different subdomains(under firebaseapp.com).

Body:
I would like a Google Cloud project A (project-a-id) to access the firestore data of another Google Cloud project B (project-b-id). For the same I added project A default service account viz. project-a-id@appspot.gserviceaccount.com in the IAM of project B and set the role to Cloud Filestore Editor.

In the cloud function of project A, I am trying to access both project A's (its own) firestore as well as project B's firestore but it keeps showing project A default database for both Apps. The code is:

var primaryAppConfig = {
  databaseURL: 'https://project-a-id.firebaseio.com'
};
var primaryApp = admin.initializeApp(primaryAppConfig, 'primary');
var primarydb = admin.firestore(primaryApp);

var secondaryAppConfig = {
  databaseURL: 'https://project-b-id.firebaseio.com'
};
var secondaryApp = admin.initializeApp(secondaryAppConfig, 'secondary');
var secondarydb = admin.firestore(secondaryApp);

I was under the impression if the default service account of project-a is given rights in project-b it should automatically get rights. At least I found it applicable when I am accessing google cloud storage buckets in this manner.

Is something else to be done? Thanks


问:
Date Conversion from value in C#
Does anyone possibly recognize the following value "40195.315752" as a date?  I need to convert/format this value-based date to a System.DateTime object, but don't understand it's format.

Thanks.

答:
It's a serial date-time, which means it's the number of days since a particular date. Note that you need to know the date which it is an offset to. In Excel, that would be Jan 1st, 1900, which makes your date 17/01/2010  07:34:41, but other programs will vary.

Another common start date is 1st January 1970 (Unix Epoch).

Title: Date Conversion from value in C#


问:
Aurora database exceeding capacity due to "/io/file/myisam/kfile" Wait
This morning, one of our Aurora clusters suddenly began experiencing high latency, slower running queries and was being reported as exceeding exceeding capacity - with up to 20 sessions for the db.r5.large instance which has only 2 CPUs.

There we no code changes, no deploy, no background process or any other cause we can identify. The higher latency is intermittent, occurring every 10 minutes and lasting for about as long. The Aurora monitoring isn't helping much, the only change of note being higher latency on the all queries (selects, updates and deletes).

Under Performance Metrics, the cases where usage spikes - we're seeing that of the total 20 sessions, these are attributed almost solely to the io/file/myisam/kfile Wait. Researching online has yielded very little and so I'm somewhat stumped as to what this means, and how to go about getting to the cause of the issue. Looking at the SQL queries ran during spikes, their slow run time appears more caused by the intermittent issue - as opposed to the being the cause of it.

So my question is: can anyone explain what the 'myisam/kfile' Wait is, and how I can use this knowledge to help diagnose the cause of the problem here?

My feeling is that it's one of those rare occurrences where an AWS instance unexplainably goes rogue at a level below which we can directly control and is only solved by spinning up a new instance (even where all else is equal from a configuration and code perspective). All the same, I'd love to better understand the issue here, especially when none of our DB table are MyISAM, all being innoDB.

答:
Is there a table called kfile?  How big is it?  What operations are being performed?

While the problem is occurring, do SHOW FULL PROCESSLIST; to see what is running.  That may give a good clue.

If the slowlog is turned on, look at it shortly after the problem has subsided; probably the naughty query will be at the end of the list.  Publish pt-query-digest path_to_slowlog.  The first one or two queries are very likely to be the villains.

Check SHOW ENGINE INNODB STATUS;.  Near the front will be the "latest deadlock".  That may be a clue.

In most situations most of the graphs don't provide any useful information.  When something does go wrong, it is not obvious which graph to look at.  I would look for graphs that look "different" in sync with the problem.  The one you show us perhaps indicates that there is a 20-second timeout, and everyone is stuck until they hit that timeout.

Do you run any ALTERs?  When do backups occur?

Are you using MyISAM?  Don't.  That ENGINE does not allow concurrency, hence could lead to a bunch of queries piling up.  More on converting to InnoDB: http://mysql.rjweb.org/doc.php/myisam2innodb


问:
Unable to hide "Chrome is being controlled by automated software" infobar within Chrome v76
After updating Chrome to version 76, I cannot figure out how to hide the "Chrome is being controlled by automated software..." notification overriding some controls on the page.

The latest stable release of ChromeDriver is indeed 76.0.3809.68.
The following code worked with Chrome 75 and ChromeDriver 74.

```<code>var options = new ChromeOptions();
options.AddArgument("--test-type");
options.AddArgument("--disable-extensions");
options.AddArguments("disable-infobars");
options.AddArguments("--disable-notifications");
options.AddArguments("enable-automation");
options.AddArguments("--disable-popup-blocking");
options.AddArguments("start-maximized");
var driver = new ChromeDriver(driverLocation, options, ScriptTimeout);
</code>```

答:
You can use --app=desired_address_without_brackets flag, e.g. --app=https://google.com. Works in Chrome 80.

Of course it works only if it's acceptable for your project to be launched in App mode and you have a page link you can insert there. See this answer of mine for a little more info.

You can also use --test-type command line flag, which removes such infobars too.

Attention! In very rare cases it causes strange things like muting page sound! So I'm not sure I should recommend it in the first place.

Body:
After updating Chrome to version 76, I cannot figure out how to hide the "Chrome is being controlled by automated software..." notification overriding some controls on the page.

The latest stable release of ChromeDriver is indeed 76.0.3809.68.
The following code worked with Chrome 75 and ChromeDriver 74.

var options = new ChromeOptions();
options.AddArgument("--test-type");
options.AddArgument("--disable-extensions");
options.AddArguments("disable-infobars");
options.AddArguments("--disable-notifications");
options.AddArguments("enable-automation");
options.AddArguments("--disable-popup-blocking");
options.AddArguments("start-maximized");
var driver = new ChromeDriver(driverLocation, options, ScriptTimeout);


问:
add annotation to static method with byte buddy
I have the following code

public class InstrumentedArquillian extends BlockJUnit4ClassRunner {
   static {
      net.bytebuddy.agent.ByteBuddyAgent.install();
      new ByteBuddy()
            .redefine(BaseIT.class)
            .method(named("createDeployment"))
            .intercept(???)
            .annotateMethod(AnnotationDescription.Builder.ofType(Deployment.class).build())
            .make()
            .load(InstrumentedArquillian.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()).getLoaded();
   }
}
```

<pre class="lang-java prettyprint-override"><code>public class BaseIT {

   public static WebArchive createDeployment() {
      return DeploymentBuilder.war();
   }
}
</code>```

I would like to add the annotation Deployment, method createDeployment, class BaseIT without changing any kind of implementation

答:
Well, later I found Add method annotation at runtime with Byte Buddy

         net.bytebuddy.agent.ByteBuddyAgent.install();
         Method existingMethod = BaseIT.class.getMethod("createDeployment");
         AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType(Deployment.class).build();
         AsmVisitorWrapper visit = new MemberAttributeExtension.ForMethod().annotateMethod(annotationDescription).on(ElementMatchers.anyOf(existingMethod));
         new ByteBuddy()
               .redefine(BaseIT.class)
               .visit(visit)
               .make()
               .load(InstrumentedArquillian.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()).getLoaded();
```

```        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy</artifactId>
            <version>1.10.0</version>
        </dependency>
        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy-agent</artifactId>
            <version>1.10.0</version>
        </dependency>
```

Body:
I have the following code

public class InstrumentedArquillian extends BlockJUnit4ClassRunner {
   static {
      net.bytebuddy.agent.ByteBuddyAgent.install();
      new ByteBuddy()
            .redefine(BaseIT.class)
            .method(named("createDeployment"))
            .intercept(???)
            .annotateMethod(AnnotationDescription.Builder.ofType(Deployment.class).build())
            .make()
            .load(InstrumentedArquillian.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()).getLoaded();
   }
}

public class BaseIT {

   public static WebArchive createDeployment() {
      return DeploymentBuilder.war();
   }
}

I would like to add the annotation Deployment, method createDeployment, class BaseIT without changing any kind of implementation

Body:
Well, later I found Add method annotation at runtime with Byte Buddy

         net.bytebuddy.agent.ByteBuddyAgent.install();
         Method existingMethod = BaseIT.class.getMethod("createDeployment");
         AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType(Deployment.class).build();
         AsmVisitorWrapper visit = new MemberAttributeExtension.ForMethod().annotateMethod(annotationDescription).on(ElementMatchers.anyOf(existingMethod));
         new ByteBuddy()
               .redefine(BaseIT.class)
               .visit(visit)
               .make()
               .load(InstrumentedArquillian.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()).getLoaded();

        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy</artifactId>
            <version>1.10.0</version>
        </dependency>
        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy-agent</artifactId>
            <version>1.10.0</version>
        </dependency>


问:
Alignment between thermal and color images
I have an RGB color image and a corresponding thermal image, generated by the same thermal camera. I'd like to check if these two images are aligned. so my question is how can I know if these two images of the same size are aligned or co-registred? are there any metrics or measurements that allow that?
Thank you in advance</p>

答: Interesting question.  Matlab suggests you start w/ an intensity-based approach.  There are more suggestions here.  In general, not a "plug and chug" type problem.</p>


问:
Regular expression
Need to replace this string

'Acute Tox. 4 ;H302|Eye Irrit. 2A;H319'

with this

'Acute Tox. 4 (H302)|Eye Irrit. 2A;(H319)'

Basically I need to put all H codes in parentheses.

I tried:

```<code>select REGEXP_replace('Acute Tox. 4 ;H302|Eye Irrit. 2A;H319',';H\d{3}','(H') from dual;
</code>```

but that results in:

```<code>Acute Tox. 4 (H|Eye Irrit. 2A(H
</code>```

答:
You can use:</p>

```<code>select REGEXP_replace('Acute Tox. 4 ;H302|Eye Irrit. 2A;H319',';(H\d{3})',';(\1)') from dual;
</code>```

Title: Regular expression

Body:
Need to replace this string

'Acute Tox. 4 ;H302|Eye Irrit. 2A;H319'

with this

'Acute Tox. 4 (H302)|Eye Irrit. 2A;(H319)'

Basically I need to put all H codes in parentheses.

I tried:

select REGEXP_replace('Acute Tox. 4 ;H302|Eye Irrit. 2A;H319',';H\d{3}','(H') from dual;

but that results in:

Acute Tox. 4 (H|Eye Irrit. 2A(H

Body:
You can use:

select REGEXP_replace('Acute Tox. 4 ;H302|Eye Irrit. 2A;H319',';(H\d{3})',';(\1)') from dual;


问:
Redirect 403 forbidden error message to 404 in IIS
If we post the URL by appending the text "/../../../../ " at the end. IIS returns a "403 - Forbidden" error in the response header.

Is there any way to configure IIS to return a "404 - Not Found" error instead of a "403"?

This is an asp.net web application.

A security scan of our site noted that returning "403" could assist a malicious person mapping our site; had not thought of that before, but I have to admit it makes sense.

答:
I Had to do the same thing because of a security scan too.
Here is my solution, do this on your web.config file. In my case I had custom html pages for error codes, witch I believe is a good practice.

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="false" />
        <httpErrors errorMode="Custom">
            <remove statusCode="404" />
            <error statusCode="404" path="/physical_path_to_your_custom_404_page_relative_to_the_web.config_file/404.html" responseMode="Redirect" />
            <error statusCode="403" subStatusCode="14" path="/physical_path_to_your_custom_404_page_relative_to_the_web.config_file/404.html" responseMode="Redirect" />
        </httpErrors>
    </system.webServer>
</configuration>
</code>```

With that, both the real 404 errors and 403.14 (.14 is the specific code for reaching a real path but with browsing denied) errors will redirect to a 404 error page. There will be no 403 to be seen, so for the end user both are 404 errors.

edit: you may need to install the "http errors" feature for this to work.

Body:
I Had to do the same thing because of a security scan too.
Here is my solution, do this on your web.config file. In my case I had custom html pages for error codes, witch I believe is a good practice.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="false" />
        <httpErrors errorMode="Custom">
            <remove statusCode="404" />
            <error statusCode="404" path="/physical_path_to_your_custom_404_page_relative_to_the_web.config_file/404.html" responseMode="Redirect" />
            <error statusCode="403" subStatusCode="14" path="/physical_path_to_your_custom_404_page_relative_to_the_web.config_file/404.html" responseMode="Redirect" />
        </httpErrors>
    </system.webServer>
</configuration>

With that, both the real 404 errors and 403.14 (.14 is the specific code for reaching a real path but with browsing denied) errors will redirect to a 404 error page. There will be no 403 to be seen, so for the end user both are 404 errors.

edit: you may need to install the "http errors" feature for this to work.


问:
IndexError in Django. List out of range
I have a program that takes in input from user then splits the values and converts it into a list.

```<code>num_of_subjects = 5 #input by user
subjects = ['eng', 'maths', 'sci', 'his'] #wrong input by user
</code>```

expecting

```<code>subjects = ['eng', 'maths', 'sci', 'his', 'phy'] #because num_of_subjects is 5
</code>```

views.py

```<code>def schoolinput_view(request):
    if request.method == 'POST':
    subjects_view = request.POST.get('subjects')

   for i in range(num_of_subjects):
       sub = subjects_view[i]
       print(sub)
</code>```

This gives an list out of range error as expected so I tried

```<code>try:
    def schoolinput_view(request):
        if request.method == 'POST':
        subjects_view = request.POST.get('subjects')

    for i in range(num_of_subjects):
       sub = subjects_view[i]
       print(sub)
except IndexError as listerror:
    print('Please check if subjects meet number of subjects')
</code>```

And this didn't solve the problem and still gives IndexError even if the exception is handled.

答:
What you could do instead is before continuing to the next process, to verify that the number of subjects they entered matches.

```<code>if num_of_subjects == len(subjects):
    for i in range(num_of_subjects):
        sub = subjects_view[i]
        print(sub)
else:
    print('Please check if subjects meet number of subjects')
</code>```

You can also shorten

```<code>for i in range(num_of_subjects):
    sub = subjects_view[i]
    print(sub)
</code>```

to

```<code>for subject in subjects:
    print(subject)
</code>```

Title: IndexError in Django. List out of range

Body:
I have a program that takes in input from user then splits the values and converts it into a list.

num_of_subjects = 5 #input by user
subjects = ['eng', 'maths', 'sci', 'his'] #wrong input by user

expecting

subjects = ['eng', 'maths', 'sci', 'his', 'phy'] #because num_of_subjects is 5

views.py

def schoolinput_view(request):
    if request.method == 'POST':
    subjects_view = request.POST.get('subjects')

   for i in range(num_of_subjects):
       sub = subjects_view[i]
       print(sub)

This gives an list out of range error as expected so I tried

try:
    def schoolinput_view(request):
        if request.method == 'POST':
        subjects_view = request.POST.get('subjects')

    for i in range(num_of_subjects):
       sub = subjects_view[i]
       print(sub)
except IndexError as listerror:
    print('Please check if subjects meet number of subjects')

And this didn't solve the problem and still gives IndexError even if the exception is handled.

Body:
What you could do instead is before continuing to the next process, to verify that the number of subjects they entered matches.

if num_of_subjects == len(subjects):
    for i in range(num_of_subjects):
        sub = subjects_view[i]
        print(sub)
else:
    print('Please check if subjects meet number of subjects')

You can also shorten

for i in range(num_of_subjects):
    sub = subjects_view[i]
    print(sub)

to

for subject in subjects:
    print(subject)


问:
How to create Karaf shell command in Gradle project
I'm trying to create own Karaf shell command and I'm willing to do this using Gradle because entire project is on Gradle.

The only relevant documentation I've found so far is here
http://karaf.apache.org/manual/latest/#_shell_commands
and it says

```<code>See [examples/karaf-command-example] to add your own shell commands.
</code>```

Examples are created using MAVEN and there is absolutely no description about what magic is happening there and what should appear in resulting bundle so that I could reproduce it in Gradle.

Can someone tell how to achieve the same in Gradle project?

How Karaf identifies which commands are present in Bundle?

答:
Over time I did not find how to make that same thing in gradle, but I came across the solution which gives same result - using OSGI Declarative Services.

More details here (look for osgi.command.scope):

http://blog.vogella.com/2016/09/26/configuring-osgi-declarative-services/

Here is sample code, which allows running command some:command with one optional string parameter.

```<code>package some.application;

import org.osgi.service.component.annotations.Component;

@Component(
    service=SomeCommand.class,
    property = {"osgi.command.scope=some", "osgi.command.function=command"}
)
public class SomeCommand {

    public void command() {
        System.out.println("SomeCommand: " + "<no args>");
    }

    public void command(String param) {
        System.out.println("SomeCommand: " + param);
    }
}
</code>```

Body:
I'm trying to create own Karaf shell command and I'm willing to do this using Gradle because entire project is on Gradle.

The only relevant documentation I've found so far is here
http://karaf.apache.org/manual/latest/#_shell_commands
and it says

See [examples/karaf-command-example] to add your own shell commands.

Examples are created using MAVEN and there is absolutely no description about what magic is happening there and what should appear in resulting bundle so that I could reproduce it in Gradle.

Can someone tell how to achieve the same in Gradle project?

How Karaf identifies which commands are present in Bundle?

Body:
Over time I did not find how to make that same thing in gradle, but I came across the solution which gives same result - using OSGI Declarative Services.

More details here (look for osgi.command.scope):

http://blog.vogella.com/2016/09/26/configuring-osgi-declarative-services/

Here is sample code, which allows running command some:command with one optional string parameter.

package some.application;

import org.osgi.service.component.annotations.Component;

@Component(
    service=SomeCommand.class,
    property = {"osgi.command.scope=some", "osgi.command.function=command"}
)
public class SomeCommand {

    public void command() {
        System.out.println("SomeCommand: " + "<no args>");
    }

    public void command(String param) {
        System.out.println("SomeCommand: " + param);
    }
}


问:
How should you calculate partial derivative ∂f/∂x using first the chain rule & directly in MAPLE?
If f(u,v) = vsinu+v^2, u(x,y)=tan^−1(y/x), v=sqrt(x^2 + y^2)

Calculate using chain rule and directly substituting for u(x,y), v(x,y).

答:
Your syntax is not altogether clear to me, but I am guessing you are trying to achieve something like this:

```<code>uveqs := [u(x,y)=arctan(y/x), v(x,y)=sqrt(x^2+y^2)]:
f := v(x,y)*sin(u(x,y))+v(x,y)^2:
</code>```

Differentiate f with respect to x (noticing the effect of the chain-rule),

```<code>K := diff(f,x):

      diff(v(x,y),x) * sin(u(x,y))
      + v(x,y) * diff(u(x,y),x) * cos(u(x,y))
      + 2*v(x,y) * diff(v(x,y),x)
</code>```

Now substitute for u(x,y) and v(x,u), and simplify,

```<code>S1 := eval(K,uveqs):
simplify(S1);

                 2 x
</code>```

Alternatively, first substitute for u(x,y) and v(x,y) into f itself,

```<code>fxy := eval(f,uveqs):

    (x^2+y^2)^(1/2)*y/x/(1+y^2/x^2)^(1/2)+x^2+y^2
</code>```

And then differentiate with respect to x, and simplify,

```<code>S2 := diff(fxy,x):
simplify(S2);

                 2 x
</code>```

If you have trouble understanding the mechanisms, you might also compare these two pairs of operations,

```<code>diff( v(x,y), x );
eval( %, uveqs );
</code>```

and,

```<code>eval( v(x,y), uveqs );
diff( %, x );
</code>```

Body:
Your syntax is not altogether clear to me, but I am guessing you are trying to achieve something like this:

uveqs := [u(x,y)=arctan(y/x), v(x,y)=sqrt(x^2+y^2)]:
f := v(x,y)*sin(u(x,y))+v(x,y)^2:

Differentiate f with respect to x (noticing the effect of the chain-rule),

K := diff(f,x):

      diff(v(x,y),x) * sin(u(x,y))
      + v(x,y) * diff(u(x,y),x) * cos(u(x,y))
      + 2*v(x,y) * diff(v(x,y),x)

Now substitute for u(x,y) and v(x,u), and simplify,

S1 := eval(K,uveqs):
simplify(S1);

                 2 x

Alternatively, first substitute for u(x,y) and v(x,y) into f itself,

fxy := eval(f,uveqs):

    (x^2+y^2)^(1/2)*y/x/(1+y^2/x^2)^(1/2)+x^2+y^2

And then differentiate with respect to x, and simplify,

S2 := diff(fxy,x):
simplify(S2);

                 2 x

If you have trouble understanding the mechanisms, you might also compare these two pairs of operations,

diff( v(x,y), x );
eval( %, uveqs );

and,

eval( v(x,y), uveqs );
diff( %, x );


问:
How to add an onClick function to a dynamically-filled div?
I have bootstrap navbar with dropdown:

```<code><ul class="navbar-nav mr-auto">
  <li class="nav-item dropdown">
   <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria haspopup="true" aria-expanded="false">GANRES</a>
   <div class="dropdown-menu"></div>
  </li>
</ul>
</code>```

And I have function that fills them with genres with the TMDb API:

```<code>async function getGenres() {
    let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
    let response = await fetch(url);
    let genres = await response.json();
    let navbar = document.getElementsByClassName("nav-item dropdown");
    navbar.innerHTML += `<div class="dropdown-menu">`;
    let nav = document.getElementsByClassName("dropdown-menu");
    for (let i = 0; i < genres.genres.length; i++) {
        nav[0].innerHTML += `<a class="dropdown-item" href="#">` + genres.genres[i].name + `</a>`;
    }

//This part should add separately to each element, but it does not work
//Here is error: Cannot set property 'click' of undefined at getGenres

    for (let i = 0; i < genres.genres.length; i++) {
    document.getElementsByClassName("dropdown-menu")[i].click = function () {
        getmovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
    };
};
}
</code>```

The items themselves are created normally.GenresThe onClick function just doesn't work.

I tried to load this function as onload in body, but it didn't work

答:
I removed the API calls to focus on the code that was causing the issues:</p>

```<code>async function getGenres() {
  const genres = {
    genres: [{ name: "pop" }, { name: "punk" }]
  };

  const navbar = document.getElementsByClassName("nav-item dropdown");
  console.log("navbar", navbar);

  let nav = document.createElement("div");
  nav.className = "dropdown-menu";

  for (let i = 0; i < genres.genres.length; i++) {
    let a_tag = document.createElement("a");
    let link = document.createTextNode(genres.genres[i].name);
    a_tag.appendChild(link);
    a_tag.className = "dropdown-item";
    a_tag.href = "#";
    nav.appendChild(a_tag);
  }
  navbar[0].appendChild(nav);

  //This part should add separately to each element, but it does not work
  //Here is error: Cannot set property 'click' of undefined at getGenres

  const items = document.getElementsByClassName("dropdown-item");
  for (let i = 0; i < genres.genres.length; i++) {
    items[i].addEventListener("click", () => {
      alert("get movies here for name" + genres.genres[i].name);

    });
  }
}

</code>```

Body:
I have bootstrap navbar with dropdown:

   GANRES

And I have function that fills them with genres with the TMDb API:

async function getGenres() {
    let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
    let response = await fetch(url);
    let genres = await response.json();
    let navbar = document.getElementsByClassName("nav-item dropdown");
    navbar.innerHTML += `<div class="dropdown-menu">`;
    let nav = document.getElementsByClassName("dropdown-menu");
    for (let i = 0; i < genres.genres.length; i++) {
        nav[0].innerHTML += `<a class="dropdown-item" href="#">` + genres.genres[i].name + `</a>`;
    }

//This part should add separately to each element, but it does not work
//Here is error: Cannot set property 'click' of undefined at getGenres

    for (let i = 0; i < genres.genres.length; i++) {
    document.getElementsByClassName("dropdown-menu")[i].click = function () {
        getmovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
    };
};
}

The items themselves are created normally.GenresThe onClick function just doesn't work.

I tried to load this function as onload in body, but it didn't work

Body:
I removed the API calls to focus on the code that was causing the issues:

async function getGenres() {
  const genres = {
    genres: [{ name: "pop" }, { name: "punk" }]
  };

  const navbar = document.getElementsByClassName("nav-item dropdown");
  console.log("navbar", navbar);

  let nav = document.createElement("div");
  nav.className = "dropdown-menu";

  for (let i = 0; i < genres.genres.length; i++) {
    let a_tag = document.createElement("a");
    let link = document.createTextNode(genres.genres[i].name);
    a_tag.appendChild(link);
    a_tag.className = "dropdown-item";
    a_tag.href = "#";
    nav.appendChild(a_tag);
  }
  navbar[0].appendChild(nav);

  //This part should add separately to each element, but it does not work
  //Here is error: Cannot set property 'click' of undefined at getGenres

  const items = document.getElementsByClassName("dropdown-item");
  for (let i = 0; i < genres.genres.length; i++) {
    items[i].addEventListener("click", () => {
      alert("get movies here for name" + genres.genres[i].name);

    });
  }
}


问:
hashmap or hashset?
I have two list containing

```<code>List<MyObj>.
</code>```

and MyObj has a "String ID" member.

I need to iterate them from time to time and sometimes I need to find objects which are similar on both.

I want a quicker way than lists.  so I can know I can use  hashMap
(than ask contains (String ) when comparing )

should I use hashmap or hashset?

note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where  upon inserting I put the string id in the key.
Am I correct?

答:
This does not really make a difference at all, because when you look at the JDK source code, the Sun implementation of HashSet uses an instance of HashMap internally to store its values:

```<code>   public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
......
</code>```

And even if that was not the case, all other answers about that it does not really make a difference from a performance POV apply. The only real difference is that instead of using the equals() and hashCode() implementations of your key class you need to write your own for using the Set - but those could be as simple as delegating to the id field of your class, in case that the id field is the unique identifier.

Title: hashmap or hashset?

Body:
I have two list containing

List<MyObj>.

and MyObj has a "String ID" member.

I need to iterate them from time to time and sometimes I need to find objects which are similar on both.

I want a quicker way than lists.  so I can know I can use  hashMap
(than ask contains (String ) when comparing )

should I use hashmap or hashset?

note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where  upon inserting I put the string id in the key.
Am I correct?

Body:
This does not really make a difference at all, because when you look at the JDK source code, the Sun implementation of HashSet uses an instance of HashMap internally to store its values:

   public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
......

And even if that was not the case, all other answers about that it does not really make a difference from a performance POV apply. The only real difference is that instead of using the equals() and hashCode() implementations of your key class you need to write your own for using the Set - but those could be as simple as delegating to the id field of your class, in case that the id field is the unique identifier.


问:
Check if a control is loaded in Silverlight
I'm trying to write an extension method that will allow me to set focus on a Control.  I've written the method below which works fine, however if the control is already loaded then obviously hooking up the Loaded event isn't going to be any use - I also need a way to check if the control has been loaded so I can simply run the Focus() code without hooking up the event.

Is there any way to simulate an IsLoaded property on a control?

```<code>public static void SetFocus(this Control control)
{
    // return if the control is not visible
    if (control.Visibility == Visibility.Collapsed) { return; }

    control.Loaded += (sender, routedeventArgs) =>
        {
            // focus the Silverlight plugin first
            System.Windows.Browser.HtmlPage.Plugin.Focus();

            control.IsTabStop = true; // required to allow Focus
            control.Focus();

            if (control is TextBox)
            {
                ((TextBox)control).SelectAll();
            }
        };
}
</code>```

EDIT: As per ColinE's answer below, I implemented it like this:

```<code>public static void SetFocus(this Control control)
{
    // return if the control is not visible
    if (control.Visibility == Visibility.Collapsed) { return; }

    if (control.Descendants().Count() > 0)
    {
        // already loaded, just set focus and return
        SetFocusDelegate(control);
        return;
    }

    // not loaded, wait for load before setting focus
    control.Loaded += (sender, routedeventArgs) =>
    {
        SetFocusDelegate(control);
    };
}

public static void SetFocusDelegate(Control control)
{
    // focus the Silverlight plugin first
    System.Windows.Browser.HtmlPage.Plugin.Focus();

    control.IsTabStop = true; // required to allow Focus
    control.Focus();

    if (control is TextBox)
    {
        ((TextBox)control).SelectAll();
    }
}
</code>```

答:
If a control has not been loaded, then the various elements within its template will not have been constructed. Using Linq-to-VisualTree you can confirm this:

```<code>Debug.WriteLine(control.Descendants().Count());

control.Loaded += (s, e) =>
  {
    Debug.WriteLine(foo.Descendants().Count());
  };
</code>```

The first debug output should show '0', the second will be a number >0 which indicates the number of child elements of the control once the template has been applied.

Body:
I'm trying to write an extension method that will allow me to set focus on a Control.  I've written the method below which works fine, however if the control is already loaded then obviously hooking up the Loaded event isn't going to be any use - I also need a way to check if the control has been loaded so I can simply run the Focus() code without hooking up the event.

Is there any way to simulate an IsLoaded property on a control?

public static void SetFocus(this Control control)
{
    // return if the control is not visible
    if (control.Visibility == Visibility.Collapsed) { return; }

    control.Loaded += (sender, routedeventArgs) =>
        {
            // focus the Silverlight plugin first
            System.Windows.Browser.HtmlPage.Plugin.Focus();

            control.IsTabStop = true; // required to allow Focus
            control.Focus();

            if (control is TextBox)
            {
                ((TextBox)control).SelectAll();
            }
        };
}

EDIT: As per ColinE's answer below, I implemented it like this:

public static void SetFocus(this Control control)
{
    // return if the control is not visible
    if (control.Visibility == Visibility.Collapsed) { return; }

    if (control.Descendants().Count() > 0)
    {
        // already loaded, just set focus and return
        SetFocusDelegate(control);
        return;
    }

    // not loaded, wait for load before setting focus
    control.Loaded += (sender, routedeventArgs) =>
    {
        SetFocusDelegate(control);
    };
}

public static void SetFocusDelegate(Control control)
{
    // focus the Silverlight plugin first
    System.Windows.Browser.HtmlPage.Plugin.Focus();

    control.IsTabStop = true; // required to allow Focus
    control.Focus();

    if (control is TextBox)
    {
        ((TextBox)control).SelectAll();
    }
}

Body:
If a control has not been loaded, then the various elements within its template will not have been constructed. Using Linq-to-VisualTree you can confirm this:

Debug.WriteLine(control.Descendants().Count());

control.Loaded += (s, e) =>
  {
    Debug.WriteLine(foo.Descendants().Count());
  };

The first debug output should show '0', the second will be a number >0 which indicates the number of child elements of the control once the template has been applied.


问:
Intermittent "index = -1" when getting rows from DataGridView
When doing this:

```<code>        foreach (DataGridView currentGridView in tabControl.SelectedTab.Controls.OfType<DataGridView>())
        {

            rows = new DataGridViewRow[currentGridView.RowCount];
            currentGridView.Rows.CopyTo(rows, 0);
            page = 0;

            printDocDetail.DocumentName = "Contact List Detailed";
            printDocDetail.Print();

        }
</code>```

I often get this result:

And that depends on the run. For the same DataGridView data, one run will return the data correctly, the next will return all index=-1 except for the first one.

What is causing this?

P.S. Using DataGridViewRowCollection or a simple array results to the same thing.

答:
Go to TableAdapter. Next click on little arrow to edit query. Click on ID and under ID properties change AutoIncrementSeed from -1 change to 1 and AutoIncrementStep from -1 to 1. Will fix the problem

TableAdapter:

ID:

ID Properties:

Form:

Body:
When doing this:

        foreach (DataGridView currentGridView in tabControl.SelectedTab.Controls.OfType<DataGridView>())
        {

            rows = new DataGridViewRow[currentGridView.RowCount];
            currentGridView.Rows.CopyTo(rows, 0);
            page = 0;

            printDocDetail.DocumentName = "Contact List Detailed";
            printDocDetail.Print();

        }

I often get this result:

And that depends on the run. For the same DataGridView data, one run will return the data correctly, the next will return all index=-1 except for the first one.

What is causing this?

P.S. Using DataGridViewRowCollection or a simple array results to the same thing.


问:
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

答:
Replication

```<code>Create Table [DateTest] (
    [date] date NOT NULL
)

insert into [dateTest] ([date])
values
('2017-04-01'),
('2017-07-01'),
('2018-08-14'),
('2018-08-14'),
('2019-03-30'),
('2019-03-30'),
('2019-06-30'),
('2019-06-30'),
('9999-12-31'),
('9999-12-31')

SELECT DATEDIFF(day, '9990-12-31', dt.[Date]) AS "DIFF"
,dt.[Date] as [DT]
FROM [dateTest] as DT
</code>```

Diagnostic

When replication your statement (quoted), I ran the following:

"But when I add the where statement in:"

```<code>SELECT DATEDIFF(day, '9990-12-31', dt.[Date]) AS "DIFF"
,dt.[Date] as [DT]
FROM [dateTest] as DT
WHERE DATEDIFF(day, '9990-12-31', dt.[Date]) >= 0
</code>```

I retrieved the expected return:

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

The syntax for your SQL is correct, however there is possibly a datatype issue. Can you provide more information on the tables for querying?

Request for further information

A simple case for the table definitions would be ideal, or just a simple row example of the 2 tables you want to join and the datatypes.

Its hard to replicate your question without knowing the exact definition of your access file. There are too many tables in the referenced script to isolate without a direct clone. By creating a simplified example, you may be able to resolve your issue.

Recommendation

If this is a one time conversion from an Access based database, you can look at SSMS (Sql Server Management Studio) to use a direct import for access databases.

If you're looking for a way to schedule retrieval from a known Access file, what is the business requirement of using the Access file as opposed to a direct write to a SQL database? There may be a simpler solution to your issue.

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:
Replication

Create Table [DateTest] (
    [date] date NOT NULL
)

insert into [dateTest] ([date])
values
('2017-04-01'),
('2017-07-01'),
('2018-08-14'),
('2018-08-14'),
('2019-03-30'),
('2019-03-30'),
('2019-06-30'),
('2019-06-30'),
('9999-12-31'),
('9999-12-31')

SELECT DATEDIFF(day, '9990-12-31', dt.[Date]) AS "DIFF"
,dt.[Date] as [DT]
FROM [dateTest] as DT

Diagnostic

When replication your statement (quoted), I ran the following:

"But when I add the where statement in:"

SELECT DATEDIFF(day, '9990-12-31', dt.[Date]) AS "DIFF"
,dt.[Date] as [DT]
FROM [dateTest] as DT
WHERE DATEDIFF(day, '9990-12-31', dt.[Date]) >= 0

I retrieved the expected return:

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

The syntax for your SQL is correct, however there is possibly a datatype issue. Can you provide more information on the tables for querying?

Request for further information

A simple case for the table definitions would be ideal, or just a simple row example of the 2 tables you want to join and the datatypes.

Its hard to replicate your question without knowing the exact definition of your access file. There are too many tables in the referenced script to isolate without a direct clone. By creating a simplified example, you may be able to resolve your issue.

Recommendation

If this is a one time conversion from an Access based database, you can look at SSMS (Sql Server Management Studio) to use a direct import for access databases.

If you're looking for a way to schedule retrieval from a known Access file, what is the business requirement of using the Access file as opposed to a direct write to a SQL database? There may be a simpler solution to your issue.


问:
Is it possible to change the direction vertical slider in swiper slider? I want to have both top to bottom and bottom to top option?
I'm working on a page that contains two vertical sliders. But on clicking down arrow button or on mouse scroll, I want one to slide up words (bottom to top) and the other downwards (top to bottom). How can I implement this?

My code basically looks something like this:

```<code><div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide">
          <div class="swiper-container swiper-container-v swiper-left">
            <div class="swiper-pagination swiper-pagination-v"></div>
            <div class="swiper-wrapper">
              <div class="swiper-slide">Vertical Slide 1</div>
              <div class="swiper-slide">Vertical Slide 2</div>
              <div class="swiper-slide">Vertical Slide 3</div>
              <div class="swiper-slide">Vertical Slide 4</div>
              <div class="swiper-slide">Vertical Slide 5</div>
            </div>
          </div>
        <div class="swiper-container swiper-container-v2 swiper-right">
            <div class="swiper-wrapper">
              <div class="swiper-slide">Vertical Slide 1</div>
              <div class="swiper-slide">Vertical Slide 2</div>
              <div class="swiper-slide">Vertical Slide 3</div>
              <div class="swiper-slide">Vertical Slide 4</div>
              <div class="swiper-slide">Vertical Slide 5</div>
            </div>
          </div>
      </div>
    </div>
    <!-- Add Pagination -->
    <div class="swiper-pagination"></div>
 </div>
</code>```

Script like this:

```<code>var swiper = new Swiper('.swiper-container', {
      direction: 'vertical',

    });
    var swiperV = new Swiper('.swiper-container-v', {
      direction: 'vertical',
      spaceBetween: 50,
      keyboard: {
        enabled: true,
      },
      pagination: {
        el: '.swiper-pagination-v',
        clickable: true,
      },
      loop: true,
    });
    var swiperV2 = new Swiper('.swiper-container-v2', {
      direction: 'vertical',
      spaceBetween: 50,
      keyboard: {
        enabled: true,
      },
      pagination: {
        el: '.swiper-pagination-v',
        clickable: true,
      },
      loop: true,
      reverseDirection: true
    });

</code>```

答:
If you are using this swiper there is the navigation object you need to add to your configuration.

Something like in the example the guys that are developing the Swiper are reporting in their API:

```<code>var mySwiper = new Swiper('.swiper-container', {
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
    }
});
</code>```

If you want to invert the standard swiping (direction of swipe) you just need to swap the classes that reference your arrows in the configuration.

```<code>var mySwiper = new Swiper('.swiper-container', {
    navigation: {
        nextEl: '.swiper-button-prev',
        prevEl: '.swiper-button-next'
    }
});
</code>```

Body:
I'm working on a page that contains two vertical sliders. But on clicking down arrow button or on mouse scroll, I want one to slide up words (bottom to top) and the other downwards (top to bottom). How can I implement this?

My code basically looks something like this:

Vertical Slide 1

Vertical Slide 2

Vertical Slide 3

Vertical Slide 4

Vertical Slide 5

Vertical Slide 1

Vertical Slide 2

Vertical Slide 3

Vertical Slide 4

Vertical Slide 5

Script like this:

var swiper = new Swiper('.swiper-container', {
      direction: 'vertical',

    });
    var swiperV = new Swiper('.swiper-container-v', {
      direction: 'vertical',
      spaceBetween: 50,
      keyboard: {
        enabled: true,
      },
      pagination: {
        el: '.swiper-pagination-v',
        clickable: true,
      },
      loop: true,
    });
    var swiperV2 = new Swiper('.swiper-container-v2', {
      direction: 'vertical',
      spaceBetween: 50,
      keyboard: {
        enabled: true,
      },
      pagination: {
        el: '.swiper-pagination-v',
        clickable: true,
      },
      loop: true,
      reverseDirection: true
    });

Body:
If you are using this swiper there is the navigation object you need to add to your configuration.

Something like in the example the guys that are developing the Swiper are reporting in their API:

var mySwiper = new Swiper('.swiper-container', {
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
    }
});

If you want to invert the standard swiping (direction of swipe) you just need to swap the classes that reference your arrows in the configuration.

var mySwiper = new Swiper('.swiper-container', {
    navigation: {
        nextEl: '.swiper-button-prev',
        prevEl: '.swiper-button-next'
    }
});


答:
You can use aggregation in one fell swoop:

```<code>select (case when user_id = 1 then id end) as my_user_or_not,
       sum(amount_1), sum(amount_2), sum(amount_3)
from t
group by my_user_or_not;
</code>```

The null values in the first column indicate another user.  You have labelled the column id, which is a bit problematic if you were -- for instance -- to choose user_id = 2 in your example.  NULL seems safer for this purpose.

Title: SQL query to return combined data of all rows that don't belong to current user

Body:
Imagine this is my table:

----------------------------------------------------
| id | user_id    | amount_1 | amount_2 | amount_3 |
----------------------------------------------------
| 1  | 1          | 2        | 3        | 4        |
----------------------------------------------------
| 2  | 2          | 2        | 1        | 1        |
----------------------------------------------------
| 3  | 2          | 1        | 2        | 2        |
----------------------------------------------------
| 4  | 3          | 2        | 1        | 4        |
----------------------------------------------------

I need a query that gives me one result set for every entry that belongs to my current user, and then returns everything else as a single combined row with the amounts summed.

So in this case if I am user 1, I should get the following rows back:

---------------------------------------
| id | amount_1 | amount_2 | amount_3 |
---------------------------------------
| 1  | 2        | 3        | 4        |   my own amounts
---------------------------------------
| 2  | 5        | 4        | 7        |   everyone else's amounts
---------------------------------------

Any tips?

I've considered it might be a better idea to just filter the data in the code (php). Please help i'm starting to hate myself

Body:
You can use aggregation in one fell swoop:

select (case when user_id = 1 then id end) as my_user_or_not,
       sum(amount_1), sum(amount_2), sum(amount_3)
from t
group by my_user_or_not;

The null values in the first column indicate another user.  You have labelled the column id, which is a bit problematic if you were -- for instance -- to choose user_id = 2 in your example.  NULL seems safer for this purpose.


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答: Eric Lippert has a good article on this. In case you can't be bothered to read the entire article, the answer is: return the interface.</p>

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ShuggyCoUk


问:
How can I handle the Return key in a CEdit control?
How can I handle the Return key (VK_RETURN) in a CEdit control? The CEdit control is parented to a CDialog.

答:
The correct answer is to handle the WM_GETDLGCODE / OnGetDlgCode message. In there you can specify that you want all keys to be handled by your class.</p>

```<code>UINT CMyEdit::OnGetDlgCode()
{
    return CEdit::OnGetDlgCode() | DLGC_WANTALLKEYS;
}
</code>```

OwnerDisplayName: knaser

Body:
The correct answer is to handle the WM_GETDLGCODE / OnGetDlgCode message. In there you can specify that you want all keys to be handled by your class.

UINT CMyEdit::OnGetDlgCode()
{
    return CEdit::OnGetDlgCode() | DLGC_WANTALLKEYS;
}