问:
Adding a video to the animating frame
We can add an image to the frame by Adding the image as the background of the content but I can't find a solution to add a video using the same approach without a hand. (I just want a frame for my video.)

I want to add an id to the added video too.

Here is the CodePen.

And here is exact same code:

setTimeout(function(){
MovieClip();

}, 2000)

function MovieClip() {
  let video = document.createElement('video');
  video.setAttribute("id", "clip"); // Note: add id to video so that we can interact with it later
  document.getElementsByClassName('content')[0].appendChild(video);

  let clip = document.getElementById("clip");

  let source = document.createElement('source');
  source.src = `http://clips.vorwaerts-gmbh.de/VfE_html5.mp4`;

  /* Adding video as the background of the content not working
  let node = document.getElementsByClassName('content')[0];
  node.style.background = `url(http://clips.vorwaerts-gmbh.de/VfE_html5.mp4) center/cover`; */

  source.type = 'video/mp4';
  video.appendChild(source);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* html {
 overflow: hidden;
 background-color: #121518;
}

video {
 position: absolute;
 overflow: hidden;
 left: 0vw;
 top: 0vh;
 width: 90%;
 height: auto;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 margin-left: auto;
 margin-right: auto;
 margin-top: auto;
 margin-bottom: auto;
  border: 0.1vw dashed #eb4034;

} */

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #11151a;
}

.box {
 border-radius: 1.31vh;
 position: relative;
 overflow: hidden;
}

.box::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:
    repeating-linear-gradient(-45deg, white 0  0.48828125vw, hotpink 0 0.9765625vw) 0 0/1.380859375vw 1.380859375vw;
    width: calc(100% + 1.380859375vw);
    height: calc(100% + 1.380859375vw);
    transform: translate(-1.380859375vw, -1.380859375vw);
    will-change: transform;
    animation: animate 4s linear infinite;
  }

.box .content {
  width: calc(90vw -  1.953125vw);
  height: calc(85vh - 3.9318479685452163vh);
  /*border-radius: 1.31vh;*/
  box-shadow: 0 0 0.262vh deeppink, 0 0 0.6553vh rgba(0, 0, 0, 1), inset 0 0 0.6553vh rgba(0, 0, 0, 1);
  margin:1vh;
}

@keyframes animate {
  to {
    transform: translate(0, 0);
    will-change: transform;
  }
}

.stopAnimation:after {
  -webkit-transform: none !important;
  transform: none !important;
}</code>```

<!DOCTYPE html>

```

Please run the CodePen, I think there is two main issues with my code:

First: the video doesn't fill the frame

Second: Compare the top corner with the bottom, as you see the lower corner is covered unexpectedly with the video.

答:
To use en element in the same style as a background-image, use the CSS object-fit property. When the value is cover the element will cover the entire width and height of the parent. Works great for images and video's.

Although this will mess up your ratio. Adding a padding-top to the .content element with a value of 56.25% will give you a 16:9 aspect ratio. You can calculate these easily by doing (height / width) * 100.

Also since you are practically lazy loading the video, wait for adding the video whenever the canplaythrough event has triggered. This event is fired whenever the video has buffered enough to play till the end of the video, with the current speed of streaming data.

The video won't load in the snippet, but if you'll paste this in your codepen or project it works.

setTimeout(function() {
  MovieClip();
}, 2000)

const content = document.querySelector('.content');

function MovieClip() {
  let video = document.createElement('video');
  video.controls = 'true';
  video.addEventListener('canplaythrough', function() {
    content.appendChild(video);
  });

  video.id = 'clip'; // Note: add id to video so that we can interact with it later

  let source = document.createElement('source');
  source.src = `http://clips.vorwaerts-gmbh.de/VfE_html5.mp4`;
  source.type = 'video/mp4';
  video.appendChild(source);
  video.load();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>video {
  position: absolute;
  top: 0;
  left: 0;
  max-width: 100%;
  max-height: 100%;
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
  object-fit: cover;
}

body {
  height: 100vh;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #11151a;
}

.box {
  border-radius: 1.31vh;
  position: relative;
  overflow: hidden;
}

.box::after {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: repeating-linear-gradient(-45deg, white 0 0.48828125vw, hotpink 0 0.9765625vw) 0 0/1.380859375vw 1.380859375vw;
  width: calc(100% + 1.380859375vw);
  height: calc(100% + 1.380859375vw);
  transform: translate(-1.380859375vw, -1.380859375vw);
  will-change: transform;
  animation: animate 4s linear infinite;
}

.box .content {
  position: relative;
  width: calc(90vw - 1.953125vw);

  /**
   * Remove padding and use the height
   * if you don't want to maintain the aspect ratio
  height: calc(85vh - 3.9318479685452163vh); */

  padding-top: 56.25%;
  /*border-radius: 1.31vh;*/
  box-shadow: 0 0 0.262vh deeppink, 0 0 0.6553vh rgba(0, 0, 0, 1), inset 0 0 0.6553vh rgba(0, 0, 0, 1);
  margin: 1vh;
}

@keyframes animate {
  to {
    transform: translate(0, 0);
    will-change: transform;
  }
}

.stopAnimation:after {
  -webkit-transform: none !important;
  transform: none !important;
}</code>```

<!DOCTYPE html>

```

Title: Adding a video to the animating frame

Body:
We can add an image to the frame by Adding the image as the background of the content but I can't find a solution to add a video using the same approach without a hand. (I just want a frame for my video.)

I want to add an id to the added video too.

Here is the CodePen.

And here is exact same code:

setTimeout(function(){
MovieClip();

}, 2000)

function MovieClip() {
  let video = document.createElement('video');
  video.setAttribute("id", "clip"); // Note: add id to video so that we can interact with it later
  document.getElementsByClassName('content')[0].appendChild(video);

  let clip = document.getElementById("clip");

  let source = document.createElement('source');
  source.src = `http://clips.vorwaerts-gmbh.de/VfE_html5.mp4`;

  /* Adding video as the background of the content not working
  let node = document.getElementsByClassName('content')[0];
  node.style.background = `url(http://clips.vorwaerts-gmbh.de/VfE_html5.mp4) center/cover`; */

  source.type = 'video/mp4';
  video.appendChild(source);

}

/* html {
 overflow: hidden;
 background-color: #121518;
}

video {
 position: absolute;
 overflow: hidden;
 left: 0vw;
 top: 0vh;
 width: 90%;
 height: auto;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 margin-left: auto;
 margin-right: auto;
 margin-top: auto;
 margin-bottom: auto;
  border: 0.1vw dashed #eb4034;

} */

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #11151a;
}

.box {
 border-radius: 1.31vh;
 position: relative;
 overflow: hidden;
}

.box::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:
    repeating-linear-gradient(-45deg, white 0  0.48828125vw, hotpink 0 0.9765625vw) 0 0/1.380859375vw 1.380859375vw;
    width: calc(100% + 1.380859375vw);
    height: calc(100% + 1.380859375vw);
    transform: translate(-1.380859375vw, -1.380859375vw);
    will-change: transform;
    animation: animate 4s linear infinite;
  }

.box .content {
  width: calc(90vw -  1.953125vw);
  height: calc(85vh - 3.9318479685452163vh);
  /*border-radius: 1.31vh;*/
  box-shadow: 0 0 0.262vh deeppink, 0 0 0.6553vh rgba(0, 0, 0, 1), inset 0 0 0.6553vh rgba(0, 0, 0, 1);
  margin:1vh;
}

@keyframes animate {
  to {
    transform: translate(0, 0);
    will-change: transform;
  }
}

.stopAnimation:after {
  -webkit-transform: none !important;
  transform: none !important;
}

<!DOCTYPE html>

Please run the CodePen, I think there is two main issues with my code:

First: the video doesn't fill the frame

Second: Compare the top corner with the bottom, as you see the lower corner is covered unexpectedly with the video.

Body:
To use en element in the same style as a background-image, use the CSS object-fit property. When the value is cover the element will cover the entire width and height of the parent. Works great for images and video's.

Although this will mess up your ratio. Adding a padding-top to the .content element with a value of 56.25% will give you a 16:9 aspect ratio. You can calculate these easily by doing (height / width) * 100.

Also since you are practically lazy loading the video, wait for adding the video whenever the canplaythrough event has triggered. This event is fired whenever the video has buffered enough to play till the end of the video, with the current speed of streaming data.

The video won't load in the snippet, but if you'll paste this in your codepen or project it works.

setTimeout(function() {
  MovieClip();
}, 2000)

const content = document.querySelector('.content');

function MovieClip() {
  let video = document.createElement('video');
  video.controls = 'true';
  video.addEventListener('canplaythrough', function() {
    content.appendChild(video);
  });

  video.id = 'clip'; // Note: add id to video so that we can interact with it later

  let source = document.createElement('source');
  source.src = `http://clips.vorwaerts-gmbh.de/VfE_html5.mp4`;
  source.type = 'video/mp4';
  video.appendChild(source);
  video.load();
}

video {
  position: absolute;
  top: 0;
  left: 0;
  max-width: 100%;
  max-height: 100%;
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
  object-fit: cover;
}

body {
  height: 100vh;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #11151a;
}

.box {
  border-radius: 1.31vh;
  position: relative;
  overflow: hidden;
}

.box::after {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: repeating-linear-gradient(-45deg, white 0 0.48828125vw, hotpink 0 0.9765625vw) 0 0/1.380859375vw 1.380859375vw;
  width: calc(100% + 1.380859375vw);
  height: calc(100% + 1.380859375vw);
  transform: translate(-1.380859375vw, -1.380859375vw);
  will-change: transform;
  animation: animate 4s linear infinite;
}

.box .content {
  position: relative;
  width: calc(90vw - 1.953125vw);

  /**
   * Remove padding and use the height
   * if you don't want to maintain the aspect ratio
  height: calc(85vh - 3.9318479685452163vh); */

  padding-top: 56.25%;
  /*border-radius: 1.31vh;*/
  box-shadow: 0 0 0.262vh deeppink, 0 0 0.6553vh rgba(0, 0, 0, 1), inset 0 0 0.6553vh rgba(0, 0, 0, 1);
  margin: 1vh;
}

