问:
Make dynamic fontsize using javascript to fit into a button
I have a button of fixed size and various chunks of text. The length of the texts is different. How can I make the size of the text font change dynamically according to its length in order to fit the button boundaries properly? Thank you.</p>

答:
Well, depends. Is the height fix as well? If both height and width are fixed, you will have to calculate the fontsize via javascript.

In most of the cases two or three if conditions should be absolutely sufficient for the specific usecase.

function font_size_adjust () {

  // Grab the string
  var string = $('#button_text').text()

  // Get the length in characters of the string
  var string_size = string.length

  // Build variable to change attribute
  var font_size = 0

  // Define logic for resizing, adapt this to your personal needs
  if (string_size < 60) {
     fontsize = '2vw';
  } else if (string_size > 60) {
    fontsize = '4vw';
  } else {}

  // Change fontsize
  $('#button_text').css('font-size', fontsize)

}

// Call the function where- and whenever needed:
font_size_adjust();

// Example stuff
$('#toggle_small').click(function () {
  $('#button_text').text('Now I am small again!')
  font_size_adjust();
})

$('#toggle_big').click(function () {
  $('#button_text').text('Now I am large again! Lets get this rollin! rollin! rollin! rollin!')
  font_size_adjust();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ctn {
  display: flex;
  float: left;
}

#button {
  width: 45vw;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
  font-family: Varela Round;
  color: #FFF;
    background: linear-gradient(126deg, rgba(143,61,217,1) 12%, rgba(109,35,177,1) 43%, rgba(101,34,162,1) 72%);
}

#ctn_toggle {
  display: flex;
  float: left;
}

.toggle {
  background-color: lightblue;
  font-size: 3vw;
  padding: 10px;
  border-radius: 25px;
  width: 11vw;
  text-align: center;
  margin-right: 2vw;
  font-family: Varela Round;
}</code>```

<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">

Make me small and big all day long this is so exciting! Let's go broooh!

Click me to shrink!

Click me to expand!

```
</div>
</div>
</p>

<p>Otherwise, these are the options... :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ctn {
  display: flex;
  float: left;
}

#button {
  width: 20vw;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
}

#button_text {
  font-size: 4vw;
}

#button2 {
  width: 20vw;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
}

#button_text2 {

}

#button3 {
  width: 20vw;
  height: 10vh;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
}

#button_text3 {
  font-size: 4vw;
}

#button4 {
  width: 20vw;
  height: 10vh;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
}

#button_text4 {

}</code>```

Fix button width and fix font-size

Fix button width and no specific font-size

Fix button width, fix button height and fix font-size

Fix button width, fix button height and no font-size

```

Body:
Well, depends. Is the height fix as well? If both height and width are fixed, you will have to calculate the fontsize via javascript.

In most of the cases two or three if conditions should be absolutely sufficient for the specific usecase.

function font_size_adjust () {

  // Grab the string
  var string = $('#button_text').text()

  // Get the length in characters of the string
  var string_size = string.length

  // Build variable to change attribute
  var font_size = 0

  // Define logic for resizing, adapt this to your personal needs
  if (string_size < 60) {
     fontsize = '2vw';
  } else if (string_size > 60) {
    fontsize = '4vw';
  } else {}

  // Change fontsize
  $('#button_text').css('font-size', fontsize)

}

// Call the function where- and whenever needed:
font_size_adjust();

// Example stuff
$('#toggle_small').click(function () {
  $('#button_text').text('Now I am small again!')
  font_size_adjust();
})

$('#toggle_big').click(function () {
  $('#button_text').text('Now I am large again! Lets get this rollin! rollin! rollin! rollin!')
  font_size_adjust();
})

#ctn {
  display: flex;
  float: left;
}

#button {
  width: 45vw;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
  font-family: Varela Round;
  color: #FFF;
    background: linear-gradient(126deg, rgba(143,61,217,1) 12%, rgba(109,35,177,1) 43%, rgba(101,34,162,1) 72%);
}

#ctn_toggle {
  display: flex;
  float: left;
}

.toggle {
  background-color: lightblue;
  font-size: 3vw;
  padding: 10px;
  border-radius: 25px;
  width: 11vw;
  text-align: center;
  margin-right: 2vw;
  font-family: Varela Round;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">
<html>
  <body>

  <div id="ctn">

    <div id="button">
      <p id="button_text">Make me small and big all day long this is so exciting! Let's go broooh!</p>
    </div>

  </div>

    <div id="ctn_toggle">

      <div id="toggle_small" class="toggle">
        <p id="button_small">Click me to shrink!</p>
      </div>

      <div id="toggle_big" class="toggle">
        <p id="button_big">Click me to expand!</p>
      </div>

  </div>

  </body>
</html>

Otherwise, these are the options... :

#ctn {
  display: flex;
  float: left;
}

#button {
  width: 20vw;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
}

#button_text {
  font-size: 4vw;
}

#button2 {
  width: 20vw;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
}

#button_text2 {

}

#button3 {
  width: 20vw;
  height: 10vh;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
  margin-right: 1vw;
}

#button_text3 {
  font-size: 4vw;
}

#button4 {
  width: 20vw;
  height: 10vh;
  background-color: lightblue;
  padding: 10px;
  border-radius: 25px;
}

#button_text4 {

}

<html>
  <body>

  <div id="ctn">

    <div id="button">
      <p id="button_text">Fix button width and fix font-size</p>
    </div>

    <div id="button2">
      <p id="button_text2">Fix button width and no specific font-size</p>
    </div>

    <div id="button3">
      <p id="button_text3">Fix button width, fix button height and fix font-size</p>
    </div>

    <div id="button4">
      <p id="button_text4">Fix button width, fix button height and no font-size</p>
    </div>

  </div>

  </body>
</html>


来源: stackexchange

问:
df.loc using index in slicer return nan
I am trying to iterate over a dateFrame and get the max of column between certain rows, the problem is when I am putting the index value over a number I get nan:

```<code>for index, row in df.iterrows():
        if index >= 51:
            print(df.loc[index:(index - 51), 'close'].max())
</code>```

for this, I get a nan value.

but if I use numbers in the slicer like this:

```<code>for index, row in df.iterrows():
        if index >= 51:
            print(df.loc[0:51, 'close'].max())
</code>```

I will get the result not the one I need because I need it to be a moving window but this is just to show the problem.

any ideas why it won't accept the index as a valid slicer?

答:
I think the issue is you have the loc index slice backwards, causing nothing to be returned; on the first iteration, your slice is df.loc[51:0, 'close'].max().  Instead:

```<code>for index, row in df.iterrows():
    if index >= 51:
        print(df.loc[index-51:index,'close'].max())

#first iteration: df.loc[0:51,'close']
</code>```

I'm assuming your index are integers/numbers, hence why you can mix integers and column names using loc?  Otherwise I think iloc could work.

Amendment: this is what I was thinking by using iloc, but it is (in my eyes) no different than your method:

```<code>close_iloc = df.columns.get_loc('close') #gets the integer number needed for iloc to reference 'close'
for i in range(len(df.index)):
    if i >= 51:
        print(df.iloc[i-51:i,close_iloc].max())
</code>```

ContentLicense: CC BY-SA 4.0

Title: df.loc using index in slicer return nan

Body:
I am trying to iterate over a dateFrame and get the max of column between certain rows, the problem is when I am putting the index value over a number I get nan:

for index, row in df.iterrows():
        if index >= 51:
            print(df.loc[index:(index - 51), 'close'].max())

for this, I get a nan value.

but if I use numbers in the slicer like this:

for index, row in df.iterrows():
        if index >= 51:
            print(df.loc[0:51, 'close'].max())

I will get the result not the one I need because I need it to be a moving window but this is just to show the problem.

any ideas why it won't accept the index as a valid slicer?

Body:
I think the issue is you have the loc index slice backwards, causing nothing to be returned; on the first iteration, your slice is df.loc[51:0, 'close'].max().  Instead:

for index, row in df.iterrows():
    if index >= 51:
        print(df.loc[index-51:index,'close'].max())

#first iteration: df.loc[0:51,'close']

I'm assuming your index are integers/numbers, hence why you can mix integers and column names using loc?  Otherwise I think iloc could work.

Amendment: this is what I was thinking by using iloc, but it is (in my eyes) no different than your method:

close_iloc = df.columns.get_loc('close') #gets the integer number needed for iloc to reference 'close'
for i in range(len(df.index)):
    if i >= 51:
        print(df.iloc[i-51:i,close_iloc].max())


问:
How can I use MAX and LIMIT together in MySQL
I have a table with the following structure:

ID | Color

1 | red

2 | blue

3 | yellow

8 | purple

10| green

.

.

.

100|yellow

I would like to be able to grab the MAX ID value for the first 5 rows.

For example, I would like to do something like so:
Select MAX(ID) From Table LIMIT 5

Hoping this would return the value 10

But, MySQL keeps returning 100...its like MySQL does not even see the LIMIT clause.

答:
There is better way to do this than subselect:

```<code>SELECT id FROM table LIMIT 4,1
</code>```

Get one row but skip 4 first..
Add 'order by id' if this is MyISAM table.

OwnerDisplayName: Jerome

ContentLicense: CC BY-SA 2.5

Body:
There is better way to do this than subselect:

SELECT id FROM table LIMIT 4,1

Get one row but skip 4 first..
Add 'order by id' if this is MyISAM table.

ContentLicense: CC BY-SA 3.0


问:
How to trigger another button when I press enter key inside my form
I have a search bar where if I type anything it processes the answer or the output in another Modal. and then, if I click [search] button, then the modal triggers. Now I want that if I press enter inside the box, it will trigger the button.

```<code> <form class="form-inline" >
        <input class="form-control mr-sm-1" onkeyup="SearchFunction()" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">

        <a class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-
target="#resultsModal">Search</a>
      </form>
</code>```

I am very very weak at javascript. please give me suggestions on how can I  make it possible.

答:
Hi, you can do this by simple JavaScript Code:

Your HTML (some changes):

```<code><form class="form-inline" >
    <input class="form-control mr-sm-1" id="searchinputfeild" type="search" placeholder="" aria-label="Search">

    <button class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-target="#resultsModal">Search</button>
</form>
</code>```

Don't use  tag, instead use button.

Now Finally Place following JavaScript code below in your body (or anywhere):

```<code><script>
 var input = document.getElementById("searchinputfeild");
 input.addEventListener("keyup", function (event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   document.getElementById("searchbutton").click();
   }
 });
</script>
</code>```

YOU ARE DONE.

It Will work smoothly

If you wanna Test, Check it below by running alert test snippet:

