问:
Reusing the previous range in ex commands in VIM
Is it possible to reuse the range of ex commands in VIM?

As an example, I can write (copy) lines 4 to 10 from my current file to a new file using the following command:

```<code>:4,10w foo/bar.txt
</code>```

But what I really want to do is move the lines to a new file. I can do this like so:

```<code>:4,10w foo/bar.txt
:4,10d
</code>```

But it's a bit annoying to have to type 4,10 both times.

So I have two questions:

Generally, Is there a way to reference the previously used range in ex commands?

Specifically, if there is not a way to do (1), is there any easier way to cut and paste a number of lines from one file into a new one.

答:
In Vim 8 and NVIM 0.3.7 as of writing, you can actually edit your command list and hit enter to execute.

```<code>:4,10w foo/bar.txt
q:
</code>```

q: is to enter interactive ex command

Once you open the interactive command list, you can then edit it and press enter to execute.

I love moopet's answer though, it's efficient.

Body:
Is it possible to reuse the range of ex commands in VIM?

As an example, I can write (copy) lines 4 to 10 from my current file to a new file using the following command:

:4,10w foo/bar.txt

But what I really want to do is move the lines to a new file. I can do this like so:

:4,10w foo/bar.txt
:4,10d

But it's a bit annoying to have to type 4,10 both times.

So I have two questions:

Generally, Is there a way to reference the previously used range in ex commands?

Specifically, if there is not a way to do (1), is there any easier way to cut and paste a number of lines from one file into a new one.

Body:
In Vim 8 and NVIM 0.3.7 as of writing, you can actually edit your command list and hit enter to execute.

:4,10w foo/bar.txt
q:

q: is to enter interactive ex command

Once you open the interactive command list, you can then edit it and press enter to execute.

I love moopet's answer though, it's efficient.


来源: stackexchange

问:
percona xtrabackup incremental backup vs replication
I was playing with percona xtrabackup innobackupex for incremental backups. It is a cool tool and very efficient and effective for incremental backups. However, i could not help but wonder why doing incremental backups would be any better than just doing a regular mysql master-slave replication, and whenever needed to retrieve point-in-time data, just use the binary log?

What advantages would doing incremental backups have over doing master-slave replication? When should you choose to use over the other?

答:
They are solutions to two different problems; master-slave is redundancy and backup is resilience.

The MySQL JDBC driver has the ability to connect to many servers. If you look at the driver options (https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-url-format.html) you will notice that the host option is not only host, but hosts. If you specify the URL to both the master and the slave and something happens to the master the driver will automatically connect to the slave instead.

Backup, on the other hand, is, as was mentioned earlier, a way to recover from either a catastrophic crash (having your backups stored off-site is a must) or recover from a catastrophic mistake -- neither of which is served by a master-slave setup. (Well, technically you could have the slave at a different site but that still does not cover the mistake scenario)

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Matching values based on row number
I have 2 equally sized vectors as follows

```<code>x <- c(0,1,2,3,4,5,6,7,8,9)
y <- c(8,7,6,5,4,3,2,1,0,9)
</code>```

I want to know that in the value that is same in x and y at the exact position in both vectors

my output should be 4, 9  because in both vectors at the 5th position the number 4 exist and 10th position 9 exist

How can I go about it

Thanks in Advance

答:
You can just do:

```<code>x[x == y]

[1] 4 9
</code>```

It checks whether "x" is the same as "y":

```<code> [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE
</code>```

and then subsets "x" if TRUE.

Title: Matching values based on row number

Body:
I have 2 equally sized vectors as follows

x <- c(0,1,2,3,4,5,6,7,8,9)
y <- c(8,7,6,5,4,3,2,1,0,9)

I want to know that in the value that is same in x and y at the exact position in both vectors

my output should be 4, 9  because in both vectors at the 5th position the number 4 exist and 10th position 9 exist

How can I go about it

Thanks in Advance

Body:
You can just do:

x[x == y]

[1] 4 9

It checks whether "x" is the same as "y":

 [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE

and then subsets "x" if TRUE.


问:
PHP.. How to loop by some selected number?
I need a output like this

```<code>Number 5
Number 4
Number 9
Number 3
Number 8
Number 10
</code>```

And so on (There are more like this)

I used this code

```<code><?php

    for ($i = 0; $i <= 10 ; $i++) {
        if ($i == 5 || $i == 4 || $i == 9) {   //And so on Like this
            echo "$i<br>";
        }
    }

?>
</code>```

But the main problem is output is showing the number serially.

```<code>//It shows
Number 3
Number 4
Number 5
Number 8
Number 9
Number 10

//But I need
Number 5
Number 4
Number 9
Number 3
Number 8
Number 10
</code>```

And this takes much time to code. And it not looks so good. Sure there is a easy way out!

I am expecting something like this -

```<code>//Surely this is not right. It's just an idea.

<?php

    $x = 5,4,9,3,8,10;

    for ($i = 0; $i = $x; $i++) {
        echo "$i<br>";
    }

?>
</code>```

答:
JustOnUnderMillions's answer is corrent - You can even have access to key & value like this</p>

```<code>$x = array(
    "num1" => 1,
    "num2" => 2,
    ...
    ...
);

foreach($x as $key => $value){
    echo $key . " : " . $value . "<br>";
}
</code>```

Body:
I need a output like this

Number 5
Number 4
Number 9
Number 3
Number 8
Number 10

And so on (There are more like this)

I used this code

<?php

    for ($i = 0; $i <= 10 ; $i++) {
        if ($i == 5 || $i == 4 || $i == 9) {   //And so on Like this
            echo "$i
";
        }
    }

?>

But the main problem is output is showing the number serially.

//It shows
Number 3
Number 4
Number 5
Number 8
Number 9
Number 10

//But I need
Number 5
Number 4
Number 9
Number 3
Number 8
Number 10

And this takes much time to code. And it not looks so good. Sure there is a easy way out!

I am expecting something like this -

//Surely this is not right. It's just an idea.

<?php

    $x = 5,4,9,3,8,10;

    for ($i = 0; $i = $x; $i++) {
        echo "$i
";
    }

?>

Body:
JustOnUnderMillions's answer is corrent - You can even have access to key & value like this

$x = array(
    "num1" => 1,
    "num2" => 2,
    ...
    ...
);

foreach($x as $key => $value){
    echo $key . " : " . $value . "<br>";
}


问:
How to setup authorization in Postman in collaborative environment
I upgraded Postman to 6.2.5. It allows Teams for free user. Ok, so I created Team and started new collection within it.

On collection level I specified Authorization as OAuth 2.0, generated new Access token (using the button Get New Access Token) so it is now in Available Tokens. I don't know if the tokens are shared with other team members (I haven't invited them yet). But there is a hint

```<code>Heads up! These parameters hold sensitive data. To keep this data secure while working in a collaborative environment, we recommend using variables.
</code>```

I know the variables but don't know how to employ them in this scenario. What is the correct way to setup OAuth 2.0 Authorization in collaborative environment? (I would like to keep it on Collection level so it could be inherited down the structure of folders and requests.)

答:
Here's what they mean by that:

Source: https://learning.getpostman.com/docs/postman/team_library/sharing/#sharing-environments

1) In addition to the standard way to share an environment, Postman Pro
  and Enterprise users can also share an environment with their team.

2) From the gear icon in the upper right corner of the Postman app,
  select "Manage Environments", and click the orange Share button next
  to the environment you want to share. You will have one last
  opportunity to hide any sensitive values like passwords and access
  tokens before sharing the environment. When someone else imports the
  environment, or accesses the shared template, they can input their own
  personal information within their own version of the template.
  environment

3) Click the Share button to complete the process.

  4) Go to the Team Library to view the full list of shared team environments.

Where you have your long access token like: "a1dfgz51dgs5dg1s21gdsdg" you'll write {{accessToken}} as it will become an environment variable.

Body:
I upgraded Postman to 6.2.5. It allows Teams for free user. Ok, so I created Team and started new collection within it.

On collection level I specified Authorization as OAuth 2.0, generated new Access token (using the button Get New Access Token) so it is now in Available Tokens. I don't know if the tokens are shared with other team members (I haven't invited them yet). But there is a hint

Heads up! These parameters hold sensitive data. To keep this data secure while working in a collaborative environment, we recommend using variables.

I know the variables but don't know how to employ them in this scenario. What is the correct way to setup OAuth 2.0 Authorization in collaborative environment? (I would like to keep it on Collection level so it could be inherited down the structure of folders and requests.)


问:
Flutter showDialog, AlertDialog background gradient.
For color, I can use dialogBackgroundColor property to give AlertDialog background my own color.

I was looking to use Gradient as my background. How can I use that? DecoratedBox is something that will be needed, but I don't know what to wrap in what. Can anyone give me idea or link for the same?

答:
You can add a Container inside which will be decorated with gradient. For example:

```<code>class GradientDialog extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _GradientDialogState();
  }
}

class _GradientDialogState extends State<GradientDialog> {

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: Container(
        padding: const EdgeInsets.all(8.0),
        decoration: new BoxDecoration(
            gradient: new LinearGradient(
                colors: AppColors.BG_GRADIENT,
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter)),
        child: YourContentInside(),

      ),
      contentPadding: EdgeInsets.all(0.0),
    );
  }
}
</code>```

Open it with

```<code>showDialog(
    context: context,
    barrierDismissible: true,
    builder: (BuildContext context) {
      return GradientDialog();
    });
</code>```

Body:
You can add a Container inside which will be decorated with gradient. For example:

class GradientDialog extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _GradientDialogState();
  }
}

class _GradientDialogState extends State<GradientDialog> {

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: Container(
        padding: const EdgeInsets.all(8.0),
        decoration: new BoxDecoration(
            gradient: new LinearGradient(
                colors: AppColors.BG_GRADIENT,
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter)),
        child: YourContentInside(),

      ),
      contentPadding: EdgeInsets.all(0.0),
    );
  }
}

Open it with

showDialog(
    context: context,
    barrierDismissible: true,
    builder: (BuildContext context) {
      return GradientDialog();
    });


问:
Baguettebox doesn't show next/previous stepper
I'm using baguettebox for image  viewer. The problem is, everything works except the "next/previous" buttons. So I can't go to the next image.