@keyframes animate {
  to {
    transform: translate(0, 0);
    will-change: transform;
  }
}

.stopAnimation:after {
  -webkit-transform: none !important;
  transform: none !important;
}

<!DOCTYPE html>
<html>

<head>
</head>

<body>

  <div id='box' class="box">
    <div class="content"></div>
  </div>

</body>

</html>


来源: stackexchange

问:
How to remove the nth element from a tuple?
I'm trying to write a function that creates a new std::tuple from an existing one, with skipping the element on a given index. In example:

I have a tuple t defined as below:

```<code>constexpr auto t = std::tuple(1, 2, 3, 4);
</code>```

And I want to copy it to another tuple. However, I want to skip the nth element. Let's say that in this case, the nth element I want to skip is 3 (this would mean that I want to skip the element with the index 2). This would result in a new tuple defined as:

```<code>std::tuple(1, 2, 4);
</code>```

This is the closest I got until now:

```<code>template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is != N ? std::get<is>(tp) : 0) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof...(elems)>());
}
</code>```

However, instead of removing the nth element, I set it to 0.

Ideally, I would change the return argument in the function fun() to create a new tuple using multiple temporary tuples:

```<code>return std::tuple_cat((is != N ? std::tuple(std::get<is>(tp)) : std::tuple()) ...);
</code>```

However, the issue with this is that the ternary operator has to have matching types on both sides.

Another approach I tried was based on recursion:

```<code>template<std::size_t N, std::size_t head, std::size_t... tail>
constexpr auto fun3() noexcept {
    if constexpr(!sizeof...(tail))
        return std::tuple(head);

    if constexpr(sizeof...(tail) - 1 == N)
        return std::tuple_cat(fun3<N, tail...>());

    if constexpr(sizeof...(tail) - 1 != N)
        return std::tuple_cat(std::tuple(head), fun3<N, tail...>());
}
</code>```

However, that was even more unsuccessful. In this case, if N is equal to 0, the nth element (which is the first element here as well) will still be used in the new tuple. Also, this won't even compile, because there's an issue with the second statement:

```<code>if constexpr(sizeof...(tail) - 1 == N)
</code>```

What am I missing here? How can I copy a tuple and skip one of its elements during the copy?

I'm using C++17, and I need the function to be evaluated during compile-time.

答:
Just a few minutes after posting the question, I found a workaround. It's not ideal, but hey:

```<code>template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is < N ? std::get<is>(tp) : std::get<is+1>(tp)) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof... (elems) - 1>());
}
</code>```

This way, we copy all of the elements prior to the nth element, and when we reach the nth element, we increase every next index for 1. We won't go out of range, since we pass the index_sequence that has 1 element less than the tuple that is passed.

I hope that this answer helps someone.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a function that creates a new std::tuple from an existing one, with skipping the element on a given index. In example:

I have a tuple t defined as below:

constexpr auto t = std::tuple(1, 2, 3, 4);

And I want to copy it to another tuple. However, I want to skip the nth element. Let's say that in this case, the nth element I want to skip is 3 (this would mean that I want to skip the element with the index 2). This would result in a new tuple defined as:

std::tuple(1, 2, 4);

This is the closest I got until now:

template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is != N ? std::get<is>(tp) : 0) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof...(elems)>());
}

However, instead of removing the nth element, I set it to 0.

Ideally, I would change the return argument in the function fun() to create a new tuple using multiple temporary tuples:

return std::tuple_cat((is != N ? std::tuple(std::get<is>(tp)) : std::tuple()) ...);

However, the issue with this is that the ternary operator has to have matching types on both sides.

Another approach I tried was based on recursion:

template<std::size_t N, std::size_t head, std::size_t... tail>
constexpr auto fun3() noexcept {
    if constexpr(!sizeof...(tail))
        return std::tuple(head);

    if constexpr(sizeof...(tail) - 1 == N)
        return std::tuple_cat(fun3<N, tail...>());

    if constexpr(sizeof...(tail) - 1 != N)
        return std::tuple_cat(std::tuple(head), fun3<N, tail...>());
}

However, that was even more unsuccessful. In this case, if N is equal to 0, the nth element (which is the first element here as well) will still be used in the new tuple. Also, this won't even compile, because there's an issue with the second statement:

if constexpr(sizeof...(tail) - 1 == N)

What am I missing here? How can I copy a tuple and skip one of its elements during the copy?

I'm using C++17, and I need the function to be evaluated during compile-time.

Body:
Just a few minutes after posting the question, I found a workaround. It's not ideal, but hey:

template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is < N ? std::get<is>(tp) : std::get<is+1>(tp)) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof... (elems) - 1>());
}

This way, we copy all of the elements prior to the nth element, and when we reach the nth element, we increase every next index for 1. We won't go out of range, since we pass the index_sequence that has 1 element less than the tuple that is passed.

I hope that this answer helps someone.


问:
Default assignment operator checks for self assignment
i would like to know if the default implementation of the assignment operator checks for self assignment, and so which of those two implementation can be considered the closest to the default one:

```<code>class A{
    int x;
public :
    ...
    // first one
    A& operator=(const A& a){
        if(this != &a) x = a.x;
        return *this;
    }
    // second one
    A& operator=(const A& a){
        x = a.x;
        return *this;
    }
}
</code>```

I've searched for C++ standard but the only one that i can found is this but there is nothing about this

答:
Assignment operator does not check against self assignment. Therefore your second implementation is the closest to the default one.

I can not see any word in standard about any such optimization and it would be strange if attributes of my class would not be assigned by compiler generated operator in some cases. Imagine that some attribute assignment is user defined one and does some uncommon task. Compiler does not know that and IMO should call them even if I assign an object to itself.

Body:
i would like to know if the default implementation of the assignment operator checks for self assignment, and so which of those two implementation can be considered the closest to the default one:

class A{
    int x;
public :
    ...
    // first one
    A& operator=(const A& a){
        if(this != &a) x = a.x;
        return *this;
    }
    // second one
    A& operator=(const A& a){
        x = a.x;
        return *this;
    }
}

I've searched for C++ standard but the only one that i can found is this but there is nothing about this


问:
Entity Framework Core: Database operation expected to affect 1 row(s) but actually affected 0 row(s)
I am using Sql Server on Linux with EC Core (2.1.0-preview1-final)

I am trying to update some data coming from a web Api service (PUT) request.  The data (ticket) is passed correctly and gets deserialised into an object (ticket).

When I try to update, I use the following code:

```<code>public Ticket UpdateTicket(Ticket ticket)
        {
            using (var ctx = new SupportTicketContext(_connectionString))
            {
                ctx.Entry(ticket).State = EntityState.Modified;
                ctx.SaveChanges(); // <== **BLOWS UP HERE**
                var result = ctx.Tickets
                    .First(t => t.TicketId == ticket.TicketId);
                return result;

            }
        }
</code>```

The code throws the following error:

Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data
may have been modified or deleted since entities were loaded

I am able to Insert and fetch from the database, no problem.

If I restart Visual Studio, the error occurs usually on the second time I try to update ANY ticket (i.e. any other ticketId - it seems to be on the second and subsequent requests).

The updates are unpredictably successful!  Sometimes I can update another ticket and it goes through (even on the 3rd or susequent request)

I have tried a number of modifications to the code, including

ctx.Attach(ticket);

but this does not help.

How do I get it to update the database successfully?
Any ideas on how to debug this?  Logging seems to be difficult to set up.

Any ideas greatly appreciated.

答:
Had such problem too, but the reason was a trigger I was using.

Changed the trigger type from "INSTEAD OF INSERT" to "AFTER INSERT" and instead of modifying and inserting the data I was allowing my command to insert the data to the table and then updated it using the trigger.

Body:
I am using Sql Server on Linux with EC Core (2.1.0-preview1-final)

I am trying to update some data coming from a web Api service (PUT) request.  The data (ticket) is passed correctly and gets deserialised into an object (ticket).

When I try to update, I use the following code:

public Ticket UpdateTicket(Ticket ticket)
        {
            using (var ctx = new SupportTicketContext(_connectionString))
            {
                ctx.Entry(ticket).State = EntityState.Modified;
                ctx.SaveChanges(); // <== **BLOWS UP HERE**
                var result = ctx.Tickets
                    .First(t => t.TicketId == ticket.TicketId);
                return result;

            }
        }

The code throws the following error:

Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data
may have been modified or deleted since entities were loaded

I am able to Insert and fetch from the database, no problem.

If I restart Visual Studio, the error occurs usually on the second time I try to update ANY ticket (i.e. any other ticketId - it seems to be on the second and subsequent requests).

The updates are unpredictably successful!  Sometimes I can update another ticket and it goes through (even on the 3rd or susequent request)

I have tried a number of modifications to the code, including

ctx.Attach(ticket);

but this does not help.

How do I get it to update the database successfully?
Any ideas on how to debug this?  Logging seems to be difficult to set up.

Any ideas greatly appreciated.


问:
ORACLE-How to manage rdf schema and instance data in multiple tables?
I need to store the rdf schema in one table and rdf instance data in another table in ORACLE.

How I can do this?

How to configure the joseki-config.ttl to work for multiple models? Some example will help me to understand the solution.

Is there any possibility to create a single model for multiple tables?

Please let me know.

答:
You need to use SDB with Joseki and Oracle.  Then you can have a persistent datasets (a collection of models).  There is an example of an SDB configuration in the Joseki download in joseki-config-sdb.ttl.

SDB controls the database table layout. A model is stored in the default graph name or in the named graphs table.  There is no control for other layouts without changing the code of SDB.

Note that TDB, a custom database layer for Jena, scales better and is faster than using a relational database over JDBC.  Fuseki is the new version of Joseki.

The Jena user mailing list is jena-users@incubator.apache.org.

ContentLicense: CC BY-SA 3.0


问:
String to integer leetcode
I was doing following leetcode question

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary
  until the first non-whitespace character is found. Then, starting from
  this character, takes an optional initial plus or minus sign followed
  by as many numerical digits as possible, and interprets them as a
  numerical value.

The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.