var input = document.getElementById("searchinputfeild");
    input.addEventListener("keyup", function (event) {
     if (event.keyCode === 13) {
      event.preventDefault();
      document.getElementById("searchbutton").click();
      }
   });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form-inline" >
         <input class="form-control mr-sm-1" id="searchinputfeild" type="search" placeholder="" aria-label="Search">

        <button onclick="javascript:alert('Hey Congrats! I am working.')" class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-target="#resultsModal">Search</button>
</form></code>```

Body:
I have a search bar where if I type anything it processes the answer or the output in another Modal. and then, if I click [search] button, then the modal triggers. Now I want that if I press enter inside the box, it will trigger the button.

 <form class="form-inline" >
        <input class="form-control mr-sm-1" onkeyup="SearchFunction()" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">

        Search
      </form>

I am very very weak at javascript. please give me suggestions on how can I  make it possible.

Body:
Hi, you can do this by simple JavaScript Code:

Your HTML (some changes):

<form class="form-inline" >
    <input class="form-control mr-sm-1" id="searchinputfeild" type="search" placeholder="" aria-label="Search">

    <button class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-target="#resultsModal">Search</button>
</form>

Don't use < a > tag, instead use button.

Now Finally Place following JavaScript code below in your body (or anywhere):

<script>
 var input = document.getElementById("searchinputfeild");
 input.addEventListener("keyup", function (event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   document.getElementById("searchbutton").click();
   }
 });
</script>

YOU ARE DONE.

It Will work smoothly

If you wanna Test, Check it below by running alert test snippet:

var input = document.getElementById("searchinputfeild");
    input.addEventListener("keyup", function (event) {
     if (event.keyCode === 13) {
      event.preventDefault();
      document.getElementById("searchbutton").click();
      }
   });

<form class="form-inline" >
         <input class="form-control mr-sm-1" id="searchinputfeild" type="search" placeholder="" aria-label="Search">

        <button onclick="javascript:alert('Hey Congrats! I am working.')" class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-target="#resultsModal">Search</button>
</form>


问:
How can I import subpackage?
I have a file structure like this:

```<code>test.py
Dir1\
  __init__.py
  Something.py
  Dir2\
    __init__.py
    Something2.py
</code>```

```<code>#Dir1.__init__.py
from .Something import *
</code>```

Dir2.__init__.py have has the same code, but with .Something2

Something.py has simple add method, Something2.py has simple sub method.

What I need:

```<code>#test.py
import Dir1
print(Dir1.Dir2.sub(10, 14))
</code>```

But I get an error AttributeError: module 'Dir1' has no attribute 'Dir2'.

If I use from .Dir2 import * in Dir1.__init__.py code in test.py works, but also works print(Dir1.sub(10, 14)), what I don't want. I tryed many variants, but they brought me to error or Dir1.sub working.

This can probably be found on the Internet, but my knowledge of English is suffering and I may miss the answer. Of course I've already tried searching for it on the Internet.

I will be very grateful for your answer.

答:
Probably it is crutch, but I found solve. Now I have this file structure:

```<code>test.py
Dir1\
  __init__.py
  Dir1\
    __init__.py
    Something.py
    Dir2\
      __init__.py
      Something2.py
</code>```

#Dir1.__init__
import Dir1 as Add
from .Dir1 import Dir2 as Sub
```

<p>And now I can use </p>

<pre class="lang-py prettyprint-override"><code>#test.py
import Dir1
print(Dir1.Sub.sub(10, 7))
</code>```

And can't use

#test.py
import Dir1
print(Dir1.sub(10, 7))
```

Title: How can I import subpackage?

Body:
I have a file structure like this:

test.py
Dir1\
  __init__.py
  Something.py
  Dir2\
    __init__.py
    Something2.py

#Dir1.__init__.py
from .Something import *

Dir2.__init__.py have has the same code, but with .Something2

Something.py has simple add method, Something2.py has simple sub method.

What I need:

#test.py
import Dir1
print(Dir1.Dir2.sub(10, 14))

But I get an error AttributeError: module 'Dir1' has no attribute 'Dir2'.

If I use from .Dir2 import * in Dir1.__init__.py code in test.py works, but also works print(Dir1.sub(10, 14)), what I don't want. I tryed many variants, but they brought me to error or Dir1.sub working.

This can probably be found on the Internet, but my knowledge of English is suffering and I may miss the answer. Of course I've already tried searching for it on the Internet.

I will be very grateful for your answer.

Body:
Probably it is crutch, but I found solve. Now I have this file structure:

test.py
Dir1\
  __init__.py
  Dir1\
    __init__.py
    Something.py
    Dir2\
      __init__.py
      Something2.py

#Dir1.__init__
import Dir1 as Add
from .Dir1 import Dir2 as Sub

And now I can use

#test.py
import Dir1
print(Dir1.Sub.sub(10, 7))

And can't use

#test.py
import Dir1
print(Dir1.sub(10, 7))


问:
The program fails to proceed after a procedure in assembly 8086
Hi friends I can't go back after the "Upper" procedure to the next line I don't understand where ip has gone ...

```<code>.MODEL SMALL
.STACK  64
.DATA
input db 30,?,30 dup('$'),'$'
msg1 db "Please enter string to convert:", 0DH , '$'
msg2 db "Your converted input :", 0DH , '$'
TransFormsMan db 32 ; Going to use the dec value 32 to change my lowers chars..

.Code

Main proc
    mov ax, @data
    mov ds, ax
    ; Printing Message1 with a lineBreak
    lea dx, msg1
    mov ah, 09
    int 21H
    mov dl,0AH
    mov ah, 02
    int 21H
    call getString
    xor ax,ax
    lea ax,input
    mov cl,input + 1
    mov ch,0
    add ax,2
    push ax
    push cx
    ; Printing Message2 with a lineBreak
    lea dx, msg2
    mov ah, 09
    int 21H
    mov dl,0AH
    mov ah, 02
    int 21H
    call upper

    mov ah, 4ch
    mov al, 0
    int 21H
endp Main

print proc
    ;Handle bp
    push bp
    mov bp,sp
    add bp,2
    ;pushes
    push ax
    push bx
    push dx
    ;body:
    mov dx,[bp+2]
    ;add dx,2 ; we want to print without the size of the string.
    xor ax,ax
    mov ah,9
    int 21H
    xor ax,ax
    xor dx,dx
    mov dx,13 ; Getting down line in the output
    mov ah,2
    int 21h
    mov dx,10
    mov ah,2
    int 21h ; ^^
    ;pops
    pop dx
    pop bx
    pop ax
    pop bp
    ret 2
endp print

getString proc
    ;Handle bp
    push bp
    mov bp,sp
    add bp,2
    ;pushes
    push ax
    push dx
    ;body:
    mov ah,0AH
    lea dx,input
    int 21H
    xor ax,ax
    xor dx,dx
    mov dx,13 ; Getting down line in the output
    mov ah,2
    int 21h
    mov dx,10
    mov ah,2
    int 21h ; ^^
    ;pops
    pop dx
    pop ax
    pop bp
    ret
endp getString

Upper proc
    ;Handle bp
    push bp
    mov bp,sp
    add bp,2
    ;pushes
    push ax
    push bx
    push cx
    push dx
    push si
    push di
    ;body:
    mov bx,[bp+4]
    mov cx,[bp+2]
    sub sp,[bp+2]
    mov si,sp
    mov di,si

    loopy:
        xor ax,ax
        mov al,[bx]
        cmp al,'z'
        ja notLower
        cmp al,'a'
        jl notLower
        sub al, 32
        mov [si],al
        inc si
        inc bx
        loop loopy
    notLower:
        cmp cx,0
        je stackPrint ; if the last letter was lower so we need to get out of here...
        inc bx
        loop loopy
    stackPrint:
    mov byte ptr [si],'$'
    push di
    call print
    add sp,[bp+2]
    ;pops
    pop di

    pop di
    pop si
    pop dx
    pop cx
    pop bx
    pop ax
    pop bp
    ret 4
endp Upper

END Main

</code>```

Like I said the code works well but every time after the "Upper" procedure ends I can't continue to the following lines because the ret does not return me to the line that comes after calling the procedure

答:
```<code>mov byte ptr [si],'$'
push di
call print
add sp,[bp+2]
;pops
pop di
</code>```

In the Upper proc , the pop di is the culpritt. The print proc already returned with the parameter removed from the stack (ret 2).

Just delete pop di.

BEWARE

If the SS and DS segment registers are different in your program, numerous other changes are needed to make this "String In The Stack" solution work!

Body:
Hi friends I can't go back after the "Upper" procedure to the next line I don't understand where ip has gone ...

.MODEL SMALL
.STACK  64
.DATA
input db 30,?,30 dup('$'),'$'
msg1 db "Please enter string to convert:", 0DH , '$'
msg2 db "Your converted input :", 0DH , '$'
TransFormsMan db 32 ; Going to use the dec value 32 to change my lowers chars..

.Code

Main proc
    mov ax, @data
    mov ds, ax
    ; Printing Message1 with a lineBreak
    lea dx, msg1
    mov ah, 09
    int 21H
    mov dl,0AH
    mov ah, 02
    int 21H
    call getString
    xor ax,ax
    lea ax,input
    mov cl,input + 1
    mov ch,0
    add ax,2
    push ax
    push cx
    ; Printing Message2 with a lineBreak
    lea dx, msg2
    mov ah, 09
    int 21H
    mov dl,0AH
    mov ah, 02
    int 21H
    call upper

    mov ah, 4ch
    mov al, 0
    int 21H
endp Main

print proc
    ;Handle bp
    push bp
    mov bp,sp
    add bp,2
    ;pushes
    push ax
    push bx
    push dx
    ;body:
    mov dx,[bp+2]
    ;add dx,2 ; we want to print without the size of the string.
    xor ax,ax
    mov ah,9
    int 21H
    xor ax,ax
    xor dx,dx
    mov dx,13 ; Getting down line in the output
    mov ah,2
    int 21h
    mov dx,10
    mov ah,2
    int 21h ; ^^
    ;pops
    pop dx
    pop bx
    pop ax
    pop bp
    ret 2
endp print

getString proc
    ;Handle bp
    push bp
    mov bp,sp
    add bp,2
    ;pushes
    push ax
    push dx
    ;body:
    mov ah,0AH
    lea dx,input
    int 21H
    xor ax,ax
    xor dx,dx
    mov dx,13 ; Getting down line in the output
    mov ah,2
    int 21h
    mov dx,10
    mov ah,2
    int 21h ; ^^
    ;pops
    pop dx
    pop ax
    pop bp
    ret