```<code> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>

<script>
   baguetteBox.run('.labrador');
</script>
</code>```

and the html:

```<code><div class="labrador">
      <a href="img/portfolio/cabin.png"
       data-at-450="img/portfolio/blog.jpg"
       data-at-800="img/portfolio/cake.png"
       data-at-1366="img/portfolio/circus.png"
       data-at-1920="img/portfolio/blog.jpg">
<button type="button" class="btn btn-primary" href="#">Images</button>
            </a>
          </div>

</code>```

My result:
https://i.gyazo.com/3e9bad7f104794962a31b8ef13ce0891.png

As you can see, there aren't next/prev buttons, only the X which works fine.

答:
in your script add this {buttons: true} in baguetteBox
try this

```<code>baguetteBox.run('.labrador',{
  buttons: true
});
</code>```

baguetteBox.run('.labrador',{
  buttons: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link href="https://feimosi.github.io/baguetteBox.js/css/baguetteBox.css" rel="stylesheet"/>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>

  <div class="labrador">

<button type="button" class="btn btn-primary" href="#">Images</button>

          </div></code>```

check this example

baguetteBox.run('.labrador',{
  buttons: true
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img{
          height:50px;
          margin:10px 0;
        }</code>```

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link href="https://feimosi.github.io/baguetteBox.js/css/baguetteBox.css" rel="stylesheet"/>

```

Body:
I'm using baguettebox for image  viewer. The problem is, everything works except the "next/previous" buttons. So I can't go to the next image.

and the html:

<button type="button" class="btn btn-primary" href="#">Images</button>

My result:
https://i.gyazo.com/3e9bad7f104794962a31b8ef13ce0891.png

As you can see, there aren't next/prev buttons, only the X which works fine.

Body:
in your script add this {buttons: true} in baguetteBox
try this

baguetteBox.run('.labrador',{
  buttons: true
});

baguetteBox.run('.labrador',{
  buttons: true
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link href="https://feimosi.github.io/baguetteBox.js/css/baguetteBox.css" rel="stylesheet"/>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>

  <div class="labrador">
      <a href="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-1.jpg"
       data-at-450="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-1.jpg"
       data-at-800="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-3.jpg"
       data-at-1366="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-4.jpg"
       data-at-1920="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-2.jpg">
<button type="button" class="btn btn-primary" href="#">Images</button>
            </a>
             <a href="https://feimosi.github.io/baguetteBox.js/img/thumbs/2-1.jpg"
       data-at-450="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-1.jpg"
       data-at-800="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-3.jpg"
       data-at-1366="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-4.jpg"
       data-at-1920="https://feimosi.github.io/baguetteBox.js/img/thumbs/4-2.jpg">
            </a>
          </div>

check this example

baguetteBox.run('.labrador',{
  buttons: true
});

img{
          height:50px;
          margin:10px 0;
        }

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link href="https://feimosi.github.io/baguetteBox.js/css/baguetteBox.css" rel="stylesheet"/>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>

         <div class="labrador">
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-1.jpg" data-caption="Golden Gate Bridge">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-1.jpg" alt="Golden Gate Bridge">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-2.jpg" title="Midnight City">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-2.jpg" alt="Midnight City">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-3.jpg">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-3.jpg" alt="">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-4.jpg">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-4.jpg" alt="">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-5.jpg">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-5.jpg" alt="">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-6.jpg">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-6.jpg" alt="">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-7.jpg">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-7.jpg" alt="">
        </a>
        <a href="https://feimosi.github.io/baguetteBox.js/img/1-8.jpg">
            <img src="https://feimosi.github.io/baguetteBox.js/img/thumbs/1-8.jpg" alt="">
        </a>
    </div>


问:
Shopify Styling
Is there any way to get page identifier in css in shopify.

I want to do styling work in shopify specific page not all the pages.

So I want to specify pages, either homepage or pages I've built, blog page or shopping page etc.

答:
Every Shopify page having its own unique id, It just similar to the below

```<code><body id="home-page" class="template-index" data-gr-c-s-loaded="true" style="overflow: visible; height: auto;">
</code>```

So if you want to add any style, You can call the unique id for the particular page before the id/class you want to make any change.

For example, if you want to give background-color to class "a", the CSS be like

```<code>#home-page .a
{
background-color:red;
}
</code>```

Title: Shopify Styling

Body:
Every Shopify page having its own unique id, It just similar to the below

<body id="home-page" class="template-index" data-gr-c-s-loaded="true" style="overflow: visible; height: auto;">

So if you want to add any style, You can call the unique id for the particular page before the id/class you want to make any change.

For example, if you want to give background-color to class "a", the CSS be like

#home-page .a
{
background-color:red;
}


问:
It's listcomps or genexps when no [] or () obvious exist
When we use list comprehension like [i for i in range(10) we got a list, use generator expression like (i for i in range(10) we got a generator. If there are no [] or () obvious exist, and what we get? a list or generator?

>>> max(i for i in range(10))
9
>>> max((i for i in range(10))
9
>>> max([i for i in range(10)])
9
```

So, I just want to know max(i for i in range(10)) use list or generator when calculate max number?

答:
It uses generator you can make a proof just writing a simple function like this one:

```<code>def guess_type(obj):
    print(type(obj))
</code>```

and then calling the function with you generator:

```<code>guess_type(i for i in range(10))
guess_type((i for i in range(10)))
guess_type([i for i in range(10)])
</code>```

Body:
When we use list comprehension like [i for i in range(10) we got a list, use generator expression like (i for i in range(10) we got a generator. If there are no [] or () obvious exist, and what we get? a list or generator?

>>> max(i for i in range(10))
9
>>> max((i for i in range(10))
9
>>> max([i for i in range(10)])
9

So, I just want to know max(i for i in range(10)) use list or generator when calculate max number?

Body:
It uses generator you can make a proof just writing a simple function like this one:

def guess_type(obj):
    print(type(obj))

and then calling the function with you generator:

guess_type(i for i in range(10))
guess_type((i for i in range(10)))
guess_type([i for i in range(10)])


问:
What is the error in this code?The javascript code is not working
I am trying to change the background color of my div element onclick.But it's not working.

```<code><html>

     <head>
         <title>Event handling5</title>
         <meta charset="UTF-8">
         <style type="text/css">
         .styleClass{
             display: table-cell;
             border: 5px solid black;
             padding: 20px;
             text-align: center;
         }
         </style>
         </head>
         <body>
             <div id="DIV1" class="styleClass">DIV1
            <div id="DIV2" class="styleClass">DIV2
                <div id="DIV3" class="styleClass">DIV3

                </div>
            </div>
            </div>
            <script type="text/javascript">
            var divElements=document.getElementsByTagName('div');
            for(var i=0;i<divElements;i++){
                divElements[i].onclick=function(){
                    this.style.borderColor='red';
                    alert(this.getAttribute("id")+"Border color changed");
                }
            }
            </script>
         </body>
 </html>
</code>```

Only css functions are working and javascript function is not working.

答:
Your script is wrong .

divElements is an array so do this . Add length to the for loop

```<code><script type="text/javascript">
            var divElements=document.getElementsByTagName('div');
            for(var i=0;i<divElements.length;i++){
                divElements[i].onclick=function(){
                    this.style.borderColor='red';
                    alert(this.getAttribute("id")+"Border color changed");
                }
            }
            </script>
</code>```

Body:
I am trying to change the background color of my div element onclick.But it's not working.

         <title>Event handling5</title>
         <meta charset="UTF-8">

DIV1

DIV2

DIV3

Only css functions are working and javascript function is not working.

Body:
Your script is wrong .

divElements is an array so do this . Add length to the for loop

<script type="text/javascript">
            var divElements=document.getElementsByTagName('div');
            for(var i=0;i<divElements.length;i++){
                divElements[i].onclick=function(){
                    this.style.borderColor='red';
                    alert(this.getAttribute("id")+"Border color changed");
                }
            }
            </script>


答:
You have to use .length with divElements in for loop: Try this code now....</p>

```<code><html>

<head>
    <title>Event handling5</title>
    <meta charset="UTF-8">
    <style type="text/css">
        .styleClass {
            display: table-cell;
            border: 5px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="DIV1" class="styleClass">DIV1
        <div id="DIV2" class="styleClass">DIV2
            <div id="DIV3" class="styleClass">DIV3

            </div>
        </div>
    </div>
    <script type="text/javascript">
        var divElements = document.getElementsByTagName('div');
        for (var i = 0; i < divElements.length; i++) {
            console.log('--' + divElements[i]);
            divElements[i].onclick = function () {
                this.style.borderColor = 'red';
                alert(this.getAttribute("id") + "Border color changed");
            }
        }
    </script>
</body>

</html>
</code>```

Title: What is the error in this code?The javascript code is not working

Body:
You have to use .length with divElements in for loop: Try this code now....

<html>

<head>
    <title>Event handling5</title>
    <meta charset="UTF-8">
    <style type="text/css">
        .styleClass {
            display: table-cell;
            border: 5px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="DIV1" class="styleClass">DIV1
        <div id="DIV2" class="styleClass">DIV2
            <div id="DIV3" class="styleClass">DIV3

            </div>
        </div>
    </div>
    <script type="text/javascript">
        var divElements = document.getElementsByTagName('div');
        for (var i = 0; i < divElements.length; i++) {
            console.log('--' + divElements[i]);
            divElements[i].onclick = function () {
                this.style.borderColor = 'red';
                alert(this.getAttribute("id") + "Border color changed");
            }
        }
    </script>
</body>

</html>


问:
Cannot start Hyper-V container
enter image description hereI am trying to run the docker container but I am getting below error message as Hyper-V and Virtualization is not enabled. But I have enabled Hyper-V and virtualization. I have made the Hyper-V set-up through Bios as well as through the power shell command even though getting this below error. Kindly help me!

Error message :

C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error
  response from daemon: failed to start service utility VM
  (createreadwrite): CreateComputeSystem
  190e30a0debfc2e6f9eeedd4b1732593f80b2b478210faa5f92f8bc69c3a5686_svm:
  No hypervisor is present on this system.

[Event Detail: Cannot start
  Hyper-V Container
  '190e30a0debfc2e6f9eeedd4b1732593f80b2b478210faa5f92f8bc69c3a5686_svm'
  since the hypervisor is not running in the host. Provider:
  17103e3f-3c6e-4677-bb17-3b267eb5be57 EventID: 12001]

(extra info: {"SystemType":"container","Name":"190e30a0debfc2e6f9eeedd4b1732593f80b2b478210faa5f92f8bc69c3a5686_svm","Layers":null,"HvPartition":true,"HvRuntime":{"ImagePath":"C:\Program
  Files\LinuxContainers","LinuxInitrdFile":"initrd.img","LinuxKernelFile":"kernel"},"ContainerType":"linux","TerminateOnLastHandleClosed":true}).

See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run
  --help'.

答:
Try this:

Go to turn windows features on or off (if you write optionalfeatures in cmd you got that files)

There search for a file with the name windows hypervisor platform

Enable it.

Reboot.

Title: Cannot start Hyper-V container


问:
Create a restricted area
I'm trying to build a restricted area for a website in which only the registered user can see his personal profile and his posts. The staff users can see all users profile and related posts.

This is models.py:

```<code>...
from django.contrib.auth.models import User

class Post(models.Model):
    authorized_users = models.ManyToManyField(
        User,
        related_name="user_set",
        default=1,
        )
    title = models.CharField(max_length=100)
...
</code>```

As you can see one post can have more then one author(authorized_users).

This is views.py:

```<code>from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User

@permission_required('user.is_staff', raise_exception=True)
def listUsers(request):
    users_list = User.objects.all()
    context = {"users_list": users_list}
    template = 'usermanager/users_list.html'
    return render(request, template, context)

@permission_required('post.authorized_users=username', raise_exception=True)
def singleUser(request, username):
    user_single = get_object_or_404(User, username=username)
    context = {"user_single": user_single}
    template = 'usermanager/single_user.html'
    return render(request, template, context)

def listPost(request):
    posts_list = Post.objects.all()
    context = {"posts_list": posts_list}
    template = 'usermanager/list_post.html'
    return render(request, template, context)

def singlePost(request, pk):
    post_single = get_object_or_404(Post, pk=pk)
    context = {"post_single": post_single}
    template = 'usermanager/single_post.html'
    return render(request, template, context)
</code>```

If I'm logged in as staff I can see the list of users(view listUsers) and the single user with all his posts(view singleUser); but if I'm logged in as non staff user I see the message 403 Forbidden. This isn't what I want to see becouse I want to see only my profile and my posts.

How I can solve this?

答:
I've solved is using this:

```<code>def userProfile(request, username):
    if request.user.username == username:
        user_details = get_object_or_404(UserProfile, username=username)
    elif request.user.is_staff:
        user_details = get_object_or_404(UserProfile, username=username)
    else:
        raise PermissionDenied
    context = {
        "user_details": user_details,
        }
    template = 'usermanager/reading/user_profile.html'
    return render(request, template, context)
</code>```

It is possible to use the same strategy for the others views.

Title: Create a restricted area

Body:
I'm trying to build a restricted area for a website in which only the registered user can see his personal profile and his posts. The staff users can see all users profile and related posts.

This is models.py:

...
from django.contrib.auth.models import User

class Post(models.Model):
    authorized_users = models.ManyToManyField(
        User,
        related_name="user_set",
        default=1,
        )
    title = models.CharField(max_length=100)
...

As you can see one post can have more then one author(authorized_users).

This is views.py:

from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User

@permission_required('user.is_staff', raise_exception=True)
def listUsers(request):
    users_list = User.objects.all()
    context = {"users_list": users_list}
    template = 'usermanager/users_list.html'
    return render(request, template, context)

@permission_required('post.authorized_users=username', raise_exception=True)
def singleUser(request, username):
    user_single = get_object_or_404(User, username=username)
    context = {"user_single": user_single}
    template = 'usermanager/single_user.html'
    return render(request, template, context)

def listPost(request):
    posts_list = Post.objects.all()
    context = {"posts_list": posts_list}
    template = 'usermanager/list_post.html'
    return render(request, template, context)

def singlePost(request, pk):
    post_single = get_object_or_404(Post, pk=pk)
    context = {"post_single": post_single}
    template = 'usermanager/single_post.html'
    return render(request, template, context)

If I'm logged in as staff I can see the list of users(view listUsers) and the single user with all his posts(view singleUser); but if I'm logged in as non staff user I see the message 403 Forbidden. This isn't what I want to see becouse I want to see only my profile and my posts.

How I can solve this?

Body:
I've solved is using this:

def userProfile(request, username):
    if request.user.username == username:
        user_details = get_object_or_404(UserProfile, username=username)
    elif request.user.is_staff:
        user_details = get_object_or_404(UserProfile, username=username)
    else:
        raise PermissionDenied
    context = {
        "user_details": user_details,
        }
    template = 'usermanager/reading/user_profile.html'
    return render(request, template, context)

It is possible to use the same strategy for the others views.


问:
How can I call printf normally in assembly without @PLT but just call printf with -l option in gcc with standard library,
I want to call printf in assembly and link it using gcc -l option with standard library, But it says:

```<code>  Symbol `printf' causes overflow in R_X86_64_PC32 relocation
  Segmentation fault (core dumped)
</code>```

this is How i compile:

```<code>   gcc mod.s -l:libc.so -o mod
</code>```

when I replace libc.so with libc.a, It still shows Sementation fault

```<code> .file  "mod.c"
.text
.section    .rodata
.LC0:
   .string  "%d"
.text
.globl  main
.type   main, @function
main:
pushq   %rbp
movq    %rsp, %rbp
subq    $16, %rsp
movl    $3, -8(%rbp)
movl    $2, -4(%rbp)
movl    -8(%rbp), %eax
cltd
idivl   -4(%rbp)
movl    %edx, -4(%rbp)
movl    -4(%rbp), %eax
movl    %eax, %esi
leaq    .LC0(%rip), %rdi
movl    $0, %eax
call    printf
movl    $0, %eax
leave
ret
.size   main, .-main
.ident  "GCC: (Ubuntu 7.4.0-1ubuntu1~18.04) 7.4.0"
.section    .note.GNU-stack,"",@progbits
</code>```

When I add @PLT after printf it goes right, But I just want to use -l in gcc

答:
You don't need -llibc, gcc already links that by default.

The problem here is that modern GCC defaults to making a PIE executable (position-independent), which is an ELF "shared object".  The linker treats it more like a library and doesn't automatically create PLT stubs for calls to undefined symbol names.  (I don't think this behaviour is necessary, ld could let you do this.)

The easy solution here is gcc -no-pie -fno-pie -o mod mod.s

Then you can write call printf and it Just Works.

With that command line, you'll create a dynamically-linked ELF executable.  The  linker rewrites your call printf to call printf@plt for you (disassemble it and see, with objdump -drwC to print relocations.).  The offset between the libc load address and your code's address is not a link-time constant.  (And could be larger than 2^32 anyway).

If you use -static, the call printf resolves to the actual address of the printf definition copied into your executable from libc.a.

I'm guessing that the option of building a static or dynamic executable from the same source is why ld is willing to rewrite calls to PLT stubs for ELF executables but not ELF shared objects (like PIE executables).

See 32-bit absolute addresses no longer allowed in x86-64 Linux? for more about PIE.

The other way to call shared library functions is call *printf@GOTPCREL(%rip), like gcc does if you compile with -fno-plt.  This bypasses the PLT entirely, just doing a call through the function pointer in the GOT (which you access with a RIP-relative addressing mode).

The NASM version of this is call [rel printf wrt ..got]

as an alternative to call printf wrt ..plt.  Can't call C standard library function on 64-bit Linux from assembly (yasm) code

Body:
I want to call printf in assembly and link it using gcc -l option with standard library, But it says:

  Symbol `printf' causes overflow in R_X86_64_PC32 relocation
  Segmentation fault (core dumped)

this is How i compile:

   gcc mod.s -l:libc.so -o mod

when I replace libc.so with libc.a, It still shows Sementation fault

 .file  "mod.c"
.text
.section    .rodata
.LC0:
   .string  "%d"
.text
.globl  main
.type   main, @function
main:
pushq   %rbp
movq    %rsp, %rbp
subq    $16, %rsp
movl    $3, -8(%rbp)
movl    $2, -4(%rbp)
movl    -8(%rbp), %eax
cltd
idivl   -4(%rbp)
movl    %edx, -4(%rbp)
movl    -4(%rbp), %eax
movl    %eax, %esi
leaq    .LC0(%rip), %rdi
movl    $0, %eax
call    printf
movl    $0, %eax
leave
ret
.size   main, .-main
.ident  "GCC: (Ubuntu 7.4.0-1ubuntu1~18.04) 7.4.0"
.section    .note.GNU-stack,"",@progbits

When I add @PLT after printf it goes right, But I just want to use -l in gcc


问:
How to do Method/Field Injection in Scala using Guice?
I am trying to do either method or field injection in Scala. I am using the Play Framework, which uses Guice for injecting. I have tried field injection like:

@Inject val cache: DefaultSyncCacheApi = null
```

<p>like detailed here, but whenever I try to test it I get a <code>NullPointerException</code>. I have also tried method injection, like:</p>

<pre class="lang-scala prettyprint-override"><code>@Inject
def method(id: String, cache: DefaultSyncCacheApi): Boolean = {
   val cachedItem = cache.get(id)
   cachedItem.isDefined
}
</code>```

to no avail either. I would have to pass in the cache from another place as well.

I have also tried to use overloaded methods and injecting separately, such as:

val cache: DefaultSyncCacheApi //this will not work if it is not an abstract class

@Inject //either injecting here
def methodA(id: String): Boolean = {
   methodB(string, cache)
}

@Inject //or injecting here
def methodB(id: String, cache: DefaultSyncCacheApi): Boolean = {
   //same logic as 'method' above
}
```

to no avail. Is there a clear cut way to do method or field injection without causing an NPE?

答:
Your problem is probably that these fields are injected too early (before Guice has setup the Application).

So what you can try is to change all vals to lazy vals.

I have to say I only use Injection in the constructor which works perfectly. Your Example

```<code>class HomeController @Inject()(id: String, cache: DefaultSyncCacheApi)
</code>```

However for the id you will need a Provider in your Module. And as it is a String you should name it. Here an example:

Module.scala

```<code>  @Provides
  @Named("myIdentitfier")
  def provideId(): String = {
    IdCreator.nextId().
  }
</code>```

HomeController.scala

```<code>class HomeController @Inject()(@Named("myIdentitfier") id: String, cache: DefaultSyncCacheApi)
</code>```

Body:
I am trying to do either method or field injection in Scala. I am using the Play Framework, which uses Guice for injecting. I have tried field injection like:

@Inject val cache: DefaultSyncCacheApi = null

like detailed here, but whenever I try to test it I get a NullPointerException. I have also tried method injection, like:

@Inject
def method(id: String, cache: DefaultSyncCacheApi): Boolean = {
   val cachedItem = cache.get(id)
   cachedItem.isDefined
}

to no avail either. I would have to pass in the cache from another place as well.

I have also tried to use overloaded methods and injecting separately, such as:

val cache: DefaultSyncCacheApi //this will not work if it is not an abstract class

@Inject //either injecting here
def methodA(id: String): Boolean = {
   methodB(string, cache)
}

@Inject //or injecting here
def methodB(id: String, cache: DefaultSyncCacheApi): Boolean = {
   //same logic as 'method' above
}

to no avail. Is there a clear cut way to do method or field injection without causing an NPE?

Body:
Your problem is probably that these fields are injected too early (before Guice has setup the Application).

So what you can try is to change all vals to lazy vals.

I have to say I only use Injection in the constructor which works perfectly. Your Example

class HomeController @Inject()(id: String, cache: DefaultSyncCacheApi)

However for the id you will need a Provider in your Module. And as it is a String you should name it. Here an example:

Module.scala

  @Provides
  @Named("myIdentitfier")
  def provideId(): String = {
    IdCreator.nextId().
  }

HomeController.scala

class HomeController @Inject()(@Named("myIdentitfier") id: String, cache: DefaultSyncCacheApi)


问:
Expo Developer Tools is disconnected from Expo CLI. Use the expo start command to start the CLI again
i'm new to react-native i installed expo as mention in official page like below.

```<code>npm install expo-cli --global

expo init my-new-project
cd my-new-project

expo start(run this in my cmd)
</code>```

Get this error in cmd

[09:53:03] TypeError: Cannot read property 'compile' of undefined

```<code>npm start(i did this too)
</code>```

Get this error in cmd

[09:47:17] TypeError: Cannot read property 'compile' of undefined

I get this error in my Browser
Expo Developer Tools is disconnected from Expo CLI. Use the expo start command to start the CLI again.

答:
Something is missing, Run following </p>

```<code>npm install
</code>```

<p>and then </p>

```<code>expo start
</code>```

Body:
i'm new to react-native i installed expo as mention in official page like below.

npm install expo-cli --global

expo init my-new-project
cd my-new-project

expo start(run this in my cmd)

Get this error in cmd

[09:53:03] TypeError: Cannot read property 'compile' of undefined

npm start(i did this too)

Get this error in cmd

[09:47:17] TypeError: Cannot read property 'compile' of undefined

I get this error in my Browser
Expo Developer Tools is disconnected from Expo CLI. Use the expo start command to start the CLI again.

Body:
Something is missing, Run following

npm install

and then

expo start


问:
Stop return back to first function
I'd like to stop returning to the first function. Look at my example for better understanding:</p>

```<code>function function1() {
    function2();
    console.log('back after called function'); // shoudn't log if condition is true
}

function function2() {
    if (condition === true) { // if condition is true, stop right here (no callback to function1)
        return false;
    } else {
        // callback is allowed
    }
}
</code>```

答:
The simplest way should be something like:

```<code>function function1() {
    if (function2()) {
        console.log('back after called function');
    }
}
</code>```

As Jack Bashford suggested (but wrote in the wrong way), you could use the ternary operator:

```<code>function function1() {
    function2()? console.log('back after called function') : return;
}
</code>```

Or, for a more complex code process, you could use a callback function:

```<code>function function1() {
    function2(function(error) {
        if (!error) {
            console.log('back after called function');
        }
    });
}

function function2(callback) {
    if (condition === true) {
        callback("Error: condition false");
    } else {
        callback(null);
    }
}
</code>```

EDIT:

Using my last option you can do exactly what you asked: do not return to function1:

```<code>function function1() {
    function2(function() {
        console.log('back after called function');
    });
}

function function2(callback) {
    if (condition === true) {
        return;
    } else {
        callback();
    }
}
</code>```

But I think for the sake of good practice you should always call the callback.

Title: Stop return back to first function

Body:
I'd like to stop returning to the first function. Look at my example for better understanding:

function function1() {
    function2();
    console.log('back after called function'); // shoudn't log if condition is true
}

function function2() {
    if (condition === true) { // if condition is true, stop right here (no callback to function1)
        return false;
    } else {
        // callback is allowed
    }
}

Body:
The simplest way should be something like:

function function1() {
    if (function2()) {
        console.log('back after called function');
    }
}

As Jack Bashford suggested (but wrote in the wrong way), you could use the ternary operator:

function function1() {
    function2()? console.log('back after called function') : return;
}

Or, for a more complex code process, you could use a callback function:

function function1() {
    function2(function(error) {
        if (!error) {
            console.log('back after called function');
        }
    });
}

function function2(callback) {
    if (condition === true) {
        callback("Error: condition false");
    } else {
        callback(null);
    }
}

EDIT:

Using my last option you can do exactly what you asked: do not return to function1:

function function1() {
    function2(function() {
        console.log('back after called function');
    });
}

function function2(callback) {
    if (condition === true) {
        return;
    } else {
        callback();
    }
}

But I think for the sake of good practice you should always call the callback.


问:
What does a vertical bar mean in a SQL function call?
I'm learning SQL, and a lot of the examples have | (vertical bar) in function parameters.  What does it represent?  Like this:

```<code>TRUNC(column|expression, decimal places)
</code>```

between column and expression.

答: It means "or".  In that example you could have a column name or an expression.</p>

Body:
I'm learning SQL, and a lot of the examples have | (vertical bar) in function parameters.  What does it represent?  Like this:

TRUNC(column|expression, decimal places)

between column and expression.


答:
The problem is your for-loop

```<code>for(var i=0; i<divElements; i++){
/* Some Code */
}
</code>```

Her you try to say, do it as long as i is smaller divElements. Problem here is, divElements itself don't give you any numeric value (for length). It's just the array.

To get it work you have to get the array length (https://www.w3schools.com/jsref/jsref_length_array.asp) So you need divElements.length

In you for loop it would look like this.

```<code>for(var i=0;i<divElements.length;i++){
/* Some Code */
}
</code>```

Here you can try out a working example and play with it: https://jsfiddle.net/Hoargarth/fdcL14wy/1/

And here if you just wanna see it running:

     <title>Event handling5</title>
     <meta charset="UTF-8">

DIV1

DIV2

DIV3

     ```

Body:
The problem is your for-loop

for(var i=0; i<divElements; i++){
/* Some Code */
}

Her you try to say, do it as long as i is smaller divElements. Problem here is, divElements itself don't give you any numeric value (for length). It's just the array.

To get it work you have to get the array length (https://www.w3schools.com/jsref/jsref_length_array.asp) So you need divElements.length

In you for loop it would look like this.

for(var i=0;i<divElements.length;i++){
/* Some Code */
}

Here you can try out a working example and play with it: https://jsfiddle.net/Hoargarth/fdcL14wy/1/

And here if you just wanna see it running:

 <head>
     <title>Event handling5</title>
     <meta charset="UTF-8">
     <style type="text/css">
     .styleClass{
         display: table-cell;
         border: 5px solid black;
         padding: 20px;
         text-align: center;
     }
     </style>
     </head>
     <body>
         <div id="DIV1" class="styleClass">DIV1
        <div id="DIV2" class="styleClass">DIV2
            <div id="DIV3" class="styleClass">DIV3

            </div>
        </div>
        </div>
        <script type="text/javascript">
        var divElements=document.getElementsByTagName('div');
        for(var i=0;i<divElements.length;i++){
            divElements[i].onclick=function(){
                this.style.borderColor='red';
                alert(this.getAttribute("id")+"Border color changed");
            }
        }
        </script>
     </body>


答:
I think it is impossible for function2 not to return to function1

function function1() {
    if (function2()) return;
    console.log('back after called function'); // shoudn't log if condition is true
}

Title: Stop return back to first function


问:
Trying to get back button on webKit
Real newbie here,
Have added a webpage to my main controller which takes up full page,
but there is no back button
the webview just take over the whole screen
i would like to get a back button on it if possible
will add code below</p>

```<code>import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://google.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}
</code>```

答:
It really depends on where you want to go back:

if you want to dismiss the current view controller, you can push the view controller with a navigation controller, you will get a back button for free.

Or if you don't have a navigation controller, you can add a button in you view controller, for example drag a UIButton onto you view controller in the storyboard, and create an outlet var in your code:

```<code>@IBOutlet var backButton: UIButton!
</code>```

And then adding a goBack function for the button:

```<code>@IBAction func goBack() {
    presentingViewController?.dismiss(animated: true, completion: nil)
}
</code>```

If by going back, you mean going back in the history of the web browsing, you can drag a UIButton onto you view controller in the storyboard, and create an outlet var in your code:

```<code>@IBOutlet var backButton: UIButton!
</code>```

And then adding a goBack function for the button:

```<code>@IBAction func goBack() {
    webView.goBack()
}
</code>```

Title: Trying to get back button on webKit

Body:
Real newbie here,
Have added a webpage to my main controller which takes up full page,
but there is no back button
the webview just take over the whole screen
i would like to get a back button on it if possible
will add code below

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://google.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

Body:
It really depends on where you want to go back:

if you want to dismiss the current view controller, you can push the view controller with a navigation controller, you will get a back button for free.

Or if you don't have a navigation controller, you can add a button in you view controller, for example drag a UIButton onto you view controller in the storyboard, and create an outlet var in your code:

@IBOutlet var backButton: UIButton!

And then adding a goBack function for the button:

@IBAction func goBack() {
    presentingViewController?.dismiss(animated: true, completion: nil)
}

If by going back, you mean going back in the history of the web browsing, you can drag a UIButton onto you view controller in the storyboard, and create an outlet var in your code:

@IBOutlet var backButton: UIButton!

And then adding a goBack function for the button:

@IBAction func goBack() {
    webView.goBack()
}


问:
Finding frequency of maximum digit in a number
```<code>#include <stdio.h>

int main(void)
{
    int i=0,max=0;
    long long int n,p;
    scanf("%lld",&n);
    while(n>0)
    {
        p=n%10;
        if(p==max)
        {
            i++;
        }
        else if(p>max)
        {
            max=p;
            i=1;
        }
        n/=10;
    }
    printf("%d",i);
    return 0;
}
</code>```

The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111 , it doesn't give the proper result . I've seen similar problem in this site but those were written in different language. I want to know where the problem lies for large number .

Thanks...

N.B. : It would be helpful if anyone could give alternate solutions . I'm still a newbie,so it would help me to understand things more deeply.

答:
The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111

8687557576676885 requires 53 bits but 11111111111111111111111111111111 need 104 bits, too much for your long long probably on 64bits

It would be helpful if anyone could give alternate solutions

Rather than to use scanf use fgets or equivalent then strtoll and you will be able to detect the overflow looking at errno

However in your case you do not need to extract the number, just work on the string, for instance to not be limited by any size :

```<code>#include <stdio.h>

int main(void)
{
  int i=0,max=-1;
  int c;

  while ((c = fgetc(stdin)) && (c != EOF) && (c != '\n')) {
    if ((c < '0') || (c > '9')) {
      printf("'%c' is not a valid digit\n", c);
      return -1;
    }
    c -= '0';
    if(c==max)
    {
      i++;
    }
    else if(c>max)
    {
      max=c;
      i=1;
    }
  }
  if (max != -1)
    printf("%d times %d\n",i, max);
  return 0;
}
</code>```

Compilation and executions :

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra m.c
pi@raspberrypi:/tmp $ ./a.out
8687557576676885
4 times 8
pi@raspberrypi:/tmp $ ./a.out
111111111111111111111111111111111111111111
42 times 1
</code>```

Body:
#include <stdio.h>

int main(void)
{
    int i=0,max=0;
    long long int n,p;
    scanf("%lld",&n);
    while(n>0)
    {
        p=n%10;
        if(p==max)
        {
            i++;
        }
        else if(p>max)
        {
            max=p;
            i=1;
        }
        n/=10;
    }
    printf("%d",i);
    return 0;
}

The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111 , it doesn't give the proper result . I've seen similar problem in this site but those were written in different language. I want to know where the problem lies for large number .

Thanks...

N.B. : It would be helpful if anyone could give alternate solutions . I'm still a newbie,so it would help me to understand things more deeply.

Body:
The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111

8687557576676885 requires 53 bits but 11111111111111111111111111111111 need 104 bits, too much for your long long probably on 64bits

It would be helpful if anyone could give alternate solutions

Rather than to use scanf use fgets or equivalent then strtoll and you will be able to detect the overflow looking at errno

However in your case you do not need to extract the number, just work on the string, for instance to not be limited by any size :

#include <stdio.h>

int main(void)
{
  int i=0,max=-1;
  int c;

  while ((c = fgetc(stdin)) && (c != EOF) && (c != '\n')) {
    if ((c < '0') || (c > '9')) {
      printf("'%c' is not a valid digit\n", c);
      return -1;
    }
    c -= '0';
    if(c==max)
    {
      i++;
    }
    else if(c>max)
    {
      max=c;
      i=1;
    }
  }
  if (max != -1)
    printf("%d times %d\n",i, max);
  return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra m.c
pi@raspberrypi:/tmp $ ./a.out
8687557576676885
4 times 8
pi@raspberrypi:/tmp $ ./a.out
111111111111111111111111111111111111111111
42 times 1


问:
How do i write a timer countdown in C#?
I am trying to write a countdown in C#, but I can't get it to work. I want it to countdown from 1:00 to 0:00.
How can that be accomplished?</p>

```<code>public int tidTilbage = 60;

private void Form1_Load(object sender, EventArgs e)
    {
        Timer tidTimer = new Timer();
        tidTimer.Interval = (1000);
        tidTimer.Tick += new EventHandler(Timer_Tick);
        tidTimer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        tidTilbage = tidTilbage - 1;

        label1.Text.ToString();
    }
</code>```

答:
try changing the

```<code> label1.Text.ToString();
</code>```

to

```<code>  label1.Text = tidTilbage.ToString();
</code>```

Title: How do i write a timer countdown in C#?

Body:
I am trying to write a countdown in C#, but I can't get it to work. I want it to countdown from 1:00 to 0:00.
How can that be accomplished?

public int tidTilbage = 60;

private void Form1_Load(object sender, EventArgs e)
    {
        Timer tidTimer = new Timer();
        tidTimer.Interval = (1000);
        tidTimer.Tick += new EventHandler(Timer_Tick);
        tidTimer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        tidTilbage = tidTilbage - 1;

        label1.Text.ToString();
    }

Body:
try changing the

 label1.Text.ToString();

to

  label1.Text = tidTilbage.ToString();


问:
@query with only sort by . Without limit
I`m trying to do select with @Query annotation with only sort by.

I searched a lot but without any luck. Currently I implemented it to work but with Pageable class that want me to set limit . Is there any other way to accomplish that without limit? Only normal select with order by

```<code>@Query("SELECT new com.concretepage.entity.Employee(employeeId,firstName,lastName,salary)FROM Employee")
    List<Employee> getBySalaryOrdered(Pageable pageable);

</code>```

I`m searching for way to do it without Pageable. I want only to have sort without any limits

答:
Instead of using @Query annotation you could use query generation based on a method definition inside the interface that extends  CrudRepository or JpaRepository.

In your case, it would be:

```<code>List<Employee> findAllByOrderBySalaryAsc();
</code>```

Check docs for more.

Body:
I`m trying to do select with @Query annotation with only sort by.

I searched a lot but without any luck. Currently I implemented it to work but with Pageable class that want me to set limit . Is there any other way to accomplish that without limit? Only normal select with order by

@Query("SELECT new com.concretepage.entity.Employee(employeeId,firstName,lastName,salary)FROM Employee")
    List<Employee> getBySalaryOrdered(Pageable pageable);

I`m searching for way to do it without Pageable. I want only to have sort without any limits

Body:
Instead of using @Query annotation you could use query generation based on a method definition inside the interface that extends  CrudRepository or JpaRepository.

In your case, it would be:

List<Employee> findAllByOrderBySalaryAsc();

Check docs for more.


问:
show multiple password fields with single checkbox
I am trying to make a code that shows multiple password fields into text.
Here is the approach that I made, my focus is on making the code as short as possible, but it seems like am doing something wrong with the approaches that I took.

Approach 1:

```<code><input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" onchange="document.getElementByClassName('.password').type = this.checked ? 'text' : 'password'"> Show password
</code>```

Above Approach is working perfectly if I use getElementById but not with getElementByClassName

Approach 2: fiddle

```<code>Password: <input type="password" value="FakePSW" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password
<script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
</code>```

The same issue happens with this approach as well if using getElementByClassName instead.

答:
The function you are looking for is named getElementsByClassName. It returns a collection, so you have to loop over the results to apply your transformations to all of them.

adapted Approach 2: fiddle

```<code>Password: <input type="password" value="FakePSW" id="myInput" class="password">
<input type="password" value="FakePSW" id="myInput2" class="password"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password

<script>
function myFunction() {
  var passwordFields = document.getElementsByClassName("password");
  for (let x of passwordFields) {
    if (x.type === "password") {
      x.type = "text";
    } else {
      x.type = "password";
    }
  }
}
</script>
</code>```

PS: The original question referenced jquery, but since the code contained pure javascript, so does this answer.

Body:
I am trying to make a code that shows multiple password fields into text.
Here is the approach that I made, my focus is on making the code as short as possible, but it seems like am doing something wrong with the approaches that I took.

Approach 1:

<input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" onchange="document.getElementByClassName('.password').type = this.checked ? 'text' : 'password'"> Show password

Above Approach is working perfectly if I use getElementById but not with getElementByClassName

Approach 2: fiddle

Password: <input type="password" value="FakePSW" id="myInput">

<input type="checkbox" onclick="myFunction()">Show Password

The same issue happens with this approach as well if using getElementByClassName instead.

Body:
The function you are looking for is named getElementsByClassName. It returns a collection, so you have to loop over the results to apply your transformations to all of them.

adapted Approach 2: fiddle

Password: <input type="password" value="FakePSW" id="myInput" class="password">
<input type="password" value="FakePSW" id="myInput2" class="password"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password

<script>
function myFunction() {
  var passwordFields = document.getElementsByClassName("password");
  for (let x of passwordFields) {
    if (x.type === "password") {
      x.type = "text";
    } else {
      x.type = "password";
    }
  }
}
</script>

PS: The original question referenced jquery, but since the code contained pure javascript, so does this answer.


问:
Trying to understand a recursive function to reverse a string
I can't understand why this code works. Do characters in the string get removed because they are being passed by reference? I see no decrement or such, so I find that really confusing. Also, is the string getting reversed because of the lifo nature of the function call stack?</p>

```<code> void reverse(const char * const sPtr){
   if('\0' == sPtr[0])
     return;
     else{
       reverse(&sPtr[1]);
       putchar(sPtr[0]);
    }
 }
</code>```

答:
Nothing is being removed. But the pointer being passed into the function is changed, in this expression:

```<code>&sPtr[1]
</code>```

… which is equivalent to

```<code>sPtr + 1
</code>```

So each recursive call increments the pointer by one, thus causing the recursive calls to traverse your char array.

As for why this causes the reversal of the string, the LIFO nature of the stack is indeed the reason. Your function first calls itself recursively and then outputs the current character using putchar. This has thus the effect of outputting the characters in reverse order.

Body:
I can't understand why this code works. Do characters in the string get removed because they are being passed by reference? I see no decrement or such, so I find that really confusing. Also, is the string getting reversed because of the lifo nature of the function call stack?

 void reverse(const char * const sPtr){
   if('\0' == sPtr[0])
     return;
     else{
       reverse(&sPtr[1]);
       putchar(sPtr[0]);
    }
 }

Body:
Nothing is being removed. But the pointer being passed into the function is changed, in this expression:

&sPtr[1]

… which is equivalent to

sPtr + 1

So each recursive call increments the pointer by one, thus causing the recursive calls to traverse your char array.

As for why this causes the reversal of the string, the LIFO nature of the stack is indeed the reason. Your function first calls itself recursively and then outputs the current character using putchar. This has thus the effect of outputting the characters in reverse order.


问:
can we store multiple data on single id in database?
I have this following.

```<code>id name
1  Dhiraj Dhanaji Desai.
2  ram patil
3  aman mehta
</code>```

I want this.

```<code>id name
1  Dhiraj Dhanaji Desai.
   ram patil
   aman mehta
</code>```

答:
You can store JSON value in a field for having "multiple" data in a single field.

for example, you can store this value:

```<code>{"id":1,"name":"Dhiraj Dhanaji Desai"}
</code>```

and get it back parsing JSON. (for example php have a function json_decode)

references:

https://www.php.net/manual/en/function.json-decode.php

https://www.json.org

Body:
I have this following.

id name
1  Dhiraj Dhanaji Desai.
2  ram patil
3  aman mehta

I want this.

id name
1  Dhiraj Dhanaji Desai.
   ram patil
   aman mehta

Body:
You can store JSON value in a field for having "multiple" data in a single field.

for example, you can store this value:

{"id":1,"name":"Dhiraj Dhanaji Desai"}

and get it back parsing JSON. (for example php have a function json_decode)

references:

https://www.php.net/manual/en/function.json-decode.php

https://www.json.org


问:
Getting row Count only returns value of 1
I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.

```<code>Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
    Dim sqlda2 As New SqlDataAdapter(comm2)
    Dim dt2 As New DataTable
    sqlda2.Fill(dt2)
    Dim recordcount As Integer = dt2.Rows.Count
    messagecountlbl.Text = recordcount
</code>```

this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.

I have also tried the Select Count statement and it does the same thing.

Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.

```<code>Dim sqlresult As Object
    Dim constring As String = "Connection string goes here"
    Dim dbcon As SqlConnection = New SqlConnection(constring)
    Dim sql As New SqlCommand
    dbcon.Open()
    sql.Connection = dbcon
    sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
    sqlresult = sql.ExecuteScalar
    messagecountlbl.Text = sqlresult
</code>```

答:
It looks like you're missing a single quote at the beginning of the word "Unread".</p>

```<code>...& "' AND columnname = 'Unread'")
</code>```

Body:
I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.

Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
    Dim sqlda2 As New SqlDataAdapter(comm2)
    Dim dt2 As New DataTable
    sqlda2.Fill(dt2)
    Dim recordcount As Integer = dt2.Rows.Count
    messagecountlbl.Text = recordcount

this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.

I have also tried the Select Count statement and it does the same thing.

Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.

Dim sqlresult As Object
    Dim constring As String = "Connection string goes here"
    Dim dbcon As SqlConnection = New SqlConnection(constring)
    Dim sql As New SqlCommand
    dbcon.Open()
    sql.Connection = dbcon
    sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
    sqlresult = sql.ExecuteScalar
    messagecountlbl.Text = sqlresult

Body:
It looks like you're missing a single quote at the beginning of the word "Unread".

...& "' AND columnname = 'Unread'")


问:
Cython on Termux. ImportError: dynamic module does not define module export function (PyInit_libmc)
I'm trying to use python/cython on Android within Termux. I got python, cython pip-installed - with no 'obvious' problems. Now I have two simple test-snippets

A 'main' file mct.py

```<code>import os
hm=os.path.expanduser('~')
os.chdir(hm+'/projects/python1/v1')
from libmc import sq

print(sq(4))
</code>```

and a stupidly trivial cython 'library'

```<code>cpdef double sq(double x):
  return x*x
</code>```

I compiled the library the simple way (without the distutils fuzz), i.e. I do

```<code>cython -3 mct.pyx

clang -shared -pthread -fpic -fwrapv -fno-strict-aliasing -O2 -Wall -I /data/data/com.termux/files/usr/include/python3.7m/ -o libmc.so -lpython3 mc.c
</code>```

With that I do get a libmc.so in my projects root. However then, when I try

```<code>python mct.py
</code>```

I get

```<code>Traceback (most recent call last):
  File "mct.py", line 4, in <module>
    from libmc import sq
ImportError: dynamic module does not define module export function (PyInit_libmc)
</code>```

Now I'm stuck. What am I missing here? Any suggestions to get this fixed?

Mark

PS.: Just to clarify, 'normal' Python seems works well for me on that Android-box.

答: The name of the pyx for needs to be libmc. Cython will generate an init function based on the filename which currently won't match what the .so file turns out to be called (when Python imports compiled modules it looks for an init function based on the .so filename).

Body:
I'm trying to use python/cython on Android within Termux. I got python, cython pip-installed - with no 'obvious' problems. Now I have two simple test-snippets

A 'main' file mct.py

import os
hm=os.path.expanduser('~')
os.chdir(hm+'/projects/python1/v1')
from libmc import sq

print(sq(4))

and a stupidly trivial cython 'library'

cpdef double sq(double x):
  return x*x

I compiled the library the simple way (without the distutils fuzz), i.e. I do

cython -3 mct.pyx

clang -shared -pthread -fpic -fwrapv -fno-strict-aliasing -O2 -Wall -I /data/data/com.termux/files/usr/include/python3.7m/ -o libmc.so -lpython3 mc.c

With that I do get a libmc.so in my projects root. However then, when I try

python mct.py

I get

Traceback (most recent call last):
  File "mct.py", line 4, in <module>
    from libmc import sq
ImportError: dynamic module does not define module export function (PyInit_libmc)

Now I'm stuck. What am I missing here? Any suggestions to get this fixed?

Mark

PS.: Just to clarify, 'normal' Python seems works well for me on that Android-box.


答:
No, it doesn't get deleted.

In every recursive call, you want to progress to the next character, which is done here:

```<code>reverse(&sPtr[1]); // you pass a parameter the 1st character of where you point to now
</code>```

Title: Trying to understand a recursive function to reverse a string

Body:
No, it doesn't get deleted.

In every recursive call, you want to progress to the next character, which is done here:

reverse(&sPtr[1]); // you pass a parameter the 1st character of where you point to now


问:
How to create Regular expression to extract a value from the string response?
How to find the regular expression to extract the Value Tag from the following response?</p>

```<code><CustomFieldList>
    <CustomField>
        <Name>OFFER_META_DATA</Name>
        <Value>
            SE7gOMOEOfvKjka8b+8k4SqccKEAB8ZjUqDl0Mv7OZeKEITd0l2rAFAL1XAxgzE8+lLt6XaR9IYDY0MmUaRfGXkiE/SOmYzMB+DccN2V1cOfsBav1BNaUsubTKW79qtXwwNcg4saeZZSqaiAVDJIFFUZq+u0UhqE6aZ2EbdwELyHZPP9HfHSRHCV9ihjlHvGHKRYdL2j4PvE5O5eg3ajmSTmI5aRAG42+epkCroTRDglUmCnHMTlA3VvSvtBV/fq9lI54JqqkSDj+83tKhclvZWPw08zu6drpp6PeZwmG1UwlmokLAwI0QCxYjnJEYwt7Ikt1sm8JqWzUPoVGHJoyw==%~~`%~~~~~~~%^**(%$#%ZWZby8uQ7CCjcQDbU7exlCDAXUeQ47bkD2kcxkobEQ9y1IBlPDpk7JEquCdxOnkKCRi9y8AswLegW98YyC+OAUoMCvN5XWYMJOmGK2gkj+5xzUbGZy9GS7ov4DQ+rPaHqvomADIKxXNw52ZSda/cwvfcUETGxi6yDcEgdIXj4abWQTNUGoSE34oHPNZ0CamHd1ZCZr36DqrIRXO595aTTAQX2E/ZUvoXnxT79ezoCOkt/xGOAEGKUjCUYYGnOAmHARf5t4aqK9Z+JhB8wVtT9KaD7xunGePjINmQrEYDeosEGrFyQ0OQWfwDyjQmA+GFbFRoabZgg3tkjCNCWEXI6Q==
        </Value>
    </CustomField>
</CustomFieldList>
</code>```

答:
You have to use multi select regular expression. Please find below the required expression for your case</p>

```<code>(?ms)<Value>(.*?)</Value>
</code>```

Body:
How to find the regular expression to extract the Value Tag from the following response?

<CustomFieldList>
    <CustomField>
        <Name>OFFER_META_DATA</Name>
        <Value>
            SE7gOMOEOfvKjka8b+8k4SqccKEAB8ZjUqDl0Mv7OZeKEITd0l2rAFAL1XAxgzE8+lLt6XaR9IYDY0MmUaRfGXkiE/SOmYzMB+DccN2V1cOfsBav1BNaUsubTKW79qtXwwNcg4saeZZSqaiAVDJIFFUZq+u0UhqE6aZ2EbdwELyHZPP9HfHSRHCV9ihjlHvGHKRYdL2j4PvE5O5eg3ajmSTmI5aRAG42+epkCroTRDglUmCnHMTlA3VvSvtBV/fq9lI54JqqkSDj+83tKhclvZWPw08zu6drpp6PeZwmG1UwlmokLAwI0QCxYjnJEYwt7Ikt1sm8JqWzUPoVGHJoyw==%~~`%~~~~~~~%^**(%$#%ZWZby8uQ7CCjcQDbU7exlCDAXUeQ47bkD2kcxkobEQ9y1IBlPDpk7JEquCdxOnkKCRi9y8AswLegW98YyC+OAUoMCvN5XWYMJOmGK2gkj+5xzUbGZy9GS7ov4DQ+rPaHqvomADIKxXNw52ZSda/cwvfcUETGxi6yDcEgdIXj4abWQTNUGoSE34oHPNZ0CamHd1ZCZr36DqrIRXO595aTTAQX2E/ZUvoXnxT79ezoCOkt/xGOAEGKUjCUYYGnOAmHARf5t4aqK9Z+JhB8wVtT9KaD7xunGePjINmQrEYDeosEGrFyQ0OQWfwDyjQmA+GFbFRoabZgg3tkjCNCWEXI6Q==
        </Value>
    </CustomField>
</CustomFieldList>

Body:
You have to use multi select regular expression. Please find below the required expression for your case

(?ms)<Value>(.*?)</Value>


问:
SVG ForeignObjects draw over all other elements in Chrome
Update 22 April, 2016: Nothing new, I just decided to check up on this, and post a quick code update. Firefox still performs as expected, IE doesn't perform at all, and Chrome 50.0.2661.87 m still behaves the same as it did last year. The fiddle link and code below have been updated to reflect the latest working version (in Firefox).

Background:
I'm playing with rendering a canvas + HTML elements to PNG. Of course, this means creating an interim SVG which hosts the HTML as a foreignObject.

The whole thing is a layer-cake of elements. I have a background, a layer of elements, the canvas, and another layer of elements.  You can see what it looks like in the snippet below.

I could have approached this in two ways:

Write everything, including the image, to a single SVG, which will be rendered to a canvas.

Write two SVGs, one for the background and the items behind the image, and another for the items in front of the image, then draw the back SVG, then the image, then the front SVG to the target canvas.

I chose option 1 because it seemed straightforward and simple.

The problem: SVG draw order is supposed to follow the DOM order, but in the case of Chrome (38 & Canary), it acts like it's rendering the foreignObjects after it renders the native objects, completely covering the native objects. (The code works as expected in Firefox, and fails miserably in IE11.) So who is correct? Is this a bug in Chrome, Firefox, or are neither of them handling this properly? Or is there some user error that I missed?

Thanks!

function putAnImageInTheCanvas() {
  var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  var svgNS = svg.namespaceURI;
  svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  svg.setAttribute('height', '310');
  svg.setAttribute('width', '310');
  svg.setAttribute('version', '1.1');

  var svgRect = document.createElementNS(svgNS, 'rect');
  svgRect.setAttribute('x', '125');
  svgRect.setAttribute('y', '25');
  svgRect.setAttribute('height', '250');
  svgRect.setAttribute('width', '50');
  svgRect.setAttribute('fill', 'rgb(0,255,255)');

  svg.appendChild(svgRect);

  var dataSrc = 'data:image/svg+xml;base64,' + btoa(svg.outerHTML);

  var img = document.createElement('img');
  img.setAttribute('src', dataSrc);

  var c = document.getElementById('myCanvas');
  var ctx = c.getContext("2d");
  img.addEventListener('load', function() {
    ctx.drawImage(img, 0, 0, 310, 310, 0, 0, 310, 310);
  });
}

function render(darwBackground) {
  var myCanvas = document.getElementById('myCanvas');

  var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  var svgNS = svg.namespaceURI;
  svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  svg.setAttribute('height', '310');
  svg.setAttribute('width', '310');
  svg.setAttribute('version', '1.1');

  var background = document.getElementById('main').cloneNode();
  background.setAttribute("xmlns", document.documentElement.namespaceURI);
  var svgFO_BG = document.createElementNS(svgNS, 'foreignObject');
  svgFO_BG.setAttribute('height', '310');
  svgFO_BG.setAttribute('width', '310');
  svgFO_BG.setAttribute('x', '0');
  svgFO_BG.setAttribute('y', '0');
  svgFO_BG.innerHTML = background.outerHTML.replace(/(\r\n|\n|\r|\t|[\s]{2,})/gm, '');

  var back = document.getElementById('back').cloneNode(true);
  back.setAttribute("xmlns", document.documentElement.namespaceURI);
  var svgFO_AB = document.createElementNS(svgNS, 'foreignObject');
  svgFO_AB.setAttribute('height', '310');
  svgFO_AB.setAttribute('width', '310');
  svgFO_AB.setAttribute('x', '0');
  svgFO_AB.setAttribute('y', '0');
  svgFO_AB.innerHTML = back.outerHTML.replace(/(\r\n|\n|\r|\t|[\s]{2,})/gm, '');

  var front = document.getElementById('front').cloneNode(true);
  front.setAttribute("xmlns", document.documentElement.namespaceURI);
  var svgFO_AA = document.createElementNS(svgNS, 'foreignObject');
  svgFO_AA.setAttribute('height', '310');
  svgFO_AA.setAttribute('width', '310');
  svgFO_AA.setAttribute('x', '0');
  svgFO_AA.setAttribute('y', '0');
  svgFO_AA.innerHTML = front.outerHTML.replace(/(\r\n|\n|\r|\t|[\s]{2,})/gm, '');

  var svgImage = document.createElementNS(svgNS, 'image');
  svgImage.setAttribute('xlink:href', myCanvas.toDataURL());
  svgImage.setAttribute('x', '0');
  svgImage.setAttribute('y', '0');
  svgImage.setAttribute('height', '310');
  svgImage.setAttribute('width', '310');

  var g = document.createElementNS(svgNS, 'g');
  if (darwBackground) {
    g.appendChild(svgFO_BG);
    svg.appendChild(g);
  }

  g = document.createElementNS(svgNS, 'g');
  g.appendChild(svgFO_AB);
  svg.appendChild(g);

  g = document.createElementNS(svgNS, 'g');
  g.appendChild(svgImage);
  svg.appendChild(g);

  g = document.createElementNS(svgNS, 'g');
  g.appendChild(svgFO_AA);
  svg.appendChild(g);

  var data = svg.outerHTML;

  document.getElementById('renderOutput').innerHTML = data;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="load canvas image" onclick="putAnImageInTheCanvas();" />
<input type="button" value="render with background" onclick="render(true);" />
<input type="button" value="render without background" onclick="render(false);" />
<h2>Preview:</h2>
<div id="main" style="border: 5px blue solid; width: 300px; height: 300px; background: yellow; position: relative; top: 0; left: 0; overflow: hidden;">
  <canvas id="myCanvas" height="300px" width="300px" style="display: block; position: absolute; top: 0; left: 0; z-index: 1;"></canvas>
  <div id="back" style="position: relative; top: 0; left: 0;">
    <div style=" width: 100px; position: absolute; top: 75px; left: 75px; font-size: 20px; font-family: times; z-index: 0;">
      <div style="background: orange;">BACK</div>
    </div>
  </div>
  <div id="front" style="position: relative; top: 0; left: 0;">
    <div style=" width: 100px; position: absolute; top: 150px; left: 150px; font-size: 20px; font-family: times; z-index: 2;">
      <div style="background: lime;">FRONT</div>
    </div>
  </div>
</div>
<h2>Render Result:</h2>
<div id="renderOutput">

</div></code>```

答:
This is still an issue in Chrome version 76 (canary) and official ver. 74.

The workaround I used was to place the canvas before the svg, not in the foreignObject inside it and wrap the whole content with a div with position: relative so the svg can be positioned absolute to be always above the canvas.

Also the wrapper div must have some additional css (flexbox in my case) so the canvas lays below the svg.

See it on CodePen

```<code>    <div class="wrapper" style="width: 400px; height: 400px; display: flex; position: relative;">
      <canvas></canvas>
      <svg style="position: absolute" width="100%" height="100%">
        <g transform="translate(200, 200)">
          <circle cx="0" cy="0" r="30" fill="red"/>
          <text x="-12" y="2" font-family="Arial" font-size="15px" fill="black">SVG</text>
        </g>
      </svg>
    </div>

    <script>
      const canvas = document.querySelector('canvas');
      const ctx = canvas.getContext('2d');

      canvas.width = 400;
      canvas.height = 400;

      ctx.fillStyle = "pink"
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = 'black';
      ctx.font = '20px Arial';
      ctx.fillText("Canvas", canvas.width / 2, 50);
    </script>
</code>```

The con of this approach is you won't access any canvas mouse/screen event listeners if the canvas is covered by the svg at 100%.

Body:
Update 22 April, 2016: Nothing new, I just decided to check up on this, and post a quick code update. Firefox still performs as expected, IE doesn't perform at all, and Chrome 50.0.2661.87 m still behaves the same as it did last year. The fiddle link and code below have been updated to reflect the latest working version (in Firefox).

Background:
I'm playing with rendering a canvas + HTML elements to PNG. Of course, this means creating an interim SVG which hosts the HTML as a foreignObject.

The whole thing is a layer-cake of elements. I have a background, a layer of elements, the canvas, and another layer of elements.  You can see what it looks like in the snippet below.

I could have approached this in two ways:

Write everything, including the image, to a single SVG, which will be rendered to a canvas.

Write two SVGs, one for the background and the items behind the image, and another for the items in front of the image, then draw the back SVG, then the image, then the front SVG to the target canvas.

I chose option 1 because it seemed straightforward and simple.

The problem: SVG draw order is supposed to follow the DOM order, but in the case of Chrome (38 & Canary), it acts like it's rendering the foreignObjects after it renders the native objects, completely covering the native objects. (The code works as expected in Firefox, and fails miserably in IE11.) So who is correct? Is this a bug in Chrome, Firefox, or are neither of them handling this properly? Or is there some user error that I missed?

Thanks!

function putAnImageInTheCanvas() {
  var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  var svgNS = svg.namespaceURI;
  svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  svg.setAttribute('height', '310');
  svg.setAttribute('width', '310');
  svg.setAttribute('version', '1.1');

  var svgRect = document.createElementNS(svgNS, 'rect');
  svgRect.setAttribute('x', '125');
  svgRect.setAttribute('y', '25');
  svgRect.setAttribute('height', '250');
  svgRect.setAttribute('width', '50');
  svgRect.setAttribute('fill', 'rgb(0,255,255)');

  svg.appendChild(svgRect);

  var dataSrc = 'data:image/svg+xml;base64,' + btoa(svg.outerHTML);

  var img = document.createElement('img');
  img.setAttribute('src', dataSrc);

  var c = document.getElementById('myCanvas');
  var ctx = c.getContext("2d");
  img.addEventListener('load', function() {
    ctx.drawImage(img, 0, 0, 310, 310, 0, 0, 310, 310);
  });
}

function render(darwBackground) {
  var myCanvas = document.getElementById('myCanvas');

  var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  var svgNS = svg.namespaceURI;
  svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  svg.setAttribute('height', '310');
  svg.setAttribute('width', '310');
  svg.setAttribute('version', '1.1');

  var background = document.getElementById('main').cloneNode();
  background.setAttribute("xmlns", document.documentElement.namespaceURI);
  var svgFO_BG = document.createElementNS(svgNS, 'foreignObject');
  svgFO_BG.setAttribute('height', '310');
  svgFO_BG.setAttribute('width', '310');
  svgFO_BG.setAttribute('x', '0');
  svgFO_BG.setAttribute('y', '0');
  svgFO_BG.innerHTML = background.outerHTML.replace(/(\r\n|\n|\r|\t|[\s]{2,})/gm, '');

  var back = document.getElementById('back').cloneNode(true);
  back.setAttribute("xmlns", document.documentElement.namespaceURI);
  var svgFO_AB = document.createElementNS(svgNS, 'foreignObject');
  svgFO_AB.setAttribute('height', '310');
  svgFO_AB.setAttribute('width', '310');
  svgFO_AB.setAttribute('x', '0');
  svgFO_AB.setAttribute('y', '0');
  svgFO_AB.innerHTML = back.outerHTML.replace(/(\r\n|\n|\r|\t|[\s]{2,})/gm, '');

  var front = document.getElementById('front').cloneNode(true);
  front.setAttribute("xmlns", document.documentElement.namespaceURI);
  var svgFO_AA = document.createElementNS(svgNS, 'foreignObject');
  svgFO_AA.setAttribute('height', '310');
  svgFO_AA.setAttribute('width', '310');
  svgFO_AA.setAttribute('x', '0');
  svgFO_AA.setAttribute('y', '0');
  svgFO_AA.innerHTML = front.outerHTML.replace(/(\r\n|\n|\r|\t|[\s]{2,})/gm, '');

  var svgImage = document.createElementNS(svgNS, 'image');
  svgImage.setAttribute('xlink:href', myCanvas.toDataURL());
  svgImage.setAttribute('x', '0');
  svgImage.setAttribute('y', '0');
  svgImage.setAttribute('height', '310');
  svgImage.setAttribute('width', '310');

  var g = document.createElementNS(svgNS, 'g');
  if (darwBackground) {
    g.appendChild(svgFO_BG);
    svg.appendChild(g);
  }

  g = document.createElementNS(svgNS, 'g');
  g.appendChild(svgFO_AB);
  svg.appendChild(g);

  g = document.createElementNS(svgNS, 'g');
  g.appendChild(svgImage);
  svg.appendChild(g);

  g = document.createElementNS(svgNS, 'g');
  g.appendChild(svgFO_AA);
  svg.appendChild(g);

  var data = svg.outerHTML;

  document.getElementById('renderOutput').innerHTML = data;
}

<input type="button" value="load canvas image" onclick="putAnImageInTheCanvas();" />
<input type="button" value="render with background" onclick="render(true);" />
<input type="button" value="render without background" onclick="render(false);" />

Preview:

  <canvas id="myCanvas" height="300px" width="300px" style="display: block; position: absolute; top: 0; left: 0; z-index: 1;"></canvas>

BACK

FRONT

Render Result:

Body:
This is still an issue in Chrome version 76 (canary) and official ver. 74.

The workaround I used was to place the canvas before the svg, not in the foreignObject inside it and wrap the whole content with a div with position: relative so the svg can be positioned absolute to be always above the canvas.

Also the wrapper div must have some additional css (flexbox in my case) so the canvas lays below the svg.

See it on CodePen

    <div class="wrapper" style="width: 400px; height: 400px; display: flex; position: relative;">
      <canvas></canvas>
      <svg style="position: absolute" width="100%" height="100%">
        <g transform="translate(200, 200)">
          <circle cx="0" cy="0" r="30" fill="red"/>
          <text x="-12" y="2" font-family="Arial" font-size="15px" fill="black">SVG</text>
        </g>
      </svg>
    </div>

    <script>
      const canvas = document.querySelector('canvas');
      const ctx = canvas.getContext('2d');

      canvas.width = 400;
      canvas.height = 400;

      ctx.fillStyle = "pink"
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = 'black';
      ctx.font = '20px Arial';
      ctx.fillText("Canvas", canvas.width / 2, 50);
    </script>

The con of this approach is you won't access any canvas mouse/screen event listeners if the canvas is covered by the svg at 100%.


问:
How to assign a property value of an IQueryable<T>?
I'm using Entity Framework 4.1 Code First.  In my entity, I have three date/time properties:

```<code>public class MyEntity
{
    [Key]
    public Id { get; set; }

    public DateTime FromDate { get; set; }

    public DateTime ToDate { get; set; }

    [NotMapped]
    public DateTime? QueryDate { get; set; }

    // and some other fields, of course
}
</code>```

In the database, I always have the From/To dates populated.  I query against them using a simple where clause.  But in the result set, I want to include the date I queried for. I need to persist this for some other business logic to work.

I'm working on an extension method to do this, but I'm running into problems:

```<code>public static IQueryable<T> WhereDateInRange<T>(this IQueryable<T> queryable, DateTime queryDate) where T : MyEntity
{
    // this part works fine
    var newQueryable = queryable.Where(e => e.FromDate <= queryDate &&
                                            e.ToDate >= queryDate);

    // in theory, this is what I want to do
    newQueryable = newQueryable.Select(e =>
                                           {
                                               e.QueryDate = queryDate;
                                               return e;
                                           });
    return newQueryable;
}
</code>```

This doesn't work.  It works if I use an IEnumerable, but I want to keep it as IQueryable so everything runs on the database side, and this extention method can still be used in any part of another query.  When it's IQueryable, I get a compile error of the following:

A lambda expression with a statement body cannot be converted to an expression tree

If this was SQL, I would just do something like this:

```<code>SELECT *, @QueryDate as QueryDate
FROM MyEntities
WHERE @QueryDate BETWEEN FromDate AND ToDate
</code>```

So the question is, how can I transform the expression tree I already have to include this extra property assignment?  I have looked into IQueryable.Expression and IQueryable.Provider.CreateQuery - there's a solution in there somewhere.  Maybe an assignment expression can be appended to the existing expression tree?  I'm not familiar enough with the expression tree methods to figure this out.  Any ideas?

Example Usage

To clarify, the goal is to be able to perform something like this:

```<code>var entity = dataContext.Set<MyEntity>()
                        .WhereDateInRange(DateTime.Now)
                        .FirstOrDefault();
</code>```

And have the DateTime.Now persisited into the QueryDate of the resulting row, WITHOUT having more than one row returned from the database query.  (With the IEnumerable solution, multiple rows are returned before FirstOrDefault picks the row we want.)

Another Idea

I could go ahead and map QueryDate like a real field, and set its DatabaseGeneratedOption to Computed.  But then I would need some way to inject the "@QueryDate as QueryDate" into the SQL created by EF's select statements.  Since it's computed, EF won't try to provide values during update or insert.  So how could I go about injecting custom SQL into the select statements?

答:
No, I don't think there is a solution. It is true that you can modify expression tree but you will get exactly the same exception as you got with your linq query because that query actually is what you will build in expression tree. The problem is not in expression tree but in the mapping. EF can't map QueryData to the result. Moreover you are trying to do projection. Projection can't be done to mapped entity and anonymous type can't be returned from the method.

You can off course do the select you mentioned but simply you can't map it to your entity. You must create a new type for that:

```<code>var query = from x in context.MyData
            where x.FromDate <= queryDate && x.ToDate >= queryDate
            select new MyDateWrapper
                {
                   MyData = x,
                   QueryDate = queryDate
                };
</code>```

Body:
I'm using Entity Framework 4.1 Code First.  In my entity, I have three date/time properties:

public class MyEntity
{
    [Key]
    public Id { get; set; }

    public DateTime FromDate { get; set; }

    public DateTime ToDate { get; set; }

    [NotMapped]
    public DateTime? QueryDate { get; set; }

    // and some other fields, of course
}

In the database, I always have the From/To dates populated.  I query against them using a simple where clause.  But in the result set, I want to include the date I queried for. I need to persist this for some other business logic to work.

I'm working on an extension method to do this, but I'm running into problems:

public static IQueryable<T> WhereDateInRange<T>(this IQueryable<T> queryable, DateTime queryDate) where T : MyEntity
{
    // this part works fine
    var newQueryable = queryable.Where(e => e.FromDate <= queryDate &&
                                            e.ToDate >= queryDate);

    // in theory, this is what I want to do
    newQueryable = newQueryable.Select(e =>
                                           {
                                               e.QueryDate = queryDate;
                                               return e;
                                           });
    return newQueryable;
}

This doesn't work.  It works if I use an IEnumerable, but I want to keep it as IQueryable so everything runs on the database side, and this extention method can still be used in any part of another query.  When it's IQueryable, I get a compile error of the following:

A lambda expression with a statement body cannot be converted to an expression tree

If this was SQL, I would just do something like this:

SELECT *, @QueryDate as QueryDate
FROM MyEntities
WHERE @QueryDate BETWEEN FromDate AND ToDate

So the question is, how can I transform the expression tree I already have to include this extra property assignment?  I have looked into IQueryable.Expression and IQueryable.Provider.CreateQuery - there's a solution in there somewhere.  Maybe an assignment expression can be appended to the existing expression tree?  I'm not familiar enough with the expression tree methods to figure this out.  Any ideas?

Example Usage

To clarify, the goal is to be able to perform something like this:

var entity = dataContext.Set<MyEntity>()
                        .WhereDateInRange(DateTime.Now)
                        .FirstOrDefault();

And have the DateTime.Now persisited into the QueryDate of the resulting row, WITHOUT having more than one row returned from the database query.  (With the IEnumerable solution, multiple rows are returned before FirstOrDefault picks the row we want.)

Another Idea

I could go ahead and map QueryDate like a real field, and set its DatabaseGeneratedOption to Computed.  But then I would need some way to inject the "@QueryDate as QueryDate" into the SQL created by EF's select statements.  Since it's computed, EF won't try to provide values during update or insert.  So how could I go about injecting custom SQL into the select statements?

Body:
No, I don't think there is a solution. It is true that you can modify expression tree but you will get exactly the same exception as you got with your linq query because that query actually is what you will build in expression tree. The problem is not in expression tree but in the mapping. EF can't map QueryData to the result. Moreover you are trying to do projection. Projection can't be done to mapped entity and anonymous type can't be returned from the method.

You can off course do the select you mentioned but simply you can't map it to your entity. You must create a new type for that:

var query = from x in context.MyData
            where x.FromDate <= queryDate && x.ToDate >= queryDate
            select new MyDateWrapper
                {
                   MyData = x,
                   QueryDate = queryDate
                };