If the first sequence of non-whitespace characters in str is not a
  valid integral number, or if no such sequence exists because either
  str is empty or it contains only whitespace characters, no conversion
  is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered as whitespace character.
  Assume we are dealing with an environment which could only store
  integers within the 32-bit signed integer range: [−231,  231 − 1]. If
  the numerical value is out of the range of representable values,
  INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Question link: https://leetcode.com/problems/string-to-integer-atoi/

Here for this input "-91283472332", I am not sure why do they expect the following output -2147483648 instead of -91283472332

Not sure, If this relevant but this is my code

```<code>/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    let i = 0
    let output = ''
    let nonWhiteCharacter = false
    while (i<str.length) {
       const char = str[i]
       if (!char == " ") {
           if (char.toLowerCase() === char.toUpperCase()) {
            if (!nonWhiteCharacter) nonWhiteCharacter = true
               output = output + char
           }
           if (!nonWhiteCharacter) return 0
       }
        i++
    }
    return output === null ? 0 : parseInt(output)
}
</code>```

答:
Have a look it this solution. As we are dealing with integers, they only hold 32-bit. 2^31 < x <= -2^31. So here we use a try catch as the 32bit integer can raise NumberFormat Exception which will be caught by the catch block.</p>

```<code>class Solution {
    public int myAtoi(String str) {

        int flag=0, sign = 0;
        int n = str.length();
        StringBuilder st = new StringBuilder();
        int i =0;

        //clear white spaces
        while(i<n && str.charAt(i) == ' '){
            ++i;
        }

        //overflow of string
        if (i>=n){
            return 0;
        }

        //checking sign and not allowing more than one sign, will return 0 if there is ++,+-,--
        while(i<n && (str.charAt(i) == '+' || str.charAt(i) == '-')){
            if (sign >= 1){
                return 0;
            }
            else{
           st.append((str.charAt(i++) == '+') ? '+': '-');
            sign++;
            }

        }

        //checking if character is digit
        while(i<n && Character.isDigit(str.charAt(i))){
            st.append(str.charAt(i++));
            flag = 1;
        }

        //return 0 if no digits
        if(flag == 0)
            return 0;

        //to check if the number is within the int range
        try{
            return Integer.parseInt(st.toString());

        }
        catch(NumberFormatException e){
            return (st.charAt(0) == '-') ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }

    }
}

</code>```

Title: String to integer leetcode

Body:
I was doing following leetcode question

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary
  until the first non-whitespace character is found. Then, starting from
  this character, takes an optional initial plus or minus sign followed
  by as many numerical digits as possible, and interprets them as a
  numerical value.

The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.

If the first sequence of non-whitespace characters in str is not a
  valid integral number, or if no such sequence exists because either
  str is empty or it contains only whitespace characters, no conversion
  is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered as whitespace character.
  Assume we are dealing with an environment which could only store
  integers within the 32-bit signed integer range: [−231,  231 − 1]. If
  the numerical value is out of the range of representable values,
  INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Question link: https://leetcode.com/problems/string-to-integer-atoi/

Here for this input "-91283472332", I am not sure why do they expect the following output -2147483648 instead of -91283472332

Not sure, If this relevant but this is my code

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    let i = 0
    let output = ''
    let nonWhiteCharacter = false
    while (i<str.length) {
       const char = str[i]
       if (!char == " ") {
           if (char.toLowerCase() === char.toUpperCase()) {
            if (!nonWhiteCharacter) nonWhiteCharacter = true
               output = output + char
           }
           if (!nonWhiteCharacter) return 0
       }
        i++
    }
    return output === null ? 0 : parseInt(output)
}

Body:
Have a look it this solution. As we are dealing with integers, they only hold 32-bit. 2^31 < x <= -2^31. So here we use a try catch as the 32bit integer can raise NumberFormat Exception which will be caught by the catch block.

class Solution {
    public int myAtoi(String str) {

        int flag=0, sign = 0;
        int n = str.length();
        StringBuilder st = new StringBuilder();
        int i =0;

        //clear white spaces
        while(i<n && str.charAt(i) == ' '){
            ++i;
        }

        //overflow of string
        if (i>=n){
            return 0;
        }

        //checking sign and not allowing more than one sign, will return 0 if there is ++,+-,--
        while(i<n && (str.charAt(i) == '+' || str.charAt(i) == '-')){
            if (sign >= 1){
                return 0;
            }
            else{
           st.append((str.charAt(i++) == '+') ? '+': '-');
            sign++;
            }

        }

        //checking if character is digit
        while(i<n && Character.isDigit(str.charAt(i))){
            st.append(str.charAt(i++));
            flag = 1;
        }

        //return 0 if no digits
        if(flag == 0)
            return 0;

        //to check if the number is within the int range
        try{
            return Integer.parseInt(st.toString());

        }
        catch(NumberFormatException e){
            return (st.charAt(0) == '-') ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }

    }
}


问:
Lower Login button to very bottom of my web app
I was wondering how do I position my Login button at the bottom centre of the screen and have the image displayed over it? I want this to be essentially the homepage. My image is not displaying either for some reason.

Code:

```<code><div class="container-fluid">
  <img alt="Sportly logo" src="~@/assets/sportly.png">
    <div class="row">
        <div class="col-md-12">
            <h3>Login</h3>
            <button class="btn btn-primary"
                @click="signIn">

               <i class="fa fa-twitter"></i>
                    Sign In with Twitter
                </button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    methods: {
        signIn () {
            this.$store.dispatch('signIn')
        }
    }
}
</script>

<style scoped>
h3 {
    font-weight: 700;

}
button {
    background-color: #1dcaff;
    border: 1px solid  #1dcaff;

}
div button:hover {
    background-color: #00aced;
    border: 1px solid  #00aced;

}
</style>
</code>```

答:
If you want the sign in button to be on top of an image, it would be easier to set a div with a background image and put the button on top of that. Your question is worded so that the image goes over the button, which is probably not what you want.

CSS

```<code>.mybackground {
background-image: url('yourimage.jpg');
}
</code>```

HTML (get rid of img tag)

```<code><div class="container-fluid mybackground">
    <div class="row">
        <div class="col-md-12">
            <h3>Login</h3>
            <button class="btn btn-primary"
                @click="signIn">

               <i class="fa fa-twitter"></i>
                    Sign In with Twitter
                </button>
            </div>
        </div>
    </div>
</code>```

Body:
I was wondering how do I position my Login button at the bottom centre of the screen and have the image displayed over it? I want this to be essentially the homepage. My image is not displaying either for some reason.

Code:

Login

            <button class="btn btn-primary"
                @click="signIn">

                    Sign In with Twitter
                </button>

</template>

Body:
If you want the sign in button to be on top of an image, it would be easier to set a div with a background image and put the button on top of that. Your question is worded so that the image goes over the button, which is probably not what you want.

CSS

.mybackground {
background-image: url('yourimage.jpg');
}

HTML (get rid of img tag)

<div class="container-fluid mybackground">
    <div class="row">
        <div class="col-md-12">
            <h3>Login</h3>
            <button class="btn btn-primary"
                @click="signIn">

               <i class="fa fa-twitter"></i>
                    Sign In with Twitter
                </button>
            </div>
        </div>
    </div>


问:
IntersectionObserver and ajax loaded content
I am working on website at the moment, that has some native lazy loading of images using IntersectionObserver the images that I am trying to load are loaded in via ajax as a result I don't think they are "loaded" into DOM on page load, and therefore the images cannot be lazyloaded, by lazy load codes looks like this,

```<code>const io = new IntersectionObserver((entries, observer) => {
    // console.log(entries)
    entries.forEach(entry => {
      console.log('');

      if (entry.isIntersecting) {

        console.log('intersecting');

        const img = entry.target;
        const src = img.getAttribute('data-lazy');

        img.setAttribute('src', src);
        img.classList.add('fade');

        observer.disconnect();
      }
    });
</code>```

Is it possible to lazy load images that are part of content that is loaded via ajax?

答:
Yes, it is possible. After you fetch your data and update your DOM, you need to call your observer again.</p>

```<code>const io = new IntersectionObserver((entries, observer) => {
  // console.log(entries)
  entries.forEach(entry => {
    console.log('');

    if (entry.isIntersecting) {

      console.log('intersecting');

      const img = entry.target;
      const src = img.getAttribute('data-lazy');

      img.setAttribute('src', src);
      img.classList.add('fade');

      observer.disconnect();
    }
  });
});

io.observe(document.querySelectorAll('ímg'));

const fethNewData = () => {
  // any ajax call
  window.fetch().then((html) => {
    //update DOM
    document.querySelector('body').innerHTML = html;
    //call observe again
    io.observe(document.querySelectorAll('ímg'));
  })
};
</code>```

Body:
I am working on website at the moment, that has some native lazy loading of images using IntersectionObserver the images that I am trying to load are loaded in via ajax as a result I don't think they are "loaded" into DOM on page load, and therefore the images cannot be lazyloaded, by lazy load codes looks like this,