endp getString

Upper proc
    ;Handle bp
    push bp
    mov bp,sp
    add bp,2
    ;pushes
    push ax
    push bx
    push cx
    push dx
    push si
    push di
    ;body:
    mov bx,[bp+4]
    mov cx,[bp+2]
    sub sp,[bp+2]
    mov si,sp
    mov di,si

    loopy:
        xor ax,ax
        mov al,[bx]
        cmp al,'z'
        ja notLower
        cmp al,'a'
        jl notLower
        sub al, 32
        mov [si],al
        inc si
        inc bx
        loop loopy
    notLower:
        cmp cx,0
        je stackPrint ; if the last letter was lower so we need to get out of here...
        inc bx
        loop loopy
    stackPrint:
    mov byte ptr [si],'$'
    push di
    call print
    add sp,[bp+2]
    ;pops
    pop di

    pop di
    pop si
    pop dx
    pop cx
    pop bx
    pop ax
    pop bp
    ret 4
endp Upper

END Main

Like I said the code works well but every time after the "Upper" procedure ends I can't continue to the following lines because the ret does not return me to the line that comes after calling the procedure

Body:
mov byte ptr [si],'$'
push di
call print
add sp,[bp+2]
;pops
pop di

In the Upper proc , the pop di is the culpritt. The print proc already returned with the parameter removed from the stack (ret 2).

Just delete pop di.

BEWARE

If the SS and DS segment registers are different in your program, numerous other changes are needed to make this "String In The Stack" solution work!


问:
Why aren't I getting any definitions when I type "get-command -type cmdlet"?
This is my first day learning powershell so forgive me if this is a silly question...

But the instruction video I am watching shows the teacher typing in  "get-command -type cmdlet" to demonstrate how to get a list of all available cmdlets and their definitions. I'm getting the cmdlets, but my powershell is not listing the definitions. I'm attaching screenshots to show you the what he has and what I have. what changes do I have to make to get this fixed?

答: Cmdlets are written in C#.  They are compiled and you can't normally see the definitions, if you're talking about seeing the source code.</p>


问:
Costless queries on Snowflake
I'm trying to track down Snowflake usage via the snowflake query_history table. I notice that for a few apps, there's near "100%" usage, if I track it by start_time and elapsed time. But, the queries are full of things like "select /* nodejs:heartbeat */ 1;" which I'm told don't actually cost anything. That's cool. But, how can I make my report know that they don't cost anything?

I noticed that this query:

select query_text from query_history where warehouse_size is null;

seems to get me all the queries that are "trivial"... "SELECT current_date", "select /* nodejs:heartbeat */ 1;", etc...

But, sometimes, it also gives me seemingly non-trivial selects: "select * from cst_usr_info where deleted_at is null and lower(usr_email) = ?" for instance...

I guess my questions are:

Does "warehouse_size is null" mean that there is no cost to the query?

If so, then is the reason that the "non-trivial" selects are costless because perhaps they've been cached or something?

答:
Yes, that is a great way to get all queries that relate to no warehouse being used (therefore, no cost).

Your non-trivial queries are likely a query that was available in Snowflake's query result cache (meaning it was executed previously and the results are available without the need of a warehouse).  There are other types of queries that might use metadata information that can be returned from the services layer without the need for a warehouse, like a MIN() or MAX() function, for example.

I hope that helps.

Title: Costless queries on Snowflake


问:
C++, = operator different options
I Wrote the following function for = operator:

```<code>Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}
</code>```

But, I wanted the following code to work as expected (without deleting current data):

```<code>Set s1,s2;
s1=s1;
</code>```

So I made the following changes:

```<code>Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}
</code>```

my question is:

1. Why this is correct:

```<code>    if (this == &s)
    {
        return *this;
    }
</code>```

while this is not:

```<code>    if (this == s)
    {
        return *this;
    }
</code>```

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

```<code>    if (*this == s)
    {
        return *this;
    }
</code>```

答:
If I understand exactly what you're searching about,

```<code>   if (this != &s)
    {
       //Processing
    }
</code>```

In this case you're telling the Compiler, if this address (of the current object) isn't the same as the address of the target (s), you can process the implementation.

Taking as example, two characters from a game in battle, if we're on a

```<code>void Character::punch(Character &other); //function
</code>```

(this == &s) Means that the Subject is punching himself (not what we're expecting), for a safe implementation :

```<code>void Character::punch(Character &other) {
           if (this != &s)
            {
               other.recievesDamage(punchDmg); /* w/ punchDmg defined */
            }
 }
</code>```

So it depends on your thoughts, and what you want to do, most importantly, it means to compare if the Current Object is the same as the other one (s in your example), if they have not the same reference, despite same attributes, that means that they are just similar on their data, but they aren't the same one.

```<code>if (*this == s)
        {
           //Processing
        }
</code>```

You are just comparing between s and the object.

```<code> if (this == s)
            {
               //Processing
            }
</code>```

you're comparing between a pointer reference and an object.

Title: C++, = operator different options

Body:
I Wrote the following function for = operator:

Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

But, I wanted the following code to work as expected (without deleting current data):

Set s1,s2;
s1=s1;

So I made the following changes:

Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

my question is:

1. Why this is correct:

    if (this == &s)
    {
        return *this;
    }

while this is not:

    if (this == s)
    {
        return *this;
    }

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

    if (*this == s)
    {
        return *this;
    }

Body:
If I understand exactly what you're searching about,

   if (this != &s)
    {
       //Processing
    }

In this case you're telling the Compiler, if this address (of the current object) isn't the same as the address of the target (s), you can process the implementation.

Taking as example, two characters from a game in battle, if we're on a

void Character::punch(Character &other); //function

(this == &s) Means that the Subject is punching himself (not what we're expecting), for a safe implementation :

void Character::punch(Character &other) {
           if (this != &s)
            {
               other.recievesDamage(punchDmg); /* w/ punchDmg defined */
            }
 }

So it depends on your thoughts, and what you want to do, most importantly, it means to compare if the Current Object is the same as the other one (s in your example), if they have not the same reference, despite same attributes, that means that they are just similar on their data, but they aren't the same one.

if (*this == s)
        {
           //Processing
        }

You are just comparing between s and the object.

 if (this == s)
            {
               //Processing
            }

you're comparing between a pointer reference and an object.


问:
The form of Plaintext in real number CKKS Encoding Microsoft SEAL
I wonder about the size and form of Plaintext in CKKS Encoding for real number, taking small N for example:

Input vector array = [1.1, 2.2]

N = 8, scale Delta = 2^2 = 4

Number of slot = N/2 = 4

Form of Plaintext:

ptx = [4.4 8.8 0.0 0.0] with size of N/2
or:

ptx = [4.4 8.8 0.0 0.0 | 0.0 0.0 0.0 0.0] with size of N
or:

ptx = [4.4 8.8 0.0 0.0 | 4.4 8.8 0.0 0.0] with size of N

Thank you for your help!

答:
First, in CKKS the number of slots is always N/2 where N is poly_modulus_degree. When you encode a vector shorter than that, the rest of the slots are simply set to zero. Therefore, in your case the plaintext slot values would be [1.1, 2.2, 0.0, 0.0], with a scale of 4. There is an important special case, however: when you encode a single value, then all the slots will hold that value.

However, this is not at all what the actual plaintext data looks like. There isn't an easy way to read the slot values from the plaintext coefficient data: none of the options you suggest match with what is happening in CKKS encoding:

the input vector is doubled in length with its complex conjugates;

an FFT-like transform is computed to convert the input vector into a complex-coefficient polynomial;

the complex coefficients are scaled the designated scale;

the real part of the coefficients is extracted as an integer modulo coeff_modulus (really this is in the RNS representation, i.e., modulo each coeff_modulus prime);

The resulting RNS polynomial is converted to NTT form, which is the default state for Plaintexts when using CKKS.

Without scaling, step 4. would introduce so much error that the process would become totally irreversible.


问:
Is JpaRepository's findAll() guaranteed to return a non-null result if an exception isn't thrown?
The documentation is woefully sparse on this point.</p>

答:
This is documented, see section Null Handling of Repository Methods of the Spring Data JPA documentation:

Repository methods returning collections, collection alternatives,
  wrappers, and streams are guaranteed never to return null but rather
  the corresponding empty representation. See “Repository query return
  types” for details.

As Spring Data JPA generates the query methods based on naming patterns and JpaRepository is only one example of such repositories, it probably didn't make sense to document it in the JavaDoc, but instead they put it in the user documentation.


问:
Why don't Parameters<Func> extend unknown[] (Array<unknown>) in ts strict mode
The title pretty much says it all really. I have this code:

```<code>  type testNoArgsF = () => number;
  type testArgsF = (arg1: boolean, arg2: string) => number;
  type unknownArgsF = (...args: unknown[]) => number;
  type anyArgsF = (...args: any[]) => number;

  type testII = testArgsF extends anyArgsF ? true : false; // true
  type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

  // unexpected:
  type testIV = testArgsF extends unknownArgsF ? true : false; // false <- why?
  // even though:
  type testV = testNoArgsF extends unknownArgsF ? true : false; // true
</code>```

It is written in typescript (version 3.8), and I have strict mode enabled. The unexpected result is that a test function doesn't extend a function type with spread args of unknown[], yet if you just check the parameters they do extend unknown[]. Since the return type is always number, I don't understand what else could possibly be different to falsify the extends statement.

Other notes:

The extend statement is true only if your test function has 0 arguments.

This behaviour is not seen if you turn off strict mode.

答:
I'll try to put it simple: "extends" -> "compatible" -> "can be used in place of"

Can you use (arg1: boolean, arg2: string) => number;

instead of (...args: unknown[]) => number?

No, because the latter can handle call without arguments, but the former might fail at runtime (e.g. will try to access properties of the arguments)

More info on functions compatibility here

Body:
The title pretty much says it all really. I have this code:

  type testNoArgsF = () => number;
  type testArgsF = (arg1: boolean, arg2: string) => number;
  type unknownArgsF = (...args: unknown[]) => number;
  type anyArgsF = (...args: any[]) => number;

  type testII = testArgsF extends anyArgsF ? true : false; // true
  type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

  // unexpected:
  type testIV = testArgsF extends unknownArgsF ? true : false; // false <- why?
  // even though:
  type testV = testNoArgsF extends unknownArgsF ? true : false; // true

It is written in typescript (version 3.8), and I have strict mode enabled. The unexpected result is that a test function doesn't extend a function type with spread args of unknown[], yet if you just check the parameters they do extend unknown[]. Since the return type is always number, I don't understand what else could possibly be different to falsify the extends statement.

Other notes:

The extend statement is true only if your test function has 0 arguments.

This behaviour is not seen if you turn off strict mode.


问:
Remove repetition from if-else statement
I have written an if...else statement which uses an array myArr and a string myStr as follows:

```<code>If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If
</code>```

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

答:
I don't think you'll be able to get exactly the same flow in a simpler way.

Either you're going to end up doing things different things, or doing duplicate things. eg:

```<code>If myArr.Length > 0 Then
   If myArr(0) = "-1" Then
      'Do stuff
   Else
      'Do stuff
   End If
ElseIf myStr= "xyz" Then
  'Do stuff
Else
  'Do Nothing
End If
</code>```

This will cause mystr="xyz" not to happen whenn myArr(0) <> -1 whereas it may have before.

Body:
I have written an if...else statement which uses an array myArr and a string myStr as follows:

If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

Body:
I don't think you'll be able to get exactly the same flow in a simpler way.

Either you're going to end up doing things different things, or doing duplicate things. eg:

If myArr.Length > 0 Then
   If myArr(0) = "-1" Then
      'Do stuff
   Else
      'Do stuff
   End If
ElseIf myStr= "xyz" Then
  'Do stuff
Else
  'Do Nothing
End If

This will cause mystr="xyz" not to happen whenn myArr(0) <> -1 whereas it may have before.


问:
Can't push old elements up one place in an array
I am trying to create a method where I enter a number and it replaces the first array element. However after that I want the older array values to be pushed to the next size.
Like old values {1,2,3,4}
New values after inputting 10 in this method: {10,1,2,3}.
I do not understand where I am going wrong.
Here list is the name of the array.  </p>

```<code> public void insertFirst(int newElement)
    {
        int temp = 0;
        list[0]= newElement;

        for(int y= 1; y<list.length-1;y++){
            list[y+1] = list[y];
        }

    }
</code>```

答: I can see a flaw in the code as you are first updating the details to the array[0] and you are then copying the data from array[1] to array[2] and so on you will never know the value if you directly update just try debugging the code you will find the error you have done. Try coding this way array[last] = array[last-1] and so on then your array looks like {1,1,2,3} then append the new element in array[0]  </p>

Body:
I am trying to create a method where I enter a number and it replaces the first array element. However after that I want the older array values to be pushed to the next size.
Like old values {1,2,3,4}
New values after inputting 10 in this method: {10,1,2,3}.
I do not understand where I am going wrong.
Here list is the name of the array.

 public void insertFirst(int newElement)
    {
        int temp = 0;
        list[0]= newElement;

        for(int y= 1; y<list.length-1;y++){
            list[y+1] = list[y];
        }

    }


问:
How can we get call log with specific date duration by paging using Twilio API?
I wanted to get a call log with a specific time duration but I am not getting from & to the parameter in URL. I am always getting latest records.

https://api.twilio.com/2010-04-01/Accounts/{AccountSID}/Calls.json

can someone help me to pass From & To date, to get a specific time duration call log?

Reference URL: https://www.twilio.com/docs/usage/twilios-response#response-formats-list-paging-information

答:
Try something like this:

https://api.twilio.com/2010-04-01/Accounts/{AccountSID}/Calls.json?StartTime%3E=2020-05-08T00%3A00%3A00Z&Status=completed&PageSize=100


问:
How to read csv file using CSV Data Set Config at once in Jmeter (instead of line by line)
I need to get whole text from csv file using CSV Data Set Config at once. </p>

答:
You cannot, if you want to load the whole file into certain place in the Test Plan or into a JMeter Variable you can use __FileToString() function and provide the relative or full path to the CSV file like:

```<code>${__FileToString(/path/to/your/file.csv,,)}
</code>```

if you want to save the file into the variable just provide the variable name as the last parameter:

```<code>${__FileToString(/path/to/your/file.csv,,foo)}
</code>```

Check out Apache JMeter Functions - An Introduction article to learn more about JMeter Functions concept

Body:
You cannot, if you want to load the whole file into certain place in the Test Plan or into a JMeter Variable you can use __FileToString() function and provide the relative or full path to the CSV file like:

${__FileToString(/path/to/your/file.csv,,)}

if you want to save the file into the variable just provide the variable name as the last parameter:

${__FileToString(/path/to/your/file.csv,,foo)}

Check out Apache JMeter Functions - An Introduction article to learn more about JMeter Functions concept


问:
Puppeteer confirm
I am trying to learn puppeteer. I have successfully scripted a login to a page and some navigation. Then I have it click on a button. The page throws up a window.confirm and I want my script to accept this to continue to the next step but I can’t figure out how.

Can anyone point me in the right direction?

答:
We are building objects to pass so it's a little different but I thought I would share.

We create an object for the operation:

```<code>type: "operation",
name: "Touch Delete button from tracks-hero-tmp",
description: "Click and confirm delete and verify track cluster is 1 less",
actions: [
  { method: 'waitForSelector', value: '[tg-name=track_hero_delete_btn]' },
  { method: 'focus', value: '[tg-name=track_hero_delete_btn]' },
  { method: 'click', value: '[tg-name=track_hero_delete_btn]', accept_dialog: 'false' },
  { method: 'screenshot' }
],
</code>```

Then the "accept_dialog" is set to a boolean that gets passed into an async function and we set the dialog response like this:

```<code>  if (accept_dialog) {
    await dialog.accept();
  } else {
    await dialog.dismiss();
  }
</code>```

Hope this helps someone. :)

Title: Puppeteer confirm

Body:
We are building objects to pass so it's a little different but I thought I would share.

We create an object for the operation:

type: "operation",
name: "Touch Delete button from tracks-hero-tmp",
description: "Click and confirm delete and verify track cluster is 1 less",
actions: [
  { method: 'waitForSelector', value: '[tg-name=track_hero_delete_btn]' },
  { method: 'focus', value: '[tg-name=track_hero_delete_btn]' },
  { method: 'click', value: '[tg-name=track_hero_delete_btn]', accept_dialog: 'false' },
  { method: 'screenshot' }
],

Then the "accept_dialog" is set to a boolean that gets passed into an async function and we set the dialog response like this:

  if (accept_dialog) {
    await dialog.accept();
  } else {
    await dialog.dismiss();
  }

Hope this helps someone. :)


问:
Is there a way to pull out two successive records only if they occur one after the other in a series of files?
I'm trying to pull out two successive records, but only if those records occur one after the other. I'm working with files that look like this:

```<code>#File1
>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
>CHB002 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH

#File2
>CHB0022 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0023 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0024 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

</code>```

I want to pull out everything under PatternA and PatternB from all files, but only if they occur one after the other. My desired output is:

```<code>>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
</code>```

I've tried:

```<code>awk -v RS='>' -v ORS='>' '/PatternA/,/PatternB/' file*.txt > output.txt
</code>```

But this would include PatternC from file 2 in the output and I want to skip file2 because PatternA and PatternB don't occur successively. Next I tried this command:

```<code>awk -v RS='>' -v ORS='>' '/PatternA/{l=NR}/PatternB/&&NR==l+1' file*.txt > output.txt
</code>```

This prints out this:

```<code>>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
</code>```

This gets me closer as I only print PatternB from file1.txt (which I do want to include in my output) and I exclude PatternB from file2.txt, which I don't want. However, I also want to include PatternA with PatternB in my desired output. The CHB### pattern is variable and can't rely upon that. I feel like this should be something I can accomplish in a one line command without needing to write a script, but I'm stuck (also new to this).

答:
with multi-char RS

```<code>$ awk -v RS='(^|\n)>' '$2~/PatternA/{a=1; p=$0; next}
                       a{if($2~/PatternB/) print RT p RT $0; a=0}' file1

>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
</code>```

has an extra newline at the top, easy to get rid if you change print RT p RT $0 to print ">" p "\n>" $0.  But perhaps not important.

Or, with other awks if > is not appearing anywhere else

```<code>$ awk -v RS='>' '$2~/PatternA/{a=1; p=$0; next}
                 a{if($2~/PatternB/) print RT p RT $0; a=0}' file
</code>```

Body:
I'm trying to pull out two successive records, but only if those records occur one after the other. I'm working with files that look like this:

#File1
>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH
>CHB002 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH

#File2
>CHB0022 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0023 PatternC
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB0024 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

I want to pull out everything under PatternA and PatternB from all files, but only if they occur one after the other. My desired output is:

>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

I've tried:

awk -v RS='>' -v ORS='>' '/PatternA/,/PatternB/' file*.txt > output.txt

But this would include PatternC from file 2 in the output and I want to skip file2 because PatternA and PatternB don't occur successively. Next I tried this command:

awk -v RS='>' -v ORS='>' '/PatternA/{l=NR}/PatternB/&&NR==l+1' file*.txt > output.txt

This prints out this:

>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

This gets me closer as I only print PatternB from file1.txt (which I do want to include in my output) and I exclude PatternB from file2.txt, which I don't want. However, I also want to include PatternA with PatternB in my desired output. The CHB### pattern is variable and can't rely upon that. I feel like this should be something I can accomplish in a one line command without needing to write a script, but I'm stuck (also new to this).

Body:
with multi-char RS

$ awk -v RS='(^|\n)>' '$2~/PatternA/{a=1; p=$0; next}
                       a{if($2~/PatternB/) print RT p RT $0; a=0}' file1

>CHB001 PatternA
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
>CHB002 PatternB
RANDOMSTRINGOFLETTERS
LETTERSRANDOMSTRINGHH
LETTERSRANDOMSTRINGHH

has an extra newline at the top, easy to get rid if you change print RT p RT $0 to print ">" p "\n>" $0.  But perhaps not important.

Or, with other awks if > is not appearing anywhere else

$ awk -v RS='>' '$2~/PatternA/{a=1; p=$0; next}
                 a{if($2~/PatternB/) print RT p RT $0; a=0}' file


问:
PHP/MySQL - Performance considerations querying (select only) 48k rows
I am currently attempting to build a web application that relies quite heavily on postcode data (supplied from OS CodePoint Open). The postcode database has 120 tables which breaks down the initial postcode prefix (i.e. SE, WS, B). Inside these tables there are between 11k - 48k rows with 3 fields (Postcode, Lat, Lng).

What I need to be able to do is for a user to come online, enter their postcode i.e. SE1 1LD which then selects the SE table, and converts the postcode into a lat / lng.

I am fine with doing this on a PHP level. My concern is.. well the huge number of rows that will be queried and whether it is going to grind my website to a halt?

If there are any techniques that I should know about, please do let me know.. I've never worked with tables with big numbers in!

Thanks :)