const io = new IntersectionObserver((entries, observer) => {
    // console.log(entries)
    entries.forEach(entry => {
      console.log('');

      if (entry.isIntersecting) {

        console.log('intersecting');

        const img = entry.target;
        const src = img.getAttribute('data-lazy');

        img.setAttribute('src', src);
        img.classList.add('fade');

        observer.disconnect();
      }
    });

Is it possible to lazy load images that are part of content that is loaded via ajax?

Body:
Yes, it is possible. After you fetch your data and update your DOM, you need to call your observer again.

const io = new IntersectionObserver((entries, observer) => {
  // console.log(entries)
  entries.forEach(entry => {
    console.log('');

    if (entry.isIntersecting) {

      console.log('intersecting');

      const img = entry.target;
      const src = img.getAttribute('data-lazy');

      img.setAttribute('src', src);
      img.classList.add('fade');

      observer.disconnect();
    }
  });
});

io.observe(document.querySelectorAll('ímg'));

const fethNewData = () => {
  // any ajax call
  window.fetch().then((html) => {
    //update DOM
    document.querySelector('body').innerHTML = html;
    //call observe again
    io.observe(document.querySelectorAll('ímg'));
  })
};


问:
How to use Front Camera for Barcode Scanning in Firebase ML KIT
I have a case where i need to use ML Kit from firebase for barcode scanning. By default it is using back camera. How can i change it to front facing camera ? I have searched in google firebase ML KIT documentation and couldn't find any answer.</p>

答:
Seems like the mlkit example project you linked is using deprecated camera code, but if you look at the CameraSource class on line 175 there is the createCamera method. Try replacing the following line:

```<code>val camera = Camera.open() ?: throw IOException("There is no back-facing camera.")
</code>```

with

```<code>val camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT) ?: throw IOException("There is no front-facing camera.")
</code>```

Body:
Seems like the mlkit example project you linked is using deprecated camera code, but if you look at the CameraSource class on line 175 there is the createCamera method. Try replacing the following line:

val camera = Camera.open() ?: throw IOException("There is no back-facing camera.")

with

val camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT) ?: throw IOException("There is no front-facing camera.")


问:
String is always + 1 in length when it is entered in with the keyboard rather than set as a value in code
So I am trying to write a program that will return the ip address of an entered domain name. The program is much bigger than that but it is this specific functionality that is not working.

After hours and hours of testing why the inet_ntoa was giving me a segmentation fault I decided to hard code the value "www.google.com" instead of typing it. WALA it worked! but why? I suspected that it was looking for "www.google.com\n" so I created a little funcitonality to account for that and delete the end of the string so that it would just be "www.google.com". Well that didn't work, to see if the two strings were equal I did a check. I found out that infact the hardcoded "www.google.com" and the typed in "www.google.com" were infact not the same. So i outputted both strings length. Turns out that the one that is typed in is always + 1 the one that is hardcoded.

Can someone explain this?

Here is my minimally representing example code.

```<code>    char buffer[2048];
    struct hostent *hen;
    int i = 0;

    //buffer is recieved by the client it is written to buffer like
    //while((buffer[n++] = getchar() != '\n')
    //then this server reads it.

    while(buffer[i] != '\n'){
        //            strncat(b, &buffer[i], 100);
        i++;
    }
    i = i-2;
    char b[i];
    i = 0;
    while(buffer[i] != '\n'){
        strncat(b, &buffer[i], 1);
        i++;
    }
    int t = i;
    i = 0;
    while(i != t+1){
        printf("%c", b[i]);
        i++;
    }

    char *e = "www.google.com";
    if(e == b){
        printf("THEY EQUAL");

    } else {
        printf("THEY DON'T AND IM DUMB\n");
        printf("LENGTH OF E: %d\n", strlen(e));
        printf("LENGTH OF B: %d\n", strlen(b));
    }
    printf("here is: %s\n", e);

    hen=gethostbyname(e);
    if(hen==NULL){
        fprintf(stderr,"Host not found \n");
    }
    printf("Hostname is %s \n",hen->h_name);
    printf("IP address is %s \n",inet_ntoa(*((struct in_addr *)hen->h_addr)));
</code>```

答:
```<code>    while(buffer[i] != '\n'){
        i++;
    }
    i = i-2;
    char b[i];
</code>```

Imagine a simple "1234\n" as input.

```<code>Before: i == 0;
After '1': i == 1 because buffer[0] == '1';
After '2': i == 2 because buffer[1] == '2';
After '3': i == 3 because buffer[2] == '3';
After '4': i == 4 because buffer[3] == '4';
After '\n': i == 4 because buffer[4] == '\n' and we DON'T ENTER THE LOOP BODY.
</code>```

And you allocate b[2] instead of b[5] ("1234" and the null-term!)

You simply write to random areas of the stack, corrupt memory, overwrite other variables (and they overwrite the end of your line later).

Body:
So I am trying to write a program that will return the ip address of an entered domain name. The program is much bigger than that but it is this specific functionality that is not working.

After hours and hours of testing why the inet_ntoa was giving me a segmentation fault I decided to hard code the value "www.google.com" instead of typing it. WALA it worked! but why? I suspected that it was looking for "www.google.com\n" so I created a little funcitonality to account for that and delete the end of the string so that it would just be "www.google.com". Well that didn't work, to see if the two strings were equal I did a check. I found out that infact the hardcoded "www.google.com" and the typed in "www.google.com" were infact not the same. So i outputted both strings length. Turns out that the one that is typed in is always + 1 the one that is hardcoded.

Can someone explain this?

Here is my minimally representing example code.

    char buffer[2048];
    struct hostent *hen;
    int i = 0;

    //buffer is recieved by the client it is written to buffer like
    //while((buffer[n++] = getchar() != '\n')
    //then this server reads it.

    while(buffer[i] != '\n'){
        //            strncat(b, &buffer[i], 100);
        i++;
    }
    i = i-2;
    char b[i];
    i = 0;
    while(buffer[i] != '\n'){
        strncat(b, &buffer[i], 1);
        i++;
    }
    int t = i;
    i = 0;
    while(i != t+1){
        printf("%c", b[i]);
        i++;
    }

    char *e = "www.google.com";
    if(e == b){
        printf("THEY EQUAL");

    } else {
        printf("THEY DON'T AND IM DUMB\n");
        printf("LENGTH OF E: %d\n", strlen(e));
        printf("LENGTH OF B: %d\n", strlen(b));
    }
    printf("here is: %s\n", e);

    hen=gethostbyname(e);
    if(hen==NULL){
        fprintf(stderr,"Host not found \n");
    }
    printf("Hostname is %s \n",hen->h_name);
    printf("IP address is %s \n",inet_ntoa(*((struct in_addr *)hen->h_addr)));

Body:
    while(buffer[i] != '\n'){
        i++;
    }
    i = i-2;
    char b[i];

Imagine a simple "1234\n" as input.

Before: i == 0;
After '1': i == 1 because buffer[0] == '1';
After '2': i == 2 because buffer[1] == '2';
After '3': i == 3 because buffer[2] == '3';
After '4': i == 4 because buffer[3] == '4';
After '\n': i == 4 because buffer[4] == '\n' and we DON'T ENTER THE LOOP BODY.

And you allocate b[2] instead of b[5] ("1234" and the null-term!)

You simply write to random areas of the stack, corrupt memory, overwrite other variables (and they overwrite the end of your line later).


问:
How can I force outlook to interpret and display an html file correctly
From linux, I send this file to an outlook account...

```<code><html>
<h2>HELLO</h2>
</html>
</code>```

It appears just as you see, plain text.

How can I get this to display on Outlook as it appears when I run it through firefox on liunux ?

In linux, I sent it as plain test using a system call in a perl script....

```<code>mail -s 'the title' 'recipient' < the_file.html.
</code>```

'which mail' eventually ends up being mailx

The thinking is that outlook would recognize the "html" (between the < and > which won't display here) as line 1 and do the right thing.

答:
You need to set the correct ContentType in the header.
e.g.:
 Content-Type: text/html; charset=UTF-8

Here is an old example in Perl that might help you:
How can I send an HTML email with Perl?

Body:
From linux, I send this file to an outlook account...

HELLO

It appears just as you see, plain text.

How can I get this to display on Outlook as it appears when I run it through firefox on liunux ?

In linux, I sent it as plain test using a system call in a perl script....

mail -s 'the title' 'recipient' < the_file.html.

'which mail' eventually ends up being mailx

The thinking is that outlook would recognize the "html" (between the < and > which won't display here) as line 1 and do the right thing.


问:
Sum of fitted models with sklearn
I am trying to do something that involves taking the sum of two fitted models such that the output is another LinearRegression type object. I have fitted the two models using the standard LinearRegression method from sklearn.

```<code>from sklearn.linear_model import LinearRegression

reg_1 = LinearRegression().fit(X1, y)
reg_2 = LinearRegression().fit(X2, y)
</code>```

and I want to be able to produce something like

```<code>reg = reg_1 + reg_2
</code>```

such that I can still do standard operations such as

```<code>reg.predict(X3)
</code>```

Is there an easy way to do this, clearly I can obtain the coefficients of both reg_1 and reg_2 so if I can define reg ussing those, it would work but I couldn't see a way to do this.

答:
Since your reason for doing this is that "they are just different datasets with the same features" I would recommend simply appending the datasets and creating one model on all data.

But if this isn't possible for some reason you could do this by manually setting the coef_ and intercept_ attributes of a third linear model as the averages of the first two, such as:

```<code>reg = LinearRegression()
reg.coef_ = np.array([np.mean(t) for t in zip(reg_1.coef_, reg_2.coef_)])
reg.intercept_ = np.mean([reg_1.intercept_, reg_2.intercept_])
</code>```

Then you can just use the reg.predict(X3) method as usual to make predictions from the combined averages of the 2 linear models' terms.

There are dangers in this approach though, if for example one of the datasets used to fit the original models is much larger than the other one, then the smaller dataset's intercept and coefficient terms would be over-weighted in the combined model, and you would probably want to do some weighting when averaging the intercept and coefficient terms.

Title: Sum of fitted models with sklearn

Body:
I am trying to do something that involves taking the sum of two fitted models such that the output is another LinearRegression type object. I have fitted the two models using the standard LinearRegression method from sklearn.

from sklearn.linear_model import LinearRegression

reg_1 = LinearRegression().fit(X1, y)
reg_2 = LinearRegression().fit(X2, y)

and I want to be able to produce something like

reg = reg_1 + reg_2

such that I can still do standard operations such as

reg.predict(X3)

Is there an easy way to do this, clearly I can obtain the coefficients of both reg_1 and reg_2 so if I can define reg ussing those, it would work but I couldn't see a way to do this.

Body:
Since your reason for doing this is that "they are just different datasets with the same features" I would recommend simply appending the datasets and creating one model on all data.

But if this isn't possible for some reason you could do this by manually setting the coef_ and intercept_ attributes of a third linear model as the averages of the first two, such as:

reg = LinearRegression()
reg.coef_ = np.array([np.mean(t) for t in zip(reg_1.coef_, reg_2.coef_)])
reg.intercept_ = np.mean([reg_1.intercept_, reg_2.intercept_])

Then you can just use the reg.predict(X3) method as usual to make predictions from the combined averages of the 2 linear models' terms.

There are dangers in this approach though, if for example one of the datasets used to fit the original models is much larger than the other one, then the smaller dataset's intercept and coefficient terms would be over-weighted in the combined model, and you would probably want to do some weighting when averaging the intercept and coefficient terms.


问:
Changing the AcceptButton depending on active control
I have a working WinForm that handles the search functionality in my customer database. It contains the following controls:

A textBox where you type your search string (A)

A "search" button (B)

A DataGridView (C) that returns the result of the search

An "OK" button (D) and a "Cancel" button (E)

What I am trying to accieve next is this:

When A is active the AcceptButton (enter) should be linked to B

When B or enter is pressed C should become active

When C is active the AcceptButton should be linked to D

I realise this is a somewhat big question so don't hesitate to answer just one of the bullet marks if you know the answer.

EDIT: I have solved the implementation of requirement 1 and 3 above, but I am still looking for an answer to the second one. To clarify, when the search is initiated (meaning i have pressed enter on the keyboard or the search button with the mouse) I want focus to shift to the first line in the DataGridView.

答:
Setup handlers to track the Control.Enter event for the particular controls.  When the enter is reached try:

```<code>this.AcceptButton = ControlThatShouldBeAcceptButton;
</code>```

OwnerDisplayName: Sakkle

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sakkle

Body:
Setup handlers to track the Control.Enter event for the particular controls.  When the enter is reached try:

this.AcceptButton = ControlThatShouldBeAcceptButton;

OwnerDisplayName: Quintin Robinson


问:
Override eslint settings in non-ejected create-react-app?
I've found a ton of "solutions" for this, ranging from simple package.json additions to custom hack modules, but none worked for me.

I simply want to override the eslint settings for an out-of-the-box, NON ejected create-react-app.

Namely, the rule "no-unused-vars".

I'm using Visual Studio Code.

答:
The library now supports extending the pre-defined ESLint rules natively, see the relevant docs.

The gist of it is that you will have to set the EXTEND_ESLINT environment variable, and then add your own ESLint config to the project root, optionally extending create-react-app's:

```<code>{
  "eslintConfig": {
    "extends": ["react-app"],
    "overrides": [
      {
        "files": ["**/*.js"],
        "rules": {
          "no-unused-vars": "warn"
        }
      }
    ]
  }
}
</code>```

Body:
The library now supports extending the pre-defined ESLint rules natively, see the relevant docs.

The gist of it is that you will have to set the EXTEND_ESLINT environment variable, and then add your own ESLint config to the project root, optionally extending create-react-app's:

{
  "eslintConfig": {
    "extends": ["react-app"],
    "overrides": [
      {
        "files": ["**/*.js"],
        "rules": {
          "no-unused-vars": "warn"
        }
      }
    ]
  }
}


问:
creating stored procedure - syntax error
I keep getting a syntax error, I've look at countless examples I'm not sure what the problem is...

```<code>DELIMITER //
CREATE PROCEDURE test()
BEGIN
  SELECT *  FROM user;
END //
DELIMITER ;
</code>```

SCREENSHOT:

答:
I experienced multiple problems when wanting to create a stored procedure in Navicat.

Finally I wrote the CREATE PROCEDURE-statement in the normal query window instead of inside the window to design a function/procedure, and then it worked.

Body:
I keep getting a syntax error, I've look at countless examples I'm not sure what the problem is...

DELIMITER //
CREATE PROCEDURE test()
BEGIN
  SELECT *  FROM user;
END //
DELIMITER ;

SCREENSHOT:


问:
Get referrer string for Universal Link?
I implemented Universal Links in our iOS 9 app and they work by calling a method in AppDelegate.swift, in which I get an NSUserActvity with an URL attached to it.

Is there a way to get the (HTTP-) referer? I need to know on which website the user has tapped the link that opened the app.

答:
I found another interesting solution if you need to support iOS 9 and 10 - https://appmetrica.yandex.com/blog/referrer-based-tracking-dlya-ios-tochnaya-atributsiya-dlya-lyubogo-istochnika-trafika.

Since iOS 11 I guess can be used NSUserActivity > referrerURL.

In short:

SFSafariViewController uses the same cookies as Safari app.

You can open invisible SFSafariViewController inside your app.

If your site contains some cookie - use Universal Link to pass it back to the app.

Though it requires to implement something like tracking link on your site.

Title: Get referrer string for Universal Link?


问:
sscanf_s doesn't return first character of string
I'm trying to find the first string (max 4 characters) in a comma-separated list of strings inside a C char-array.

I'm trying to achieve this by using sscanf_s (under Windows) and the format-control string %[^,]:

```<code>char mystring[] = "STR1,STR2";
char temp[5];

if (sscanf_s(mystring, "%[^,]", temp, 5) != 0) {
    if (strcmp(temp, "STR1") == 0) { return 0; }
    else if (strcmp(temp, "STR2") == 0) { return 1; }
    else { return -1; }
}
</code>```

After calling sscanf_s the content of temp is not STR1 but \0TR1 (\0 being the ASCII-interpretation of 0). And the value -1 is returned.

Why do I get that behavior and how do I fix my code to get the right result (return of 0)?

EDIT: changed char mystring to mystring[] (I should have made sure I typed it correcly here)

答:
edited per the comment from chqrlie

regarding:

```<code>if(sscanf_s(mystring, "%[^,]",temp, 5) != 0){
</code>```

The input format conversion specifier: %[..] always appends a NUL byte to the end of the input.  So the input format conversion specifier should be: "%4[^,]"  The result after the correction is:

```<code>if(sscanf_s(mystring, "%4[^,]",temp, 5) != 0){
</code>```

also, no matter how many times this code snippet is executed, the returned value wnce the other problems are corrected will ALWAYS be STR1

regarding the statement;

```<code>char mystring = "STR1,STR2";
</code>```

This is not a valid statement.  Suggest:

```<code>char *mystring = "STR1,STR2";  // notice the '*'
</code>```

--or--

```<code>char mystring[] = "STR1,STR2";  // notice the '[]'
</code>```

Body:
I'm trying to find the first string (max 4 characters) in a comma-separated list of strings inside a C char-array.

I'm trying to achieve this by using sscanf_s (under Windows) and the format-control string %[^,]:

char mystring[] = "STR1,STR2";
char temp[5];

if (sscanf_s(mystring, "%[^,]", temp, 5) != 0) {
    if (strcmp(temp, "STR1") == 0) { return 0; }
    else if (strcmp(temp, "STR2") == 0) { return 1; }
    else { return -1; }
}

After calling sscanf_s the content of temp is not STR1 but \0TR1 (\0 being the ASCII-interpretation of 0). And the value -1 is returned.

Why do I get that behavior and how do I fix my code to get the right result (return of 0)?

EDIT: changed char mystring to mystring[] (I should have made sure I typed it correcly here)

Body:
edited per the comment from chqrlie

regarding:

if(sscanf_s(mystring, "%[^,]",temp, 5) != 0){

The input format conversion specifier: %[..] always appends a NUL byte to the end of the input.  So the input format conversion specifier should be: "%4[^,]"  The result after the correction is:

if(sscanf_s(mystring, "%4[^,]",temp, 5) != 0){

also, no matter how many times this code snippet is executed, the returned value wnce the other problems are corrected will ALWAYS be STR1

regarding the statement;

char mystring = "STR1,STR2";

This is not a valid statement.  Suggest:

char *mystring = "STR1,STR2";  // notice the '*'

--or--

char mystring[] = "STR1,STR2";  // notice the '[]'


问:
how to animate css element only when it appears on a window?
i know that there is parallax but i want something else like in this website joinhandshake.com

for example i have this code

html

```<code><div class="black-div"></div>
   <div class="animated-div">
       <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit temporibus fuga sit quam fugit! Dignissimos quis qui, praesentium id nihil, aspernatur nostrum, dolores dolor molestiae error molestias ipsum ipsam at.</h1>
   </div>
</code>```

css

```<code>
.black-div {
    background-color: black;
    height: 130vh;
}
 @keyframes rotate-scale-up {
    0% {
      transform: scale(1) rotateZ(0);
    }
    50% {
      transform: scale(2) rotateZ(180deg);
    }
    100% {
      transform: scale(1) rotateZ(360deg);
    }
  }
  .animated-div {
    animation: rotate-scale-up 0.65s linear both;
}
</code>```

the problem is that when i load the page, the text gets animated, so how can i prevent that?

答:
Then page fully loaded delay element use jQuery instead.</p>

```<code>  setTimeout(function () {
  $("div").addClass("black-div").delay(2000).fadeIn();
  });
</code>```

Body:
i know that there is parallax but i want something else like in this website joinhandshake.com

for example i have this code

html

Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit temporibus fuga sit quam fugit! Dignissimos quis qui, praesentium id nihil, aspernatur nostrum, dolores dolor molestiae error molestias ipsum ipsam at.

css

.black-div {
    background-color: black;
    height: 130vh;
}
 @keyframes rotate-scale-up {
    0% {
      transform: scale(1) rotateZ(0);
    }
    50% {
      transform: scale(2) rotateZ(180deg);
    }
    100% {
      transform: scale(1) rotateZ(360deg);
    }
  }
  .animated-div {
    animation: rotate-scale-up 0.65s linear both;
}

the problem is that when i load the page, the text gets animated, so how can i prevent that?

Body:
Then page fully loaded delay element use jQuery instead.

  setTimeout(function () {
  $("div").addClass("black-div").delay(2000).fadeIn();
  });


问:
phpspreadsheet failed to work on online server! running php version 7.3

```<code>use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ReportExport extends CI_Controller
{
    public function download()
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'Hello World !');

        $writer = new Xlsx($spreadsheet);

        $filename = 'robert';

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'. $filename .'.xlsx"');
        header('Cache-Control: max-age=0');

        $writer->save('php://output'); // download file
     }
}
</code>```

I have tried to run that function in codeigniter and i get that response from the browser that File not Found (on the online server) yet when i run it offline(on localhost/) it returns the excel file that i have created.

Please any ideas i can use to fix the error!

I am using php version 7.3.14 on the online server.

答:
Save as file in a deticates Folder on Server</p>

```<code>//Path to the file on Server, eg /var/www/website/folder/name.xlsx
$PATH = <PATH>;
$writer->save($PATH);
</code>```

Body:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ReportExport extends CI_Controller
{
    public function download()
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'Hello World !');

        $writer = new Xlsx($spreadsheet);

        $filename = 'robert';

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'. $filename .'.xlsx"');
        header('Cache-Control: max-age=0');

        $writer->save('php://output'); // download file
     }
}

I have tried to run that function in codeigniter and i get that response from the browser that File not Found (on the online server) yet when i run it offline(on localhost/) it returns the excel file that i have created.

Please any ideas i can use to fix the error!

I am using php version 7.3.14 on the online server.

Body:
Save as file in a deticates Folder on Server

//Path to the file on Server, eg /var/www/website/folder/name.xlsx
$PATH = <PATH>;
$writer->save($PATH);


问:
ACF WordPress: Foreach: data-type = 'group'
I have a problem with foreach with data-type = ‘group’.
I have several fields of type "group". In each group I have sub-fields: photo and WYSIWYG editor. I would like the loop to return to:
, fields for one group, but I don't know how to refer to an array in a loop and how to define specific types of values e.g. images, WYSIWYG instead of value itself.
Can I define value differently?
I have this:

```<code><?php

        $fields = get_field_objects();

        ?>

        <?php if ($fields): ?>
            <div class="slider slider-for">
                <?php foreach ($fields as $field): ?>

                    <?php if ($field['value']): ?>
                        <div class="slider-nav-box-big" id="<?php echo $field['name']; ?>">
                            <div class="col-md-4 col-sm-12 col-12 slider-for-img">
                                <img src="<?php echo $field['value']; ?>" alt="">
                            </div>
                            <div class="col-md-8 col-sm-12 col-12 slider-for-description">
                                <p>
                                    <span><?php echo $field['label']; ?></span>
                                    <?php echo $field['wysiwyg']; ?>
                                </p>
                            </div>
                        </div>
                    <?php endif; ?>

                <?php endforeach; ?>
            </div>
        <?php endif; ?>
</code>```

$field[‘value’] obviously returns an empty Array, and $field[‘wysiwyg’] doesn’t work at all.

答:
ACF actually provides examples of how to use a group and to display said data.

Their documentation can be found here on how to do just that - https://www.advancedcustomfields.com/resources/group/

Body:
I have a problem with foreach with data-type = ‘group’.
I have several fields of type "group". In each group I have sub-fields: photo and WYSIWYG editor. I would like the loop to return to:
, fields for one group, but I don't know how to refer to an array in a loop and how to define specific types of values e.g. images, WYSIWYG instead of value itself.
Can I define value differently?
I have this:

<?php

        $fields = get_field_objects();

        ?>

        <?php if ($fields): ?>

                <?php foreach ($fields as $field): ?>

                    <?php if ($field['value']): ?>
                        <div class="slider-nav-box-big" id="<?php echo $field['name']; ?>">

                                <img src="<?php echo $field['value']; ?>" alt="">

                                    <?php echo $field['label']; ?>
                                    <?php echo $field['wysiwyg']; ?>

                    <?php endif; ?>

                <?php endforeach; ?>

        <?php endif; ?>

$field[‘value’] obviously returns an empty Array, and $field[‘wysiwyg’] doesn’t work at all.


问:
How to combine overlapping time ranges (time ranges union)
I have an array with several time ranges inside:

```<code>[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00,
 Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 09:00:00 CEST +02:00,
 Tue, 24 May 2011 15:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
</code>```

I want to get the same array with the overlapping time ranges combined, so the output for this case will be:

```<code>[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 15:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
</code>```

So it creates a new time range when to time ranges overlap, and so on. If they don´t overlap the will be keep separated. Another example:

Input:

```<code>[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:00:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
</code>```

Output (will be the same because they don´t overlap):

```<code>[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:00:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
</code>```

I was thinking in some recursive approach, but I need some guidance here...

答:
Searching a little bit I have found a code that does the trick:

```<code>def self.merge_ranges(ranges)
  ranges = ranges.sort_by {|r| r.first }
  *outages = ranges.shift
  ranges.each do |r|
    lastr = outages[-1]
    if lastr.last >= r.first - 1
      outages[-1] = lastr.first..[r.last, lastr.last].max
    else
      outages.push(r)
    end
  end
  outages
end
</code>```

A sample (working with time ranges too!):

```<code>ranges = [1..5, 20..20, 4..11, 40..45, 39..50]
merge_ranges(ranges)
=> [1..11, 20..20, 39..50]
</code>```

Found here: http://www.ruby-forum.com/topic/162010

Body:
I have an array with several time ranges inside:

[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00,
 Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 09:00:00 CEST +02:00,
 Tue, 24 May 2011 15:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]

I want to get the same array with the overlapping time ranges combined, so the output for this case will be:

[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 15:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]

So it creates a new time range when to time ranges overlap, and so on. If they don´t overlap the will be keep separated. Another example:

Input:

[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:00:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]

Output (will be the same because they don´t overlap):

[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:00:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]

I was thinking in some recursive approach, but I need some guidance here...

Body:
Searching a little bit I have found a code that does the trick:

def self.merge_ranges(ranges)
  ranges = ranges.sort_by {|r| r.first }
  *outages = ranges.shift
  ranges.each do |r|
    lastr = outages[-1]
    if lastr.last >= r.first - 1
      outages[-1] = lastr.first..[r.last, lastr.last].max
    else
      outages.push(r)
    end
  end
  outages
end

A sample (working with time ranges too!):

ranges = [1..5, 20..20, 4..11, 40..45, 39..50]
merge_ranges(ranges)
=> [1..11, 20..20, 39..50]

Found here: http://www.ruby-forum.com/topic/162010


问:
Dockerized Celery worker not picking up tasks from Localstack SQS Queue
I'm building a flask application with celery for backgrounding tasks. My app is using localstack running in a docker container to mimic SQS locally for my message broker. I've gotten flask and celery running locally to work correctly with localstack where I can see flask receiving a request, adding a message to the SQS queue and then celery picks up that task and executes it.

I've attempted to dockerize flask and celery along with localstack and all my services run as expected except for the celery worker which doesn't execute tasks from the queue. I can start a celery worker locally that will read the queue and execute tasks, but the docker celery worker won't pull any tasks.

Running the celery worker in the flask container reached the same results, as well as adding arguments like --without-gossip that I found in this github thread.

Am I missing something in the docker architecture that makes celery not pull from the SQS queue?

Here's my docker-compose.yml:

```<code>
services:
  dev:
    build:
      context: .
      dockerfile: 'dev.Dockerfile'
    ports:
    - "5050:5000"
    restart: always
    volumes:
    - .:/app
    environment:
    - GUNICORN_CMD_ARGS="--reload"
    - docker_env=true
    stdin_open: true
    tty: true
    command: ./entrypoint.sh
    depends_on:
      - localstack

  # mimics AWS services locally
  localstack:
    image: localstack/localstack:latest
    ports:
      - '4561-4599:4561-4599'
      - '8080:8080'
    environment:
      - SERVICES=sqs
      - DEBUG=1
      - DATA_DIR=/tmp/localstack/data
    volumes:
      - './.localstack:/tmp/localstack'
    restart: always

  celery:
    build:
      context: .
      dockerfile: 'dev.Dockerfile'
    volumes:
      - .:/app
    environment:
      - docker_env=true
    stdin_open: true
    tty: true
    command: ./celeryworker.sh
    restart: always
    links:
      - localstack
    depends_on:
      - localstack

volumes:
  .:
</code>```

dev.dockerfile:

```<code>FROM python:3.6

USER root

# Environment Variables
ENV HOST 0.0.0.0
ENV PORT 5000

# Install Packages
COPY requirements.txt /requirements.txt

RUN /bin/bash -c "python3 -m venv docker \
    && source docker/bin/activate \
    && pip3 install --upgrade pip \
    && pip3 install -r requirements.txt"

# Source Code
WORKDIR /app
COPY . .
COPY app/gunicorn_config.py /deploy/app/gunicorn_config.py
COPY entrypoint.sh /bin/entrypoint.sh
COPY celeryworker.sh /bin/celeryworker.sh

USER nobody

EXPOSE 5000
CMD ["bash"]
</code>```

entrypoint.sh:

```<code>source ../docker/bin/activate
gunicorn -c app/gunicorn_config.py --bind 0.0.0.0:5000 'app:create_app()'
</code>```

celeryworker.sh

```<code>source ../docker/bin/activate
celery worker -A app.celery_worker.celery
</code>```

celeryconfig.py

```<code>import os

BROKER_URL = 'sqs://fake:fake@localhost:4576/0'     # local sqs
# BROKER_URL = 'redis://localhost:6379/0'     # local redis
# RESULT_BACKEND = 'redis://localhost:6379/0'     # local redis
if os.getenv('docker_env', 'local') != 'local':
    BROKER_URL = 'sqs://fake:fake@localstack:4576/0'

BROKER_TRANSPORT_OPTIONS = {'queue_name_prefix': 'app-'}
</code>```

I use the same commands locally and everything runs as expected. I've also recreated my local virtual environment to make sure I don't have extra packages not in my requirements.txt

答: Solved this by setting HOSTNAME and HOSTNAME_EXTERNAL in the localstack environment variables. By changing the two between localhost and localstack I can get either my local or docker celery workers pulling tasks.

Body:
I'm building a flask application with celery for backgrounding tasks. My app is using localstack running in a docker container to mimic SQS locally for my message broker. I've gotten flask and celery running locally to work correctly with localstack where I can see flask receiving a request, adding a message to the SQS queue and then celery picks up that task and executes it.

I've attempted to dockerize flask and celery along with localstack and all my services run as expected except for the celery worker which doesn't execute tasks from the queue. I can start a celery worker locally that will read the queue and execute tasks, but the docker celery worker won't pull any tasks.

Running the celery worker in the flask container reached the same results, as well as adding arguments like --without-gossip that I found in this github thread.

Am I missing something in the docker architecture that makes celery not pull from the SQS queue?

Here's my docker-compose.yml:

services:
  dev:
    build:
      context: .
      dockerfile: 'dev.Dockerfile'
    ports:
    - "5050:5000"
    restart: always
    volumes:
    - .:/app
    environment:
    - GUNICORN_CMD_ARGS="--reload"
    - docker_env=true
    stdin_open: true
    tty: true
    command: ./entrypoint.sh
    depends_on:
      - localstack

  # mimics AWS services locally
  localstack:
    image: localstack/localstack:latest
    ports:
      - '4561-4599:4561-4599'
      - '8080:8080'
    environment:
      - SERVICES=sqs
      - DEBUG=1
      - DATA_DIR=/tmp/localstack/data
    volumes:
      - './.localstack:/tmp/localstack'
    restart: always

  celery:
    build:
      context: .
      dockerfile: 'dev.Dockerfile'
    volumes:
      - .:/app
    environment:
      - docker_env=true
    stdin_open: true
    tty: true
    command: ./celeryworker.sh
    restart: always
    links:
      - localstack
    depends_on:
      - localstack

volumes:
  .:

dev.dockerfile:

FROM python:3.6

USER root

# Environment Variables
ENV HOST 0.0.0.0
ENV PORT 5000

# Install Packages
COPY requirements.txt /requirements.txt

RUN /bin/bash -c "python3 -m venv docker \
    && source docker/bin/activate \
    && pip3 install --upgrade pip \
    && pip3 install -r requirements.txt"

# Source Code
WORKDIR /app
COPY . .
COPY app/gunicorn_config.py /deploy/app/gunicorn_config.py
COPY entrypoint.sh /bin/entrypoint.sh
COPY celeryworker.sh /bin/celeryworker.sh

USER nobody

EXPOSE 5000
CMD ["bash"]

entrypoint.sh:

source ../docker/bin/activate
gunicorn -c app/gunicorn_config.py --bind 0.0.0.0:5000 'app:create_app()'

celeryworker.sh

source ../docker/bin/activate
celery worker -A app.celery_worker.celery

celeryconfig.py

import os

BROKER_URL = 'sqs://fake:fake@localhost:4576/0'     # local sqs
# BROKER_URL = 'redis://localhost:6379/0'     # local redis
# RESULT_BACKEND = 'redis://localhost:6379/0'     # local redis
if os.getenv('docker_env', 'local') != 'local':
    BROKER_URL = 'sqs://fake:fake@localstack:4576/0'

BROKER_TRANSPORT_OPTIONS = {'queue_name_prefix': 'app-'}

I use the same commands locally and everything runs as expected. I've also recreated my local virtual environment to make sure I don't have extra packages not in my requirements.txt


问:
Return a value from a struct without specifying a property
I have a question, and I have been looking for a while and I don't know if it is possible. I think I have seen it done before though.

So i have a struct.

```<code>public struct Field
{
    public String Name;
    public Int32 Size;

    public Field(String name, Int32 size)
    {
        Name = name;
        Size = size;
    }
}
</code>```

What i want to do is when i use it below it returns the name value.

```<code>Field field = new Field("Ben", "1,70");

// name would receive the value Ben from the field.name variable
String name = field;
</code>```

If you wise folk would know a way to get this to work, or maybe a better way it would be much appreciated!

Thanks!

答:
You could use an Implicit operator

Note : Though its use is a little suspect in this case

```<code>public struct Field
{
   public String Name;
   public Int32 Size;

   public Field(String name, Int32 size)
   {
      Name = name;
      Size = size;
   }
   public static implicit operator string(Field d) => d.Name;
}
</code>```

Usage

```<code>Field field = new Field("Ben", 1);
Console.WriteLine(field);
</code>```

Output

```<code>Ben
</code>```

Body:
I have a question, and I have been looking for a while and I don't know if it is possible. I think I have seen it done before though.

So i have a struct.

public struct Field
{
    public String Name;
    public Int32 Size;

    public Field(String name, Int32 size)
    {
        Name = name;
        Size = size;
    }
}

What i want to do is when i use it below it returns the name value.

Field field = new Field("Ben", "1,70");

// name would receive the value Ben from the field.name variable
String name = field;

If you wise folk would know a way to get this to work, or maybe a better way it would be much appreciated!

Thanks!

Body:
You could use an Implicit operator

Note : Though its use is a little suspect in this case

public struct Field
{
   public String Name;
   public Int32 Size;

   public Field(String name, Int32 size)
   {
      Name = name;
      Size = size;
   }
   public static implicit operator string(Field d) => d.Name;
}

Usage

Field field = new Field("Ben", 1);
Console.WriteLine(field);

Output

Ben


问:
Angular how to subtract time from current time
I am fetching data from firebase i need to know how can i check difference between the fetch time and current time

Example

```<code>if(this.data.time - current time <= (less or equal) 3 hours) {
  console.log('Please wait till difference')
}
</code>```

What i need if data.time - current time is less then or equal to 3 hours then i need to console the time left in 3 hours.

I have time in second and nanoseconds.

Let me clear more. For example data time is 2.30AM and current time is 3.30AM So its not completed 3 hours till now so i need time left which is 2 hours left. and if time completed like current time is 6.30 so simple console time exceed.

Working with this code but showing error Type 'string' is not assignable to type 'number'.

```<code>secondsToHHMMSS(totalSeconds: any): string { // from https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // if you want strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0"); //here showing error of String
  hours = String(hours).padStart(2, "0"); //here showing error of String
  seconds = String(seconds).padStart(2, "0"); //here showing error of String

  return (hours + ":" + minutes + ":" + seconds);
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('3 hours hasn\'t elapsed yet.');
  console.log('Time remaining: ' + this.secondsToHHMMSS(timeDiff));
}
</code>```

答:
To answer the question you asked

Assuming this.data.time is in seconds, you can use Date.now() to get the current time in milliseconds, and divide that by 1000 to get seconds.

Since an hour is 3600 seconds, we can then compare our time difference with this multiplied by our desired hours.

```<code>const currentTime = Date.now() / 1000;

if(this.data.time - currentTime < 3 * 3600) {
  console.log("Please wait 'til difference")
}
</code>```

Body:
I am fetching data from firebase i need to know how can i check difference between the fetch time and current time

Example

if(this.data.time - current time <= (less or equal) 3 hours) {
  console.log('Please wait till difference')
}

What i need if data.time - current time is less then or equal to 3 hours then i need to console the time left in 3 hours.

I have time in second and nanoseconds.

Let me clear more. For example data time is 2.30AM and current time is 3.30AM So its not completed 3 hours till now so i need time left which is 2 hours left. and if time completed like current time is 6.30 so simple console time exceed.

Working with this code but showing error Type 'string' is not assignable to type 'number'.

secondsToHHMMSS(totalSeconds: any): string { // from https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // if you want strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0"); //here showing error of String
  hours = String(hours).padStart(2, "0"); //here showing error of String
  seconds = String(seconds).padStart(2, "0"); //here showing error of String

  return (hours + ":" + minutes + ":" + seconds);
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('3 hours hasn\'t elapsed yet.');
  console.log('Time remaining: ' + this.secondsToHHMMSS(timeDiff));
}

Body:
To answer the question you asked

Assuming this.data.time is in seconds, you can use Date.now() to get the current time in milliseconds, and divide that by 1000 to get seconds.

Since an hour is 3600 seconds, we can then compare our time difference with this multiplied by our desired hours.

const currentTime = Date.now() / 1000;

if(this.data.time - currentTime < 3 * 3600) {
  console.log("Please wait 'til difference")
}


问:
Using CTE to get a count into a variable, then trying to use same CTE to get the rows if variable is greater than 0
What I'm  trying to do is this: use a variable, create a CTE, then use the count (*) function to return how many rows were returned from the CTE, if it's 0, just move on to the else; but I get an error: query looks like this

```<code>declare @number_of_rows as int;

with cte as (select a from b)
    SELECT @number_of_rows = count(*) FROM CTE
    print @number_of_rows

    if @number_of_rows = 0  print 'No Rows Found'
        ELSE --(execute a send mail function with the result set)

        select * from CTE -- I get an error here, can I not use the CTE again if I used it to store the variable ?

</code>```

the error message is:

Msg 208, Level 16, State 1, Line 48

  Invalid object name 'CTE'.

Is there a way to accomplish what I'm trying to do without having to create a variable table inserting the rows, and using that? I'm trying to avoid that.

答:
I would do something like this</p>

```<code>SELECT a FROM b
IF (@@ROWCOUNT = 0)
BEGIN
  print 'No Rows Found'
END
</code>```

Body:
What I'm  trying to do is this: use a variable, create a CTE, then use the count (*) function to return how many rows were returned from the CTE, if it's 0, just move on to the else; but I get an error: query looks like this

declare @number_of_rows as int;

with cte as (select a from b)
    SELECT @number_of_rows = count(*) FROM CTE
    print @number_of_rows

    if @number_of_rows = 0  print 'No Rows Found'
        ELSE --(execute a send mail function with the result set)

        select * from CTE -- I get an error here, can I not use the CTE again if I used it to store the variable ?

the error message is:

Msg 208, Level 16, State 1, Line 48

  Invalid object name 'CTE'.

Is there a way to accomplish what I'm trying to do without having to create a variable table inserting the rows, and using that? I'm trying to avoid that.

Body:
I would do something like this

SELECT a FROM b
IF (@@ROWCOUNT = 0)
BEGIN
  print 'No Rows Found'
END


问:
Multiple event listener on the same object not working
Is it possible to have two listener listening to the same event? I have an event listener listening for the oncanplay video event, and in some other class, in this example the test class, I have to listen to the same event.

```<code><!DOCTYPE html>
<html>
<body>

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button><br>

<video id="myVideo" width="320" height="176" autoplay>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script>

const test = () => {

  vid.oncanplay = function() {
  console.log("CAN PLAY 2!")
};
}

var vid = document.getElementById("myVideo");
test();

  vid.oncanplay = function() {
  console.log("CAN PLAY 1!")
};

function playVid() {
  vid.play();
}

function pauseVid() {
  vid.pause();
}
</script>

</body>
</html>
</code>```

In this case only CAN PLAY 1 will be fired. If I remove the CAN PLAY 1 listener, CAN PLAY 2 will than be fired. Can I have both event be fired?

答:
oncanplay is a property of the object, and it can be assigned to multiple times, but only the last assignment means anything, as you overwrite the value.

It's like...

```<code>a=2;
a=1;
console.log(a);
//as you'd expect, it would output the value of 1
</code>```

As has been suggested, you can put multiple event listeners on the object by using

```<code>vid.addEventListener("canplay",
                     function() {
                        console.log("CAN PLAY 1!");
                      });
</code>```

...because addEventListener doesn't overwrite previously created event listeners.

Also, as a side note, keep in mind, doing this with an anonymous function will make it difficult to remove the event listener later; as, being anonymous, there is no named reference to allow you to access it during a removeEventListener request.

Body:
Is it possible to have two listener listening to the same event? I have an event listener listening for the oncanplay video event, and in some other class, in this example the test class, I have to listen to the same event.

<!DOCTYPE html>

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button>

<video id="myVideo" width="320" height="176" autoplay>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

In this case only CAN PLAY 1 will be fired. If I remove the CAN PLAY 1 listener, CAN PLAY 2 will than be fired. Can I have both event be fired?

Body:
oncanplay is a property of the object, and it can be assigned to multiple times, but only the last assignment means anything, as you overwrite the value.

It's like...

a=2;
a=1;
console.log(a);
//as you'd expect, it would output the value of 1

As has been suggested, you can put multiple event listeners on the object by using

vid.addEventListener("canplay",
                     function() {
                        console.log("CAN PLAY 1!");
                      });

...because addEventListener doesn't overwrite previously created event listeners.

Also, as a side note, keep in mind, doing this with an anonymous function will make it difficult to remove the event listener later; as, being anonymous, there is no named reference to allow you to access it during a removeEventListener request.


问:
Vue Codemirror line numbers
So I am trying to implement codemirror into my Vue.js app using https://github.com/surmon-china/vue-codemirror. The problem is that after I import and use the codemirro component everything works fine expect the line numbers (number of lines the code has) are not showing. Here is my code right out of the demo page:

<template>

        <codemirror v-model="code"
                    :options="cmOption"
                    @cursorActivity="onCmCursorActivity"
                    @ready="onCmReady"
                    @focus="onCmFocus"
                    @blur="onCmBlur">
        </codemirror>

</template>
```

<p>and here is the script: </p>

<pre class="lang-js prettyprint-override"><code>data() {
      return {
        code: '',
        cmOption: {
          tabSize: 4,
          styleActiveLine: true,
          lineNumbers: true,
          styleSelectedText: true,
          line: true,
          foldGutter: true,
          gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
          highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
          mode: 'text/javascript',
          // hint.js options
          hintOptions:{
            // 当匹配只有一项的时候是否自动补全
            completeSingle: true
          },
          //快捷键 可提供三种模式 sublime、emacs、vim
          keyMap: "sublime",
          matchBrackets: true,
          showCursorWhenSelecting: true,
          theme: "monokai",
          extraKeys: { "Ctrl": "autocomplete" }
        }
      }
    }
</code>```

答:
In your codemirror configuration options there is string:

```<code>   lineNumbers: false,
</code>```

which turns off line numbers. Change it's value to true and it should solve the problem.

Title: Vue Codemirror line numbers

Body:
So I am trying to implement codemirror into my Vue.js app using https://github.com/surmon-china/vue-codemirror. The problem is that after I import and use the codemirro component everything works fine expect the line numbers (number of lines the code has) are not showing. Here is my code right out of the demo page:

<template>

        <codemirror v-model="code"
                    :options="cmOption"
                    @cursorActivity="onCmCursorActivity"
                    @ready="onCmReady"
                    @focus="onCmFocus"
                    @blur="onCmBlur">
        </codemirror>

</template>

and here is the script:

data() {
      return {
        code: '',
        cmOption: {
          tabSize: 4,
          styleActiveLine: true,
          lineNumbers: true,
          styleSelectedText: true,
          line: true,
          foldGutter: true,
          gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
          highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
          mode: 'text/javascript',
          // hint.js options
          hintOptions:{
            // 当匹配只有一项的时候是否自动补全
            completeSingle: true
          },
          //快捷键 可提供三种模式 sublime、emacs、vim
          keyMap: "sublime",
          matchBrackets: true,
          showCursorWhenSelecting: true,
          theme: "monokai",
          extraKeys: { "Ctrl": "autocomplete" }
        }
      }
    }

Body:
In your codemirror configuration options there is string:

   lineNumbers: false,

which turns off line numbers. Change it's value to true and it should solve the problem.


问:
How to escape quotes in a string that assigns a method to onclick with a parameter?
I have a string that contains HTML-Code. And within that string I am assigning a method WITH AN ARGUMENT to the onclick-attribute. This attribute needs to be a string though.

This is the code.

This is how it looks like in HTML.

This is how it should look like in HTML.

I tried to put double quotes before and after, escape them, escape them with multiple backslahes, and many other things, nothing works. All ideas are appreaciated. :-)

答:
This looks like a job for stripslashes(). Note however, that you can not use the same double quote (") or single qoutes (') for both the attribute assignment AND the string definition for the parameter. Therefore you want your result to look something like: onclick="removeTag('naruto')".

If you have them as double quotes in your original string (i.e. $row['description']), you can replace those, all put together like this:

```<code>echo 'blabla <a href="#" onclick="removeTag(' . str_replace('"', '\'', stripslashes($row['description'])) . ')">';
</code>```

A tiny bit simpler approach might be to just trim double quotes and add your own single qoutes:

```<code>echo 'blabla <a href="#" onclick="removeTag(\'' . trim(stripslashes($row['description']), '"') . '\')">';
</code>```

Body:
This looks like a job for stripslashes(). Note however, that you can not use the same double quote (") or single qoutes (') for both the attribute assignment AND the string definition for the parameter. Therefore you want your result to look something like: onclick="removeTag('naruto')".

If you have them as double quotes in your original string (i.e. $row['description']), you can replace those, all put together like this:

echo 'blabla <a href="#" onclick="removeTag(' . str_replace('"', '\'', stripslashes($row['description'])) . ')">';

A tiny bit simpler approach might be to just trim double quotes and add your own single qoutes:

echo 'blabla <a href="#" onclick="removeTag(\'' . trim(stripslashes($row['description']), '"') . '\')">';


问:
React: [useRef, scrollIntoView,] How to only autoscroll a specific div inside of an overflowing page?
As you can see in my example

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

function App() {
  const items = ["this", "that", "those", "them", "these", "thisins"];

  const messagesRef = React.useRef(null);
  const scrollToBottom = () => {
    messagesRef.current.scrollIntoView({
      behavior: "smooth"
    });
  };

  React.useEffect(() => {
    if (messagesRef.current) {
      scrollToBottom();
    }
  }, [messagesRef]);

  return (
    // Page is overflowing, set height to mimic a full page

      {/* now set this div to overflow scroll with a small height */}

        {items.map(elem => (

            {elem}

        ))}
        {/* Set last element within this div to be the ref to scroll to */}

  );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

<div id="root"></div></code>```

The page loads, and both the page and the nested scrolling div auto scroll.

What I'm trying to do is only scrollIntoView the overflowing div I have set as my ref.

I'm targetting the ref, and it is working, but how do I NOT scroll the parent element as well?

答:
Try this:</p>

```<code>   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });
</code>```

Body:
As you can see in my example

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

function App() {
  const items = ["this", "that", "those", "them", "these", "thisins"];

  const messagesRef = React.useRef(null);
  const scrollToBottom = () => {
    messagesRef.current.scrollIntoView({
      behavior: "smooth"
    });
  };

  React.useEffect(() => {
    if (messagesRef.current) {
      scrollToBottom();
    }
  }, [messagesRef]);

  return (
    // Page is overflowing, set height to mimic a full page

      {/* now set this div to overflow scroll with a small height */}

        {items.map(elem => (

            {elem}

        ))}
        {/* Set last element within this div to be the ref to scroll to */}

  );
}

The page loads, and both the page and the nested scrolling div auto scroll.

What I'm trying to do is only scrollIntoView the overflowing div I have set as my ref.

I'm targetting the ref, and it is working, but how do I NOT scroll the parent element as well?

Body:
Try this:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });


问:
Redirect all www and http ==>> non www https on AWS Elastic Beanstalk with Load Balancer
I currently have this in place to redirect all http traffic to https.

```<code>RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]
</code>```

The above is working OK.

Now I'm trying to add rewrite condition to force all https://www traffic to https without the www.

Please note that this is an AWS Elastic Beanstalk running Apache behind Elastic Load Balancer

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

EDIT:

Working code:

```<code>RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]
</code>```

答:
Just for anyone looking for a full copy and paste solution using ElasticBeanstalks config files.

Create file inside .ebextensions/, lets call it 01-https.config.

Add the following:

```<code>files:
  "/etc/httpd/conf.d/http-redirect.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      RewriteEngine On
      RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC]
      RewriteCond %{HTTP:X-Forwarded-Proto} !https
      RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
      RewriteRule (.*) https://example.com%{REQUEST_URI}
</code>```

This takes into consideration ELB health check and will work for the following examples:

http://example.com

http://www.example.com

https://www.example.com

which will be redirected to https://example.com

Body:
I currently have this in place to redirect all http traffic to https.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

The above is working OK.

Now I'm trying to add rewrite condition to force all https://www traffic to https without the www.

Please note that this is an AWS Elastic Beanstalk running Apache behind Elastic Load Balancer

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

EDIT:

Working code:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

Body:
Just for anyone looking for a full copy and paste solution using ElasticBeanstalks config files.

Create file inside .ebextensions/, lets call it 01-https.config.

Add the following:

files:
  "/etc/httpd/conf.d/http-redirect.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      RewriteEngine On
      RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC]
      RewriteCond %{HTTP:X-Forwarded-Proto} !https
      RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
      RewriteRule (.*) https://example.com%{REQUEST_URI}

This takes into consideration ELB health check and will work for the following examples:

http://example.com

http://www.example.com

https://www.example.com

which will be redirected to https://example.com