答:
48K are not big numbers. 48 million is. :) If your tables are properly indexed (put indexes on the fields you use in the WHERE clause) it won't be a problem at all.

Avoid LIKE, and use INNER JOINS instead of LEFT JOINs if possible.


问:
Can't access images in S3 bucket using cognito identity
I'm testing to display images from an s3 bucket using javascript, prior to making this part of an application.

I have an s3 bucket (non-public), named for this post:  IMAGE-BUCKET
Created an identity role : GET-IMAGE.
I have temporarily given full s3 access to GET-IMAGE role.
I have CORS defined for the bucket.
While testing I have disabled the browser cache.

3 issues:

Getting "403 Forbidden" response when images are accessed from the
html/script below.

If I make a particular image public, that image displays -- an issue with large # of images.

If I make the entire bucket public, images do not display

It seems Cognito identiy is not able to access the bucket, or there's an issue in the script below.

Also, setting the bucket public doesn't work either, unless each image is also set public. This bucket will be used privately, so this is only an issue while troubleshooting.

I have attached AmazonS3FullAccess to GET-IMAGE, I  also added the following policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AccessS3BucketIMAGEBUCKET",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
</code>```

Using html and script from AWS documentation (modified):

Photo Album Viewer

    <button onclick="viewAlbum('');">View All Images</button>

```
</div>
</div>
</p>

<p>UPDATE:
If I grant public read in S3 Bucket Policy:</p>

```{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }
    ]
}
```

<p>It allows to access each image; solving the issue #2 and #3.
But this makes the bucket basically public.</p>

<p>If I change the Bucket policy to limit to the Cognito identity, changing the principal as follows, again I am not able to access images via the html/script, getting 403 errors.</p>

```"Principal": {
    "AWS": "arn:aws:iam::547299998870:role/Cognito_GET-IMAGEIDUnauth_Role"
}
```

<p>UPDATE:
I've been reading online, checking some of the other related posts ...
I've it reduced to the basic components, here's the latest configuration. The configuration should be as simple as, giving access to the GET-IMAGE role based on the documentation:</p>

<p>Under IAM Management Console > Roles > GET-IMAGE role (unauthenticated)
I added an inline policy:</p>

```        {
        "Sid": "VisualEditor2",
        "Effect": "Allow",
        "Action": ["s3:GetObject","s3:ListBucket"],
        "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }
```

I removed the Bucket policy -- this shouldn't be needed, the GET-IMAGE role already has access. Role trust is already included by default.  HTML contains the credential:
IdentityPoolId: 'us-east-1:9bfadd6a-xxxx-41d4-xxxx-79ad7347xxa1

Those are the most basic components, nothing else should be needed. However, it does not work.  I made 1 of the images public and that image is displayed, other images error with 403 Forbidden.

答:
I've resolved the s3 access issue, I'm including all the settings and methods I used. To troubleshoot, I started testing with an actual AWS user, then stepped back to the cognito identity.  I included notes regarding access by an AWS user for reference.  I also abondoned the AWS sample HTML code, and used a simple short function to display output in the console, utilizing getsignedurl function. I'm not familiar with AWS libraries, and finding getsignedurl helped speed up testing and finally resolving the issue.

Used the following sample names throughout:
Cognito Role: GET-IMAGE
S3 Bucket: IMAGE-BUCKET

I'll go over both Cognito and AWS user access to S3, using HTML for simple demo and testing.

With Cognito:

SETTINGS:

Role:  Create a Cognito Identity. For instructions and to create, follow this wizard:
       https://console.aws.amazon.com/cognito/create/
       Take a note of the sample code AWS provides after it's created-- you'll need the pool ID.

Permissions: Add Role level AND S3 level permissions

Role level: IAM > Roles > GET-IMAGE_Unauth_Role

Add (JSON) to both Auth and UnAuth Roles

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "s3Access",
        "Effect": "Allow",
        "Action": [
            "s3:GetObject"
        ],
        "Resource": [
            "arn:aws:s3:::IMAGE-BUCKET/*"
        ]}
</code>```

S3:
IMAGE-BUCKET > Permissions > Bucket Policy:

(JSON)

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "PublicRead",
        "Effect": "Allow",
        "Principal": {
            "AWS": [
                "arn:aws:iam::547999998899:user/anAWSUser",
                "arn:aws:iam::547999998899:role/Cognito_GET-IMAGEIDUnauth_Role",
                "arn:aws:iam::547999998899:role/Cognito_GET-IMAGEIDAuth_Role"
            ]
        },
        "Action": [
            "s3:GetObject"
        ],
        "Resource": [
            "arn:aws:s3:::IMAGE-BUCKET/*"
        ]
    }
]}
</code>```

** Note: I also added an AWSUser, for credential version, for use in the next section "With Credentials"

CORS:

IMAGE-BUCKET> Permissions > CORS

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

**Note:  You can restrict the origin in the AllowedOrigin parameter.

HTML:

<!DOCTYPE html>

S3 Test Image Display

    <button onclick="show1();">View Image</button>

```
</div>
</div>
</p>

<h1>With User Credentials</h1>

<p>You can also use credentials to authenticate a user to access s3.  In the javascript above,
comment out the cognito credentials and use the following instead:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>//access key ID, Secret
var cred = new AWS.Credentials('AKXXX283988CCCAA-ACCESS-KEY','kKsCuq7a9WNohmOYY8SApewie77493LgV-SECRET');
AWS.config.credentials=cred;</code>```

To get the access key and secret from AWS console:
IAM > Users > an-AWSUser > Security-Credentials

Under "Access Keys", click "Create Access Key"

===================

Note that the trust policy for an unauthenticated role is automatically created by AWS when you create a Cognito ID Role; it doesn't have to be defined manually as mentioned before.

Also listbucket and bucket level resource permissions, as in "IMAGE-BUCKET", are not required; Getobject is all that's needed to access a file directly.  In my case, I'm accessing images by key, do not need to list bucket contents.

I set both the Role and S3 bucket permissions; I did not test without the role permissions, bucket policy may be sufficient.

Body:
I'm testing to display images from an s3 bucket using javascript, prior to making this part of an application.

I have an s3 bucket (non-public), named for this post:  IMAGE-BUCKET
Created an identity role : GET-IMAGE.
I have temporarily given full s3 access to GET-IMAGE role.
I have CORS defined for the bucket.
While testing I have disabled the browser cache.

3 issues:

Getting "403 Forbidden" response when images are accessed from the
html/script below.

If I make a particular image public, that image displays -- an issue with large # of images.

If I make the entire bucket public, images do not display

It seems Cognito identiy is not able to access the bucket, or there's an issue in the script below.

Also, setting the bucket public doesn't work either, unless each image is also set public. This bucket will be used privately, so this is only an issue while troubleshooting.

I have attached AmazonS3FullAccess to GET-IMAGE, I  also added the following policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AccessS3BucketIMAGEBUCKET",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

Using html and script from AWS documentation (modified):

Photo Album Viewer

    <button onclick="viewAlbum('');">View All Images</button>

UPDATE:
If I grant public read in S3 Bucket Policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }
    ]
}

It allows to access each image; solving the issue #2 and #3.
But this makes the bucket basically public.

If I change the Bucket policy to limit to the Cognito identity, changing the principal as follows, again I am not able to access images via the html/script, getting 403 errors.

"Principal": {
    "AWS": "arn:aws:iam::547299998870:role/Cognito_GET-IMAGEIDUnauth_Role"
}

UPDATE:
I've been reading online, checking some of the other related posts ...
I've it reduced to the basic components, here's the latest configuration. The configuration should be as simple as, giving access to the GET-IMAGE role based on the documentation:

Under IAM Management Console > Roles > GET-IMAGE role (unauthenticated)
I added an inline policy:

        {
        "Sid": "VisualEditor2",
        "Effect": "Allow",
        "Action": ["s3:GetObject","s3:ListBucket"],
        "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }

I removed the Bucket policy -- this shouldn't be needed, the GET-IMAGE role already has access. Role trust is already included by default.  HTML contains the credential:
IdentityPoolId: 'us-east-1:9bfadd6a-xxxx-41d4-xxxx-79ad7347xxa1

Those are the most basic components, nothing else should be needed. However, it does not work.  I made 1 of the images public and that image is displayed, other images error with 403 Forbidden.

Body:
I've resolved the s3 access issue, I'm including all the settings and methods I used. To troubleshoot, I started testing with an actual AWS user, then stepped back to the cognito identity.  I included notes regarding access by an AWS user for reference.  I also abondoned the AWS sample HTML code, and used a simple short function to display output in the console, utilizing getsignedurl function. I'm not familiar with AWS libraries, and finding getsignedurl helped speed up testing and finally resolving the issue.

Used the following sample names throughout:
Cognito Role: GET-IMAGE
S3 Bucket: IMAGE-BUCKET

I'll go over both Cognito and AWS user access to S3, using HTML for simple demo and testing.

With Cognito:

SETTINGS:

Role:  Create a Cognito Identity. For instructions and to create, follow this wizard:
       https://console.aws.amazon.com/cognito/create/
       Take a note of the sample code AWS provides after it's created-- you'll need the pool ID.

Permissions: Add Role level AND S3 level permissions

Role level: IAM > Roles > GET-IMAGE_Unauth_Role

Add (JSON) to both Auth and UnAuth Roles

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "s3Access",
        "Effect": "Allow",
        "Action": [
            "s3:GetObject"
        ],
        "Resource": [
            "arn:aws:s3:::IMAGE-BUCKET/*"
        ]}

S3:
IMAGE-BUCKET > Permissions > Bucket Policy:

(JSON)

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "PublicRead",
        "Effect": "Allow",
        "Principal": {
            "AWS": [
                "arn:aws:iam::547999998899:user/anAWSUser",
                "arn:aws:iam::547999998899:role/Cognito_GET-IMAGEIDUnauth_Role",
                "arn:aws:iam::547999998899:role/Cognito_GET-IMAGEIDAuth_Role"
            ]
        },
        "Action": [
            "s3:GetObject"
        ],
        "Resource": [
            "arn:aws:s3:::IMAGE-BUCKET/*"
        ]
    }
]}

** Note: I also added an AWSUser, for credential version, for use in the next section "With Credentials"

CORS:

IMAGE-BUCKET> Permissions > CORS

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

**Note:  You can restrict the origin in the AllowedOrigin parameter.

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.487.0.js"></script>
    <script>
    //   Replace IMAGE-BUCKET with your bucket name.
    var BucketName = 'IMAGE-BUCKET';

    // Cognito credentials (from Cognito ID creation sample code)
    AWS.config.region = 'us-east-1'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
         IdentityPoolId: 'us-east-1:9999996a-f099-99d4-b999-79a99999aaa1',

    });

    // Create a new service object
    var s3 = new AWS.S3({
            apiVersion: '2006-03-01',
            params: { Bucket: BucketName }
    });

    // Test Function.  REPLACE Key with test file name from s3
function show1() {
  var UrlExpireSeconds = 180 * 1;
  var params = {
  Bucket: BucketName,
  Key: "20190815_file_name.jpg",
  Expires: UrlExpireSeconds
               };
var url = s3.getSignedUrl('getObject', params);
console.log('The URL is', url);
document.getElementById('viewer').innerHTML =
                                '<span>'+
                                '<div>'+
                                '<br/>'+
                                '<img style="width:128px;height:128px;" src="' +
                                url + '"/>' +
                                '</div>'+
                                '<div>'+
                                '<span>'
};

 show1();
   </script>

</head>
<body>
    <h1>S3 Test Image Display</h1>
    <div id="viewer" />
    <button onclick="show1();">View Image</button>
</body>
</html>

With User Credentials

You can also use credentials to authenticate a user to access s3.  In the javascript above,
comment out the cognito credentials and use the following instead:

//access key ID, Secret
var cred = new AWS.Credentials('AKXXX283988CCCAA-ACCESS-KEY','kKsCuq7a9WNohmOYY8SApewie77493LgV-SECRET');
AWS.config.credentials=cred;

To get the access key and secret from AWS console:
IAM > Users > an-AWSUser > Security-Credentials

Under "Access Keys", click "Create Access Key"

===================

Note that the trust policy for an unauthenticated role is automatically created by AWS when you create a Cognito ID Role; it doesn't have to be defined manually as mentioned before.

Also listbucket and bucket level resource permissions, as in "IMAGE-BUCKET", are not required; Getobject is all that's needed to access a file directly.  In my case, I'm accessing images by key, do not need to list bucket contents.

I set both the Role and S3 bucket permissions; I did not test without the role permissions, bucket policy may be sufficient.


问:
How can I read errors and warnings in IntelliJ with a screen reader?
I am using IntelliJ Idea for developing scala and Java programs. I am also a screen reader user.

One of the most useful features that IDEs provide is code linting and displaying error and warnings in your code, along with descriptions. I understand if you are a sighted user, you can just hover your mouse over an erroneous line of code and you get a tooltip with the description.

I haven't been able to figure out how to access this description as a screen reader users. So far, to review errors/warnings I would just build the program and look at the command line output, however this is pretty inefficient compared to just hovering over line of code.

Could someone share a better way of reviewing errors/warnings in IntelliJ using a screen reader? Ideally how to access the error tooltip, or how to access a better UI for reviewing them instead of looking at raw command line output.

答:
I'm not sure about warnings however errors can be accessed in two ways:
Firstly when the caret is moved into a line with error the error text is written into the status bar - the problem with this approach is that for JAB applications screen readers are generally unable to find it, so in case of NVDA object navigation has to be used.
The second way requires your caret to be exactly at the point with error - generally it would be set in the proper place if you've navigated to the line with F2. After that you need to press CTRL+f1 - focus moves to the unnamed pane and the error text is its first descendant so once again you need to employ object navigation. I haven't found any reasonable way to access error texts with JAWS  sadly.</p>


问:
Flutter : Could not find a generator for route RouteSettings("/HomePage", null) in the _WidgetsAppState
I'm using the following in my demo project for routes:

```<code> routes: <String, WidgetBuilder>{
    '/HomePage': (BuildContext context) => HomePage()
  },
</code>```

And trying to navigate home screen using the following code:

```<code>onPressed: () {
    debugPrint("Hello button is clicked");

     Navigator.of(context)
               .pushReplacementNamed('/HomePage');
 },
</code>```

But When my button clicked I'm getting the following Exception:

```<code>════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Could not find a generator for route RouteSettings("/HomePage", null) in the _WidgetsAppState.

Generators for routes are searched for in the following order:
 1. For the "/" route, the "home" property, if non-null, is used.
 2. Otherwise, the "routes" table is used, if it has an entry for the route.
 3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
 4. Finally if all else fails onUnknownRoute is called.
Unfortunately, onUnknownRoute was not set.
When the exception was thrown, this was the stack:
#0      _WidgetsAppState._onUnknownRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:772:9)
#1      _WidgetsAppState._onUnknownRoute (package:flutter/src/widgets/app.dart:785:6)
#2      NavigatorState._routeNamed (package:flutter/src/widgets/navigator.dart:1625:22)
#3      NavigatorState.pushReplacementNamed (package:flutter/src/widgets/navigator.dart:1690:35)
#4      _RegisterPage.build.<anonymous closure> (package:oricon/register.dart:231:42)
</code>```

I have already checked below Stack-overflow links

Could not find a generator for route RouteSettings("/", null) in the _WidgetsAppState

How to use routes in flutter to navigate to page other than from main?

Could not find a generator for route "home-page" in the _MaterialAppState

Why does it not work when I use pushNamedReplacement instead of pushReplacement?

If you need more information, please do let me know.

答:
You can use instead of:

```<code>Navigator.of(context)
           .pushReplacementNamed('/HomePage');
</code>```

Use this:

```<code> Navigator.push(context, new MaterialPageRoute(
   builder: (context) => new MyHomePage())
 );
</code>```

As you can see in this answer, this worked for me

Body:
I'm using the following in my demo project for routes:

 routes: <String, WidgetBuilder>{
    '/HomePage': (BuildContext context) => HomePage()
  },

And trying to navigate home screen using the following code:

onPressed: () {
    debugPrint("Hello button is clicked");

     Navigator.of(context)
               .pushReplacementNamed('/HomePage');
 },

But When my button clicked I'm getting the following Exception:

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Could not find a generator for route RouteSettings("/HomePage", null) in the _WidgetsAppState.

Generators for routes are searched for in the following order:
 1. For the "/" route, the "home" property, if non-null, is used.
 2. Otherwise, the "routes" table is used, if it has an entry for the route.
 3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
 4. Finally if all else fails onUnknownRoute is called.
Unfortunately, onUnknownRoute was not set.
When the exception was thrown, this was the stack:
#0      _WidgetsAppState._onUnknownRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:772:9)
#1      _WidgetsAppState._onUnknownRoute (package:flutter/src/widgets/app.dart:785:6)
#2      NavigatorState._routeNamed (package:flutter/src/widgets/navigator.dart:1625:22)
#3      NavigatorState.pushReplacementNamed (package:flutter/src/widgets/navigator.dart:1690:35)
#4      _RegisterPage.build.<anonymous closure> (package:oricon/register.dart:231:42)

I have already checked below Stack-overflow links

Could not find a generator for route RouteSettings("/", null) in the _WidgetsAppState

How to use routes in flutter to navigate to page other than from main?

Could not find a generator for route "home-page" in the _MaterialAppState

Why does it not work when I use pushNamedReplacement instead of pushReplacement?

If you need more information, please do let me know.

Body:
You can use instead of:

Navigator.of(context)
           .pushReplacementNamed('/HomePage');

Use this:

 Navigator.push(context, new MaterialPageRoute(
   builder: (context) => new MyHomePage())
 );

As you can see in this answer, this worked for me


问:
How to speed up a search on large collection of text files (1TB)
I have a collection of text files containing anonymised medical data (age, country, symptoms, diagnosis etc). This data goes back for at least 30 years so as you can imagine I have quite a large sized data set. In total I have around 20,000 text files totalling approx. 1TB.

Periodically I will be needing to search these files for occurances of a particular string (not regex). What is the quickest way to search through this data?

I have tried using grep and recursively searching through the directory as follows:

```<code>LC_ALL=C fgrep -r -i "searchTerm" /Folder/Containing/Files
</code>```

The only problem with doing the above is that it takes hours (sometimes half a day!) to search through this data.

Is there a quicker way to search through this data? At this moment I am open to different approaches such as databases, elasticsearch etc. If I do go down the database route, I will have approx. 1 billion records.

My only requirements are:

1) The search will be happening on my local computer (Dual-Core CPU and 8GB RAM)

2) I will be searching for strings (not regex).

3) I will need to see all occurances of the search string and the file it was within.

答:
I see 3 options for you.

You should really consider upgrading your hardware, hdd -> ssd upgrade can multiply the speed of search by times.

Increase the speed of your search on the spot.
You can refer to this question for various recommendations. The main idea of this method is optimize CPU load, but you will be limited by your HDD speed. The maximum speed multiplier is the number of your cores.

You can index your dataset.
Because you're working with texts, you would need some full text search databases. Elasticsearch and Postgres are good options.
This method requires you more disk space (but usually less than x2 space, depending on the data structure and the list of fields you want to index).
This method will be infinitely faster (seconds).
If you decide to use this method, select the analyzer configuration carefully to match what considered to be a single word for your task (here is an example for Elasticsearch)

Body:
I have a collection of text files containing anonymised medical data (age, country, symptoms, diagnosis etc). This data goes back for at least 30 years so as you can imagine I have quite a large sized data set. In total I have around 20,000 text files totalling approx. 1TB.

Periodically I will be needing to search these files for occurances of a particular string (not regex). What is the quickest way to search through this data?

I have tried using grep and recursively searching through the directory as follows:

LC_ALL=C fgrep -r -i "searchTerm" /Folder/Containing/Files

The only problem with doing the above is that it takes hours (sometimes half a day!) to search through this data.

Is there a quicker way to search through this data? At this moment I am open to different approaches such as databases, elasticsearch etc. If I do go down the database route, I will have approx. 1 billion records.

My only requirements are:

1) The search will be happening on my local computer (Dual-Core CPU and 8GB RAM)

2) I will be searching for strings (not regex).

3) I will need to see all occurances of the search string and the file it was within.


问:
How can I get a particular part of a String enclosed between 2 characters using Excel VBA?
I need to write a macro in excel which can help me get a particular part of a string. My string is as follows :

PAYPAL *VINAYAKAGGRAWAL 4029357733

I need to extract VINAYAKAGGRAWAL from the above string. Any help with vba macro or any excel formula to do this would help.

Thanks in advance.

答:
Maybe this:</p>

```<code>strClean = Replace("PAYPAL *VINAYAKAGGRAWAL 4029357733", "PAYPAL *", "")
strWanted = Left(strClean, InStr(strClean, " ") - 1)
Debug.Print strWanted
</code>```

Body:
Maybe this:

strClean = Replace("PAYPAL *VINAYAKAGGRAWAL 4029357733", "PAYPAL *", "")
strWanted = Left(strClean, InStr(strClean, " ") - 1)
Debug.Print strWanted


问:
Error:module 'cv2.cv2' has no attribute 'STEREO_BM_BASIC_PRESET'
I am trying to get the depth map of two stereo images but error 'cv2.cv2' has no attribute 'STEREO_BM_BASIC_PRESET' occurred.
the code:</p>

```<code>import cv2
import numpy as np
from matplotlib import pyplot as plt
# Convert to depth image

imgL = cv2.imread('D:\Books\Pav Man\PICS\R.jpg',0)
imgR = cv2.imread('D:\Books\Pav Man\PICS\L.jpg',0)

stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET,ndisparities=16, SADWindowSize=15)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()
#-------------------
</code>```

答:
solved worked with OpenCV 4.  </p>

```<code>import cv2
import numpy as np
from matplotlib import pyplot as plt
# Convert to depth image

imgL = cv2.imread('D:\Books\Pav Man\PICS\R.jpg',0)
imgR = cv2.imread('D:\Books\Pav Man\PICS\L.jpg',0)

stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)

disparity = stereo.compute(imgL,imgR)

plt.imshow(disparity,'gray')

plt.show()
</code>```

Body:
I am trying to get the depth map of two stereo images but error 'cv2.cv2' has no attribute 'STEREO_BM_BASIC_PRESET' occurred.
the code:

import cv2
import numpy as np
from matplotlib import pyplot as plt
# Convert to depth image

imgL = cv2.imread('D:\Books\Pav Man\PICS\R.jpg',0)
imgR = cv2.imread('D:\Books\Pav Man\PICS\L.jpg',0)

stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET,ndisparities=16, SADWindowSize=15)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()
#-------------------

Body:
solved worked with OpenCV 4.

import cv2
import numpy as np
from matplotlib import pyplot as plt
# Convert to depth image

imgL = cv2.imread('D:\Books\Pav Man\PICS\R.jpg',0)
imgR = cv2.imread('D:\Books\Pav Man\PICS\L.jpg',0)

stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)

disparity = stereo.compute(imgL,imgR)

plt.imshow(disparity,'gray')

plt.show()


问:
set the timezone for the XMLGregorianCalendar
I have a the XMLGregorianCalendar instance and I need to set the timezone to the "America/New_York". The class has a method to set the timezone. AS the Greenwich Mean Time is 4 hours ahead of Eastern Time, does it set like this to the "America/New_York" timezone?</p>

```<code>gregorianCalendar.setTimezone(-4);
</code>```

答:
I have come with this solution lately and works fine for me. </p>

```<code>Date date = format.parse(beginTime);

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);

        XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

        TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
        int minutes = timeZone.getOffset(cal.getTimeInMillis()) / 1000 / 60;
        xmlGregCal.setTimezone(minutes);
</code>```

Body:
I have a the XMLGregorianCalendar instance and I need to set the timezone to the "America/New_York". The class has a method to set the timezone. AS the Greenwich Mean Time is 4 hours ahead of Eastern Time, does it set like this to the "America/New_York" timezone?

gregorianCalendar.setTimezone(-4);

Body:
I have come with this solution lately and works fine for me.

Date date = format.parse(beginTime);

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);

        XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

        TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
        int minutes = timeZone.getOffset(cal.getTimeInMillis()) / 1000 / 60;
        xmlGregCal.setTimezone(minutes);


问:
How Can I input n-values to n-keys in a dictionary from user with python?
I have the following code:

l=[]
n=int(input('enter number of list'))
[[] for i in range (n)]

for i in range (1, n+1):
    m=input('enter student')
    l.append(m)
    n=int(input('enter number of grades'))
    for i in range (1, n+1):
        y=int(input('enter grade'))
        l.append(y)
        s = ''.join(str(l))
print (*l,sep='')
```

and I would like to represent the input data as the following data:

答:
I believe what you want to do is the following:

n=int(input('enter number of students'))
l=[]
for i in range (n):
    m=input('enter student name:')
    l.append([m])
    x=int(input(f'enter number of grades for {m}:'))
    for j in range (x):
        y=float(input(f'enter grade {j+1} for {m}:'))
        l[i].append(y)
print(*l,sep=' ')
```

<p>With the following input you'll get:</p>

<pre class="lang-python prettyprint-override"><code>enter number of students>? 2
enter student name:>? fdkfsd
enter number of grades for fdkfsd:>? 2
enter grade 1 for fdkfsd:>? 1.2
enter grade 2 for fdkfsd:>? 3.3
enter student name:>? sdsa
enter number of grades for sdsa:>? 3
enter grade 1 for sdsa:>? 34.5
enter grade 2 for sdsa:>? 43.2
enter grade 3 for sdsa:>? 12.2
['fdkfsd', 1.2, 3.3] ['sdsa', 34.5, 43.2, 12.2]
</code>```

However, I would recommend using pandas.

Body:
I have the following code:

l=[]
n=int(input('enter number of list'))
[[] for i in range (n)]

for i in range (1, n+1):
    m=input('enter student')
    l.append(m)
    n=int(input('enter number of grades'))
    for i in range (1, n+1):
        y=int(input('enter grade'))
        l.append(y)
        s = ''.join(str(l))
print (*l,sep='')

and I would like to represent the input data as the following data:

Body:
I believe what you want to do is the following:

n=int(input('enter number of students'))
l=[]
for i in range (n):
    m=input('enter student name:')
    l.append([m])
    x=int(input(f'enter number of grades for {m}:'))
    for j in range (x):
        y=float(input(f'enter grade {j+1} for {m}:'))
        l[i].append(y)
print(*l,sep=' ')

With the following input you'll get:

enter number of students>? 2
enter student name:>? fdkfsd
enter number of grades for fdkfsd:>? 2
enter grade 1 for fdkfsd:>? 1.2
enter grade 2 for fdkfsd:>? 3.3
enter student name:>? sdsa
enter number of grades for sdsa:>? 3
enter grade 1 for sdsa:>? 34.5
enter grade 2 for sdsa:>? 43.2
enter grade 3 for sdsa:>? 12.2
['fdkfsd', 1.2, 3.3] ['sdsa', 34.5, 43.2, 12.2]

However, I would recommend using pandas.


问:
How to force http or https with Url.Action<tController>
I'm using the strongly typed Url.Action method from MvcContrib to do all of my url generation on my site.

For example:

```<code>Url.Action<CategoriesController>(c => c.List())
</code>```

Is there a way to force the urls generated by this method to use http or https?  Right now it seems to just be creating urls relative to the current page.  So, for example, if I'm on an https page it makes all my header and footer links use https even though I don't want those pages to be secure.

Something like:

```<code>Url.Action<CategoriesController>(c => c.List(), protocol: "https")
</code>```

答:
Unfortunately MvcContrib's Action<T> extension doesn't support generating https URLs.

Internally, this method calls into Microsoft's LinkBuilder.BuildUrlFromExpression method from the MvcFutures library which is very simplistic. It only supports generating simple relative links and doesn't support many of the features build into the normal Url.Action method including https and areas. As long as  the MvcContrib extensions rely on this method internally, it won't support these additional features.

You'd be better off sticking with Mvc's normal Url.Action if you want to take advantage of these features.

Body:
I'm using the strongly typed Url.Action method from MvcContrib to do all of my url generation on my site.

For example:

Url.Action<CategoriesController>(c => c.List())

Is there a way to force the urls generated by this method to use http or https?  Right now it seems to just be creating urls relative to the current page.  So, for example, if I'm on an https page it makes all my header and footer links use https even though I don't want those pages to be secure.

Something like:

Url.Action<CategoriesController>(c => c.List(), protocol: "https")


问:
grpc-okhttp-3 java.lang.OutOfMemoryError: Failed to allocate a 8204 byte allocation with 3880 free bytes and 3KB until OOM
I am trying to upload a file of size more than 300 MB using StreamObserver grpc it gives the following exception. I am uploading it in chunks of 512 KB.

grpc-okhttp-3 java.lang.OutOfMemoryError: Failed to allocate a 8204 byte allocation with 3880 free bytes and 3KB until OOM  at
    okio.Segment.(Segment.java:63) ~[na:0.0]    at
    okio.SegmentPool.take(SegmentPool.java:48) ~[na:0.0]  at
    okio.Buffer.writableSegment(Buffer.java:1211) ~[na:0.0]   at
    okio.Buffer.writeByte(Buffer.java:1069) ~[na:0.0]     at
    okio.RealBufferedSink.writeByte(RealBufferedSink.java:124) ~[na:0.0]
      at io.grpc.okhttp.internal.framed.Http2.writeMedium(Http2.java:773)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2.access$600(Http2.java:47)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2$Writer.frameHeader(Http2.java:578)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2$Writer.dataFrame(Http2.java:498)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2$Writer.data(Http2.java:493)
    ~[na:0.0]     at
    io.grpc.okhttp.AsyncFrameWriter$9.doRun(AsyncFrameWriter.java:148)
    ~[na:0.0]     at
    io.grpc.okhttp.AsyncFrameWriter$WriteRunnable.run(AsyncFrameWriter.java:220)
    ~[na:0.0]     at
    io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    ~[na:0.0]     at
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    ~[na:0.0]     at
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    ~[na:0.0]     at java.lang.Thread.run(Thread.java:761) ~[na:0.0]

```<code>BufferedInputStream bInputStream = new BufferedInputStream(new FileInputStream(file));

try {

int bufferSize = 512; // 512k
byte[] buffer = new byte[bufferSize];
long size = 0, originalSize = file.length();
int chunk;
do {
chunk = bInputStream.read(buffer);
size += chunk;
if (chunk > 0) {
ByteString byteString = null;
if (chunk < 512) {
byte[] remaining = Arrays.copyOfRange(buffer, 0, chunk);
byteString = ByteString.copyFrom(remaining);
 } else {
byteString = ByteString.copyFrom(buffer);
}
putRequestStreamObserver.onNext(FileUploadRequest.newBuilder()
.setFileChunk(FileChunk.newBuilder()
.setChunk(byteString)
.build())
.build());

logger.info("New Chunk!");
</code>```

i have android:hardwareAccelerated="false"  and android:largeHeap="true" in my manifest.

答:
Since the StreamObserver API is asynchronous, it can return before the message is sent. If you send too quickly, they will buffer locally.

You need to observe flow control/backpressure. You should create a ClientResponseObserver to be provided the ClientCallStreamObserver and call setOnReadyHandler() within beforeStart(). You'd then want to observe isReady() and avoid sending when it becomes false. See the manualflowcontrol example; you can ignore the disableAutoInboundFlowControl()/request() pieces; that is for receiving, not sending.

Body:
I am trying to upload a file of size more than 300 MB using StreamObserver grpc it gives the following exception. I am uploading it in chunks of 512 KB.

grpc-okhttp-3 java.lang.OutOfMemoryError: Failed to allocate a 8204 byte allocation with 3880 free bytes and 3KB until OOM  at
    okio.Segment.(Segment.java:63) ~[na:0.0]    at
    okio.SegmentPool.take(SegmentPool.java:48) ~[na:0.0]  at
    okio.Buffer.writableSegment(Buffer.java:1211) ~[na:0.0]   at
    okio.Buffer.writeByte(Buffer.java:1069) ~[na:0.0]     at
    okio.RealBufferedSink.writeByte(RealBufferedSink.java:124) ~[na:0.0]
      at io.grpc.okhttp.internal.framed.Http2.writeMedium(Http2.java:773)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2.access$600(Http2.java:47)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2$Writer.frameHeader(Http2.java:578)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2$Writer.dataFrame(Http2.java:498)
    ~[na:0.0]     at
    io.grpc.okhttp.internal.framed.Http2$Writer.data(Http2.java:493)
    ~[na:0.0]     at
    io.grpc.okhttp.AsyncFrameWriter$9.doRun(AsyncFrameWriter.java:148)
    ~[na:0.0]     at
    io.grpc.okhttp.AsyncFrameWriter$WriteRunnable.run(AsyncFrameWriter.java:220)
    ~[na:0.0]     at
    io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    ~[na:0.0]     at
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    ~[na:0.0]     at
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    ~[na:0.0]     at java.lang.Thread.run(Thread.java:761) ~[na:0.0]

BufferedInputStream bInputStream = new BufferedInputStream(new FileInputStream(file));

try {

int bufferSize = 512; // 512k
byte[] buffer = new byte[bufferSize];
long size = 0, originalSize = file.length();
int chunk;
do {
chunk = bInputStream.read(buffer);
size += chunk;
if (chunk > 0) {
ByteString byteString = null;
if (chunk < 512) {
byte[] remaining = Arrays.copyOfRange(buffer, 0, chunk);
byteString = ByteString.copyFrom(remaining);
 } else {
byteString = ByteString.copyFrom(buffer);
}
putRequestStreamObserver.onNext(FileUploadRequest.newBuilder()
.setFileChunk(FileChunk.newBuilder()
.setChunk(byteString)
.build())
.build());

logger.info("New Chunk!");

i have android:hardwareAccelerated="false"  and android:largeHeap="true" in my manifest.


问:
How to implement ajax request using Python Request
I'm trying to log into a website using  Python request. Unfortunately, it is always showing this error when printing its content.

```<code>b'<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>
</code>```

For reference my code

```<code>from requests import Session
import requests

INDEX_URL = 'https://phpzag.com/demo/ajax_login_script_with_php_jquery/index.php'
URL = 'https://phpzag.com/demo/ajax_login_script_with_php_jquery/welcome.php'
LOGIN_URL = 'https://phpzag.com/demo/ajax_login_script_with_php_jquery/login.php' # Or whatever the login request url is
payload = {'user_email': 'test@phpzag.com','password':'test'}

s = requests.Session()
user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}
t=s.post(LOGIN_URL, data=payload, headers=user_agent)
r=s.get('https://phpzag.com/demo/ajax_login_script_with_php_jquery/welcome.php',headers=user_agent,cookies=t.cookies.get_dict())
print(r.content)

</code>```

May I know what is missing and how can I get HTML code of welcome page from this

UPDATE

I'm trying to get make an API call after login authentication. However, I'm not able to succeed in login authentication. Hence I am not able to get the response of API Call. As per my thought it due to multi-factor authentication it is getting failed. I need to know how can I implement this?

For eg: www.abc.com is the URL of the website. The login is done through JS form submission Hence URL is specified in the ajax part. On the success of that, there is another third authentication party(okta) which will also verify the credentials and finally reach the home page. then I need to call the real API for my task.

But it is not working.

```<code>import requests
import sys
class Login:

     def sendRequestWithAuthentication(self,loginDetails,requestDetails):
         user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}
         action_url=loginDetails['action_url'] if 'action_url' in loginDetails.keys() else None
         pay_load=loginDetails['payload'] if 'payload' in loginDetails.keys() else None
         session_requests = requests.session()
         if action_url and pay_load:
             act_resp=session_requests.post(action_url, data=pay_load, headers=user_agent,verify=False,files=[ ])
             print(act_resp)
             auth_cookies=act_resp.cookies.get_dict()
             url,method,request_payload = requestDetails['url'],requestDetails['method'],requestDetails['payload']
             querystring=requestDetails['querystring']
             response=session_requests.get(url,headers=user_agent,cookies=auth_cookies,data=request_payload,params=querystring)
             print(response)
             return response.json()
</code>```

In the above action URL is the API given in the ajax part & in the second request, the URL is the API address for that GET.

In short, may I know how can implement multifactor authentication in python request

My Doubt

Do we need the cookies from the login form page to include in the login request

How to implement multifactor authentication in python request(Here we don't need any pin or something it is done through RSA.)Is there any need of a certificate for login as it now raising unable to validate the SSL certificate

Give a dummy example api that is implement such kind of scenario

答:
No, you make it complex.This code worked:

```<code>import requests

login_url = "https://phpzag.com/demo/ajax_login_script_with_php_jquery/login.php"
welcome_url = "https://phpzag.com/demo/ajax_login_script_with_php_jquery/welcome.php"

payload = 'user_email=test@phpzag.com&password=test&login_button='
login_headers = {
    'x-requested-with': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded', # its urlencoded instead of form-data
    'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
}
s = requests.Session()
login = s.post(login_url, headers=login_headers, data=payload) # post requests
welcome = s.get(welcome_url, headers=login_headers)
print(welcome.text)
</code>```

Result:

```<code>.....Hello, <br><br>Welcome to the members page.<br><br>
</code>```

Body:
I'm trying to log into a website using  Python request. Unfortunately, it is always showing this error when printing its content.

b'<title>Not Acceptable!</title>
Not Acceptable!

An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.

For reference my code

from requests import Session
import requests

INDEX_URL = 'https://phpzag.com/demo/ajax_login_script_with_php_jquery/index.php'
URL = 'https://phpzag.com/demo/ajax_login_script_with_php_jquery/welcome.php'
LOGIN_URL = 'https://phpzag.com/demo/ajax_login_script_with_php_jquery/login.php' # Or whatever the login request url is
payload = {'user_email': 'test@phpzag.com','password':'test'}

s = requests.Session()
user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}
t=s.post(LOGIN_URL, data=payload, headers=user_agent)
r=s.get('https://phpzag.com/demo/ajax_login_script_with_php_jquery/welcome.php',headers=user_agent,cookies=t.cookies.get_dict())
print(r.content)

May I know what is missing and how can I get HTML code of welcome page from this

UPDATE

I'm trying to get make an API call after login authentication. However, I'm not able to succeed in login authentication. Hence I am not able to get the response of API Call. As per my thought it due to multi-factor authentication it is getting failed. I need to know how can I implement this?

For eg: www.abc.com is the URL of the website. The login is done through JS form submission Hence URL is specified in the ajax part. On the success of that, there is another third authentication party(okta) which will also verify the credentials and finally reach the home page. then I need to call the real API for my task.

But it is not working.

import requests
import sys
class Login:

     def sendRequestWithAuthentication(self,loginDetails,requestDetails):
         user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}
         action_url=loginDetails['action_url'] if 'action_url' in loginDetails.keys() else None
         pay_load=loginDetails['payload'] if 'payload' in loginDetails.keys() else None
         session_requests = requests.session()
         if action_url and pay_load:
             act_resp=session_requests.post(action_url, data=pay_load, headers=user_agent,verify=False,files=[ ])
             print(act_resp)
             auth_cookies=act_resp.cookies.get_dict()
             url,method,request_payload = requestDetails['url'],requestDetails['method'],requestDetails['payload']
             querystring=requestDetails['querystring']
             response=session_requests.get(url,headers=user_agent,cookies=auth_cookies,data=request_payload,params=querystring)
             print(response)
             return response.json()

In the above action URL is the API given in the ajax part & in the second request, the URL is the API address for that GET.

In short, may I know how can implement multifactor authentication in python request

My Doubt

Do we need the cookies from the login form page to include in the login request

How to implement multifactor authentication in python request(Here we don't need any pin or something it is done through RSA.)Is there any need of a certificate for login as it now raising unable to validate the SSL certificate

Give a dummy example api that is implement such kind of scenario

Body:
No, you make it complex.This code worked:

import requests

login_url = "https://phpzag.com/demo/ajax_login_script_with_php_jquery/login.php"
welcome_url = "https://phpzag.com/demo/ajax_login_script_with_php_jquery/welcome.php"

payload = 'user_email=test@phpzag.com&password=test&login_button='
login_headers = {
    'x-requested-with': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded', # its urlencoded instead of form-data
    'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
}
s = requests.Session()
login = s.post(login_url, headers=login_headers, data=payload) # post requests
welcome = s.get(welcome_url, headers=login_headers)
print(welcome.text)

Result:

.....Hello, <br><br>Welcome to the members page.<br><br>


问:
Number of occurrences of an element in a 2d-array c++
If I'm given a 2d array say {{1,2},{2,3,4},{5,1,2,7}}, how do I count how many times an element say 1 has occurred in the array?
Is there any c++ STL function for this?

答:
Assuming that the 2d array is nested standard library containers and the outer container is called arr:

```<code>auto target = 1;
auto count = std::accumulate(
    std::begin(arr), std::end(arr), 0,
    [target](auto a, auto const &inner) {
        return a + std::count(std::begin(inner), std::end(inner), target);
    }
);
</code>```

(Demo)

This assumes C++14 support for an auto lambda parameter.

If the type of arr is int** then this will not work as std::end() will not know where each array ends, but you'd have exactly the same problem trying to iterate over the inner elements of that array manually.

Body:
Assuming that the 2d array is nested standard library containers and the outer container is called arr:

auto target = 1;
auto count = std::accumulate(
    std::begin(arr), std::end(arr), 0,
    [target](auto a, auto const &inner) {
        return a + std::count(std::begin(inner), std::end(inner), target);
    }
);

(Demo)

This assumes C++14 support for an auto lambda parameter.

If the type of arr is int** then this will not work as std::end() will not know where each array ends, but you'd have exactly the same problem trying to iterate over the inner elements of that array manually.