问:
Copy constructor with non-const argument suggested by thread-safety rules?
I have a wrapper to some piece of legacy code.

```<code>class A{
   L* impl_; // the legacy object has to be in the heap, could be also unique_ptr
   A(A const&) = delete;
   L* duplicate(){L* ret; legacy_duplicate(impl_, &L); return ret;}
   ... // proper resource management here
};
</code>```

In this legacy code, the function that “duplicates” an object is not thread safe (when calling on the same first argument), therefore it is not marked const in the wrapper. I guess following modern rules: https://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/

This duplicate looks like a good way to implement a copy constructor, except for the detail that is it not const. Therefore I cannot do this directly:

```<code>class A{
   L* impl_; // the legacy object has to be in the heap
   A(A const& other) : L{other.duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

So what is the way out this paradoxical situation?

(Let's say also that legacy_duplicate is not thread-safe but I know leaves the object in the original state when it exits. Being a C-function the behavior is only documented but has no concept of constness.)

I can think of many possible scenarios:

(1) One possibility is that there is no way to implement a copy constructor with the usual semantics at all. (Yes, I can move the object and that is not what I need.)

(2) On the other hand, copying an object is inherently non-thread-safe in the sense that copying a simple type can find the source in an half-modified state, so I can just go forward and do this perhaps,

```<code>class A{
   L* impl_;
   A(A const& other) : L{const_cast<A&>(other).duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

(3) or even just declare duplicate const and lie about thread safety in all contexts. (After all the legacy function doesn't care about const so the compiler will not even complain.)

```<code>class A{
   L* impl_;
   A(A const& other) : L{other.duplicate()}{}
   L* duplicate() const{L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

(4) Finally, I can follow the logic and make a copy-constructor that takes a non-const argument.

```<code>class A{
   L* impl_;
   A(A const&) = delete;
   A(A& other) : L{other.duplicate()}{}
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

It turns out that this works in many contexts, because these objects are not usually const.

The question is, it this a valid or common route?

I cannot name them, but I intuitively expect lots of problems down the road of having a non-const copy constructor. Probably it will not qualify as a value-type because of this subtlety.

(5) Finally, although this seems to be an overkill and could have a steep runtime cost, I could add a mutex:

```<code>class A{
   L* impl_;
   A(A const& other) : L{other.duplicate_locked()}{}
   L* duplicate(){
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   L* duplicate_locked() const{
      std::lock_guard<std::mutex> lk(mut);
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   mutable std::mutex mut;
};
</code>```

But being forced to do this looks like pessimization and makes the class bigger. I am not sure. I am currently leaning towards (4), or (5) or a combination of both.

EDIT 1:

Another option:

(6) Forget about all the non-sense of the duplicate member function and simply call legacy_duplicate from the constructor and declare that the copy constructor is not thread safe. (And if necessary make another thread-safe versión of the type, A_mt)

```<code>class A{
   L* impl_;
   A(A const& other){legacy_duplicate(other.impl_, &impl_);}
};
</code>```

EDIT 2:

This could be a good model for what the legacy function does. Note that by touching the input the call is not thread safe with respect to the value represented by the first argument.

```<code>void legacy_duplicate(L* in, L** out){
   *out = new L{};
   char tmp = in[0];
   in[0] = tmp;
   std::memcpy(*out, in, sizeof *in); return;
}
</code>```

EDIT 3:
I lately learned that std::auto_ptr had a similar problem of having a non-const "copy" constructor. The effect was that auto_ptr couldn't be used inside a container. https://www.quantstart.com/articles/STL-Containers-and-Auto_ptrs-Why-They-Dont-Mix/

答:
I would just include both your options (4) and (5), but explicitly opt-in to thread-unsafe behavior when you think it is necessary for performance.

Here is a complete example.

#include <cstdlib>
#include <thread>

struct L {
  int val;
};

void legacy_duplicate(const L* in, L** out) {
  *out = new L{};
  std::memcpy(*out, in, sizeof *in);
  return;
}

class A {
 public:
  A(L* l) : impl_{l} {}
  A(A const& other) : impl_{other.duplicate_locked()} {}

  A copy_unsafe_for_multithreading() { return {duplicate()}; }

  L* impl_;

  L* duplicate() {
    printf("in duplicate\n");
    L* ret;
    legacy_duplicate(impl_, &ret);
    return ret;
  }
  L* duplicate_locked() const {
    std::lock_guard<std::mutex> lk(mut);
    printf("in duplicate_locked\n");
    L* ret;
    legacy_duplicate(impl_, &ret);
    return ret;
  }
  mutable std::mutex mut;
};

int main() {
  A a(new L{1});
  const A b(new L{2});

  A c = a;
  A d = b;

  A e = a.copy_unsafe_for_multithreading();
  A f = const_cast(b).copy_unsafe_for_multithreading();

  printf("\npointers:\na=%p\nb=%p\nc=%p\nc=%p\nd=%p\nf=%p\n\n", a.impl_,
     b.impl_, c.impl_, d.impl_, e.impl_, f.impl_);

  printf("vals:\na=%d\nb=%d\nc=%d\nc=%d\nd=%d\nf=%d\n", a.impl_->val,
     b.impl_->val, c.impl_->val, d.impl_->val, e.impl_->val, f.impl_->val);
}
```

<p>Output:</p>

```in duplicate_locked
in duplicate_locked
in duplicate
in duplicate

pointers:
a=0x7f85e8c01840
b=0x7f85e8c01850
c=0x7f85e8c01860
c=0x7f85e8c01870
d=0x7f85e8c01880
f=0x7f85e8c01890

vals:
a=1
b=2
c=1
c=2
d=1
f=2
```

This follows the Google style guide in which const communicates thread safety, but code calling your API can opt-out using const_cast

Body:
I have a wrapper to some piece of legacy code.

class A{
   L* impl_; // the legacy object has to be in the heap, could be also unique_ptr
   A(A const&) = delete;
   L* duplicate(){L* ret; legacy_duplicate(impl_, &L); return ret;}
   ... // proper resource management here
};

In this legacy code, the function that “duplicates” an object is not thread safe (when calling on the same first argument), therefore it is not marked const in the wrapper. I guess following modern rules: https://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/

This duplicate looks like a good way to implement a copy constructor, except for the detail that is it not const. Therefore I cannot do this directly:

class A{
   L* impl_; // the legacy object has to be in the heap
   A(A const& other) : L{other.duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

So what is the way out this paradoxical situation?

(Let's say also that legacy_duplicate is not thread-safe but I know leaves the object in the original state when it exits. Being a C-function the behavior is only documented but has no concept of constness.)

I can think of many possible scenarios:

(1) One possibility is that there is no way to implement a copy constructor with the usual semantics at all. (Yes, I can move the object and that is not what I need.)

(2) On the other hand, copying an object is inherently non-thread-safe in the sense that copying a simple type can find the source in an half-modified state, so I can just go forward and do this perhaps,

class A{
   L* impl_;
   A(A const& other) : L{const_cast(other).duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

(3) or even just declare duplicate const and lie about thread safety in all contexts. (After all the legacy function doesn't care about const so the compiler will not even complain.)

class A{
   L* impl_;
   A(A const& other) : L{other.duplicate()}{}
   L* duplicate() const{L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

(4) Finally, I can follow the logic and make a copy-constructor that takes a non-const argument.

class A{
   L* impl_;
   A(A const&) = delete;
   A(A& other) : L{other.duplicate()}{}
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

It turns out that this works in many contexts, because these objects are not usually const.

The question is, it this a valid or common route?

I cannot name them, but I intuitively expect lots of problems down the road of having a non-const copy constructor. Probably it will not qualify as a value-type because of this subtlety.

(5) Finally, although this seems to be an overkill and could have a steep runtime cost, I could add a mutex:

class A{
   L* impl_;
   A(A const& other) : L{other.duplicate_locked()}{}
   L* duplicate(){
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   L* duplicate_locked() const{
      std::lock_guard<std::mutex> lk(mut);
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   mutable std::mutex mut;
};

But being forced to do this looks like pessimization and makes the class bigger. I am not sure. I am currently leaning towards (4), or (5) or a combination of both.

EDIT 1:

Another option:

(6) Forget about all the non-sense of the duplicate member function and simply call legacy_duplicate from the constructor and declare that the copy constructor is not thread safe. (And if necessary make another thread-safe versión of the type, A_mt)

class A{
   L* impl_;
   A(A const& other){legacy_duplicate(other.impl_, &impl_);}
};

EDIT 2:

This could be a good model for what the legacy function does. Note that by touching the input the call is not thread safe with respect to the value represented by the first argument.

void legacy_duplicate(L* in, L** out){
   *out = new L{};
   char tmp = in[0];
   in[0] = tmp;
   std::memcpy(*out, in, sizeof *in); return;
}

EDIT 3:
I lately learned that std::auto_ptr had a similar problem of having a non-const "copy" constructor. The effect was that auto_ptr couldn't be used inside a container. https://www.quantstart.com/articles/STL-Containers-and-Auto_ptrs-Why-They-Dont-Mix/

Body:
I would just include both your options (4) and (5), but explicitly opt-in to thread-unsafe behavior when you think it is necessary for performance.

Here is a complete example.

#include <cstdlib>
#include <thread>

struct L {
  int val;
};

void legacy_duplicate(const L* in, L** out) {
  *out = new L{};
  std::memcpy(*out, in, sizeof *in);
  return;
}

class A {
 public:
  A(L* l) : impl_{l} {}
  A(A const& other) : impl_{other.duplicate_locked()} {}

  A copy_unsafe_for_multithreading() { return {duplicate()}; }

  L* impl_;

  L* duplicate() {
    printf("in duplicate\n");
    L* ret;
    legacy_duplicate(impl_, &ret);
    return ret;
  }
  L* duplicate_locked() const {
    std::lock_guard<std::mutex> lk(mut);
    printf("in duplicate_locked\n");
    L* ret;
    legacy_duplicate(impl_, &ret);
    return ret;
  }
  mutable std::mutex mut;
};

int main() {
  A a(new L{1});
  const A b(new L{2});

  A c = a;
  A d = b;

  A e = a.copy_unsafe_for_multithreading();
  A f = const_cast<A&>(b).copy_unsafe_for_multithreading();

  printf("\npointers:\na=%p\nb=%p\nc=%p\nc=%p\nd=%p\nf=%p\n\n", a.impl_,
     b.impl_, c.impl_, d.impl_, e.impl_, f.impl_);

  printf("vals:\na=%d\nb=%d\nc=%d\nc=%d\nd=%d\nf=%d\n", a.impl_->val,
     b.impl_->val, c.impl_->val, d.impl_->val, e.impl_->val, f.impl_->val);
}

Output:

in duplicate_locked
in duplicate_locked
in duplicate
in duplicate

pointers:
a=0x7f85e8c01840
b=0x7f85e8c01850
c=0x7f85e8c01860
c=0x7f85e8c01870
d=0x7f85e8c01880
f=0x7f85e8c01890

vals:
a=1
b=2
c=1
c=2
d=1
f=2

This follows the Google style guide in which const communicates thread safety, but code calling your API can opt-out using const_cast


来源: stackexchange

问:
scraping multiple page web table with vba
i'm trying to save in excel with vba the second page of the table in the url below in code but i'm unable to use the click property, may you help me please? i have searched everywhere on the web without results. thanks.

Sub BrowseSiteTableObjectX()
    Dim IE As New SHDocVw.InternetExplorer
    Dim Docm As MSHTML.HTMLDocument
    Dim HTMLAtab As MSHTML.IHTMLElement
    Dim HTMLArow As MSHTML.IHTMLElement
    Dim iRow As Long

    With IE
        .navigate "https://www.nasdaq.com/market-activity/stocks/screener"
        Do While .Busy Or .readyState <> 4
           DoEvents
        Loop
    End With

    Set Docm = IE.document

    Docm.getElementsByClassName("symbol-screener__pagination")(0).getElementsByClassName("next")(0).Click

    Set Docm = IE.document

    Set HTMLAtab = Docm.getElementsByClassName("symbol-screener__table")(0)

    For Each HTMLArow In HTMLAtab.getElementsByClassName("symbol-screener__row")
        iRow = iRow + 1
        Cells(iRow, 1) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--ticker")(0).innerText
        Cells(iRow, 2) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--company")(0).innerText
        DoEvents
    Next HTMLArow

    IE.Quit
    Set IE = Nothing
    Set Docm = Nothing
End Sub
```

答:
See if this helps, in this post, I outlined multiple ways to deal with elements on the page. You need to consider what is happening when you 'click' the Next button. It could be submitting a form, running page javascript,

Excel VBA Submitting data via IE on an online MS Forms not working

See if any of those ideas help. You might find ExecScript is the best, since the Next button probably links back to script on the page to load the next set of data. Just need to watch your Chrome Dev Tools and see what happens.

Good luck!

ContentLicense: CC BY-SA 4.0


问:
Type definition: Pointer vs Value
I'm new in Go and would like to extend treemap.Map from GoDS project.

I started by defining a type alias for treemap.Map:

import "github.com/emirpasic/gods/maps/treemap"

type Index = treemap.Map

func (idx Index) Add(k int, v int) {
    idx.Put(k, v)
}
```

<p>Getting the following compilation error: <code>cannot define new methods on non-local type treemap.Map</code></p>

<p>After that, I changed the type alias to a type definition:</p>

<pre class="lang-golang prettyprint-override"><code>type IndexType treemap.Map

func (idx IndexType) Add(k int, v int) {
    idx.Put(k, v)
}
</code>```

Now I started getting the following error: idx.Put undefined (type IndexType has no field or method Put).

The initial thought was that I'm getting this error because Put is defined for a pointer type and based on this naive assumption  I changed the receiver type:

func (idx *IndexType) Add(k int, v int) {
    idx.Put(k, v)
}
```

<p>Doesn't compile: <code>idx.Put undefined (type *IndexType has no field or method Put)</code></p>

<p>Tried another way around:</p>

<pre class="lang-golang prettyprint-override"><code>func (idx IndexType) Add(k int, v int) {
    (&idx).Put(k, v)
}
</code>```

Doesn't compile: (&idx).Put undefined (type *IndexType has no field or method Put)

I also tried type IndexType *treemap.Map but it did not lead me to anything.
I spent a few hours trying to understand the logic behind those errors but I failed to find any logical explanation.

I know that I can achieve my goal by using embedding:

import "github.com/emirpasic/gods/maps/treemap"

type IndexType struct {
    *treemap.Map
}

func (idx IndexType) Add(k int, v int) {
    idx.Put(k, v)
}
```

The code above compiles.

However, the question I still have: is it possible to extend the type like treemap.Map using type operator? gol

答:
It is stated perhaps too plainly in the Go spec:

Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.

That means when you define a type like type Foo Bar where Foo and Bar are both named types, the underlying type of Foo is not Bar. It is Bar's underlying type. If Bar is a struct, then Foo's underlying type is the struct literal that defines Bar (or the type Bar is based on, and so on). Since a struct literal has no methods, neither does Foo; the methods defined on Bar are defined only on Bar, not on the struct literal which might be its underlying type. So Foo has no methods.

Foo also has no "parent type"; it has only its underlying type, which is the struct literal. There is no type hierarchy; you can type Foo Bar, then type Baz Foo, then type Qux Baz, and none of these have any "knowledge" of one another; they simply all share an underlying type, which is just a memory layout for storing the type's data.

Title: Type definition: Pointer vs Value

Body:
I'm new in Go and would like to extend treemap.Map from GoDS project.

I started by defining a type alias for treemap.Map:

import "github.com/emirpasic/gods/maps/treemap"

type Index = treemap.Map

func (idx Index) Add(k int, v int) {
    idx.Put(k, v)
}

Getting the following compilation error: cannot define new methods on non-local type treemap.Map

After that, I changed the type alias to a type definition:

type IndexType treemap.Map

func (idx IndexType) Add(k int, v int) {
    idx.Put(k, v)
}

Now I started getting the following error: idx.Put undefined (type IndexType has no field or method Put).

The initial thought was that I'm getting this error because Put is defined for a pointer type and based on this naive assumption  I changed the receiver type:

func (idx *IndexType) Add(k int, v int) {
    idx.Put(k, v)
}

Doesn't compile: idx.Put undefined (type *IndexType has no field or method Put)

Tried another way around:

func (idx IndexType) Add(k int, v int) {
    (&idx).Put(k, v)
}

Doesn't compile: (&idx).Put undefined (type *IndexType has no field or method Put)

I also tried type IndexType *treemap.Map but it did not lead me to anything.
I spent a few hours trying to understand the logic behind those errors but I failed to find any logical explanation.

I know that I can achieve my goal by using embedding:

import "github.com/emirpasic/gods/maps/treemap"

type IndexType struct {
    *treemap.Map
}

func (idx IndexType) Add(k int, v int) {
    idx.Put(k, v)
}

The code above compiles.

However, the question I still have: is it possible to extend the type like treemap.Map using type operator? gol


问:
How do you drop an in use database in Azure Sql Managed Instance?
When we ran Sql Server in a virtual machine we were able to use the following sql to drop in use databases.

```<code>use master
ALTER DATABASE [TargetDatabase] set single_user with rollback immediate;
Drop database [TargetDatabase]
</code>```

According to the Managed Instance Documentation and our testing set single_user is not supported.  Is there an alternative way to drop in use databases?

答:
I would recommend doing it using powershell. That is more efficient and goes through checks

https://learn.microsoft.com/en-us/powershell/module/az.sql/remove-azsqlinstancedatabase?view=azps-3.5.0

Remove-AzSqlInstanceDatabase -InstanceName '' -ResourceGroupName '' -Name '' -Verbose

Body:
When we ran Sql Server in a virtual machine we were able to use the following sql to drop in use databases.

use master
ALTER DATABASE [TargetDatabase] set single_user with rollback immediate;
Drop database [TargetDatabase]

According to the Managed Instance Documentation and our testing set single_user is not supported.  Is there an alternative way to drop in use databases?


问:
What kind of button does DatePicker and ComboBox use?
I have been trying to find the button that DatePicker and ComboBox uses. I have searched through ComboBoxBase, and all other similar classes, and have been unable to find it. Is there a public version of this?</p>

答:
There is no ComboBoxButton class or public method that creates such a thing. You can try to reproduce what's done in the specific controls by referring to the source code.

The look of the JavaFX controls are defined in their skin classes; so ComboBoxBaseSkin for ComboBox, with some supporting classes for the popup and list view that's displayed inside the popup. For the most part, the skin class defines the layout and behavior (i.e. response to user input), and the actual look (shape of the arrow, colors, etc) is defined by the CSS file.

These buttons are defined in a pretty non-trivial way; for ComboBox the arrow itself is defined as a Region, which is placed inside the arrowButton, which is a StackPane. Then the CSS file defines the shape of the arrow and different colors and borders depending on whether it's pressed, selected, etc.

The source for JavaFX is available via OpenJFX:

Home

ComboBoxBaseSkin

modena.css

In the CSS file, I would search for combo-box (there's a couple of dozen occurrences), and pay particular attention to the .arrow-button and .arrow classes.


问:
IE6: How to get inline base64 images to work with IE6?
How do I get IE6 to display inline base64 encoded images?

```<code><img src="data:image/png;base64,....." />
</code>```

This works in Firefox/Chrome/Safari but not IE6.

答:
My solution run smoothly on IE6. It may help you!</p>

```<code><!--
Content-Type: multipart/related; boundary="=_data-uri"
-->
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#pic {
width:670px;height:710px;
background-image: expression("url(mhtml:" + window.location + "!locoloco)");
}
</style>
</head>
<body>

<div id="pic" ></div>
<div id=test style="display: none;">

--=_data-uri
Content-Location:locoloco
Content-Transfer-Encoding:base64

iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8  /w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
--=_data-uri--

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

ContentLicense: CC BY-SA 2.5

Body:
How do I get IE6 to display inline base64 encoded images?

This works in Firefox/Chrome/Safari but not IE6.

Body:
My solution run smoothly on IE6. It may help you!

<!--
Content-Type: multipart/related; boundary="=_data-uri"
-->
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#pic {
width:670px;height:710px;
background-image: expression("url(mhtml:" + window.location + "!locoloco)");
}
</style>
</head>
<body>

<div id="pic" ></div>
<div id=test style="display: none;">

--=_data-uri
Content-Location:locoloco
Content-Transfer-Encoding:base64

iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8  /w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
--=_data-uri--

</div>
</body>
</html>

ContentLicense: CC BY-SA 3.0


问:
Javascript/html undefined input
For some reason, no matter what I do, my variables are returning undefined for this javascript assignment for homework. I wasn't getting the output i wanted so I used alert to see if I was at least getting a value, but no matter what, the value of op1 is always undefined no matter what is entered into the first operand box, and no matter which way i tried selecting the value of what was in that input box. if someone could help me out here i would appreciate that.    </p>

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Multiply and Divide</title>
<style>
  body {margin-left:100px;}
</style>

<script>
// code two functions multiply and divide functions here
    //hints:
    //when you get a value out of an input, you are getting a string.  To get a number, use
    //parseInt()
    //When you want to output something into the HTML you can use .innerHTML - like
    //document.getElementById("result").innerHTML= "fred";
    var op1 = document.forms["test"]["firstoperand"].value;

    var op2 = document.getElementById("secondoperand").value;

    var ans = "";

    function divide() {
        alert(op1);
    }
    function multiply() {

    }

</script>

</head>
<body>
  <div>
    <h2>JavaScript Exercise 5d </h2>
  </div>
  <form id="test">
    <input type="text" id="firstoperand" placeholder="First Operand"/><br>
    <input type="text" id="secondoperand" placeholder="Second Operand"/><br>
    <input type="button" onclick="divide()" value="Divide" />
    <input type="button" onclick="multiply()" value="Multiply" />
    <p>The answer: <span id="result"></span></p>
  </form>
</body>
</html>
</code>```

答:
Follow the bellow code. I think this code will serve your purpose. and check the tutorial on javaScript dom </p>

```<code>     <!-- html -->
       <form id="test">
        <input type="text" id="firstoperand" placeholder="First Operand"/>
        <input type="button"id="multiply" value="Multiply" />
       </form>

      <!-- js -->
      document.getElementById("multiply").addEventListener("click", multiply);

     function multiply() {
       let firstoperand = document.getElementById('firstoperand').value;
       alert(firstoperand);
     }
</code>```

Title: Javascript/html undefined input

Body:
For some reason, no matter what I do, my variables are returning undefined for this javascript assignment for homework. I wasn't getting the output i wanted so I used alert to see if I was at least getting a value, but no matter what, the value of op1 is always undefined no matter what is entered into the first operand box, and no matter which way i tried selecting the value of what was in that input box. if someone could help me out here i would appreciate that.

<!DOCTYPE html>

<meta charset="utf-8"/>
<title>Multiply and Divide</title>

JavaScript Exercise 5d

  <form id="test">
    <input type="text" id="firstoperand" placeholder="First Operand"/>

    <input type="text" id="secondoperand" placeholder="Second Operand"/>

    <input type="button" onclick="divide()" value="Divide" />
    <input type="button" onclick="multiply()" value="Multiply" />

The answer:

  </form>

Body:
Follow the bellow code. I think this code will serve your purpose. and check the tutorial on javaScript dom

     <!-- html -->
       <form id="test">
        <input type="text" id="firstoperand" placeholder="First Operand"/>
        <input type="button"id="multiply" value="Multiply" />
       </form>

      <!-- js -->
      document.getElementById("multiply").addEventListener("click", multiply);

     function multiply() {
       let firstoperand = document.getElementById('firstoperand').value;
       alert(firstoperand);
     }


问:
How do you write a sequence as a vector?
I have a vector "I" which we can take for example to be (0,1,2,3.....) till an unknown length. I want to create a vector such that x^(I-1) so it will be a vector that looks like (0,x,x^2...).
However I do not know how to write this code and I tried (x^I-1) alone doesn't work. </p>

答:
As commented on your question, R is vectorized. This means that you can specify a vector y of integers, a variable x of length 1, and then take x to the power of y via x^y:

```<code>y <- 0:10
x <- 2
x^y
</code>```

which returns:

```<code>[1]    1    2    4    8   16   32   64  128  256  512 1024
</code>```

Body:
As commented on your question, R is vectorized. This means that you can specify a vector y of integers, a variable x of length 1, and then take x to the power of y via x^y:

y <- 0:10
x <- 2
x^y

which returns:

[1]    1    2    4    8   16   32   64  128  256  512 1024


问:
Can't do anything with helm
I have all sorts of problems with Kubernetes/helm, but I'm really new to it and so I'm not sure what I'm doing at all, despite spending a day trying to work it out.

I have a pod that's in a CrashLoopBackOff situation as I entered an incorrect port number in the Dockerfile. When I do a kubectl -n dev get pods, I can see it in the crash loop. I tried to kill it with helm delete --purge emails but I get the error Error: unknown flag: --purge. I tried to edit the chart with kubectl edit pod emails -n dev, but I get an error saying that the field cannot be changed.

But I can't delete the pod, so I'm not quite sure where to go from here. I've tried without the --purge flag and I get the error Error: uninstall: Release not loaded: emails: release: not found. I get the same if I try helm uninstall emails or pretty much anything.

To get to the crux of the matter, I believe it's because there's been an upgrade to the helm client to version v3.1.0 but the pods were created with v2.11.0. But I don't know how to roll back the client to this version. I've downloaded it via curl -L https://git.io/get_helm.sh | bash -s -- --version v2.11.0 but I can't run helm init and so I'm still on v3.1.0

If I run helm list, I get an empty list. I have 16 running pods I can see through kubectl -n dev get pods but I don't seem to be able to do anything to any of them.

Is this likely to be because my helm client is the wrong version and, if so, how do I roll it back?

Thanks for any suggestions.

答:
The problem is you mixed helm 2 and helm 3

The release was created by helm v2, so you need helm v2 to delete it, helm v3 won't be able to see releases created by helm v2.

You could do the following

download helm v2, delete release (I normally have both helm 2/3 in one folder, rename helm v2 to helm2).

Optional, you can delete tiller, , as helm v3 won't need tiller anymore. just make sure no other release deployed by helm v2

update your helm chart to use correct port

use helm v3 deploy your updated chart

Title: Can't do anything with helm


问:
Why does my template literal not create a new line?
```<code>var request = require("request");
request("https://jsonplaceholder.typicode.com/users/1", function(
  error,
  response,
  body
) {
  if (!error && response.statusCode == 200) {
    //Things worked!
    var parsedData = JSON.parse(body);
    console.log(parsedData);
    document.getElementById(
      "text"
    ).innerHTML = `${parsedData.name} lives in Saint John NB.
     Her street name is ${parsedData.address.street}`; //This should be a new line??????
  }
});
</code>```

Can someone explain why there is not a new line in my template literal here?

答:
The template literal does contain a newline. But when the browser renders the HTML, it re-wraps the line.

If you want to see the text without being reformatted, put it in a ```</code> element or set the style of the element to <code>white-space: pre;</code> with CSS.</p>

<p>Or use <code><br></code> in the HTML:</p>

```  if (!error && response.statusCode == 200) {
    //Things worked!
    var parsedData = JSON.parse(body);
    console.log(parsedData);
    document.getElementById(
      "text"
    ).innerHTML = `${parsedData.name} lives in Saint John NB.

     Her street name is ${parsedData.address.street}`; //This should be a new line??????
  }
```

Or assign to .innerText instead of .innerHTML, this retains newlines (but not other formatting like indentation).

Body:
var request = require("request");
request("https://jsonplaceholder.typicode.com/users/1", function(
  error,
  response,
  body
) {
  if (!error && response.statusCode == 200) {
    //Things worked!
    var parsedData = JSON.parse(body);
    console.log(parsedData);
    document.getElementById(
      "text"
    ).innerHTML = `${parsedData.name} lives in Saint John NB.
     Her street name is ${parsedData.address.street}`; //This should be a new line??????
  }
});

Can someone explain why there is not a new line in my template literal here?

Body:
The template literal does contain a newline. But when the browser renders the HTML, it re-wraps the line.

If you want to see the text without being reformatted, put it in a <pre> element or set the style of the element to white-space: pre; with CSS.

Or use <br> in the HTML:

  if (!error && response.statusCode == 200) {
    //Things worked!
    var parsedData = JSON.parse(body);
    console.log(parsedData);
    document.getElementById(
      "text"
    ).innerHTML = `${parsedData.name} lives in Saint John NB.<br>
     Her street name is ${parsedData.address.street}`; //This should be a new line??????
  }

Or assign to .innerText instead of .innerHTML, this retains newlines (but not other formatting like indentation).


问:
I have a LINQ statement that is partially query and partially method. How can I do this using one or the other?
Here is my query as it stands now:

```<code>Goals = await (from p in _context.FixtureActivityTb
               where p.ActivityType.Trim() == "G"
               group p by p.PlayerId into x
               join j in _context.PlayerTb on x.Key equals j.PlayerId
               select new Stats
               {
                   Name = j.GivenName,
                   pID = j.PlayerId,
                   TeamId = j.TeamId,
                   Count = x.Count()
               })
   .OrderByDescending(s => s.Count)
   .ThenBy(s => s.Name)
   .Take(10)
   .ToListAsync();
</code>```

As you can see this is a mix of method and query. I should be able to do a join, where, and add the data to a custom class all in Method, however so far I have not been able to put it all together. Any guidance will be appreciated.

I will include these other items, however, I think they are beside the point.

Variable Declaration:

```<code>public IList<Stats> Goals { get; set; }
</code>```

Class:

```<code>public class Stats
{
    public Guid pID { get; set; }
    public string TeamId { get; set; }
    public string Name { get; set; }
    public int Count { get; set; }
}
</code>```

答:
If i understand your question (and the lack of coffee isn't affecting me), to get this all to a Linq chain method, it should be as simple as

```<code>Goals = await _context.FixtureActivityTb.Where(p => p.ActivityType.Trim() == "G")
                      .GroupBy(p => p.PlayerId)
                      .Join(_context.PlayerTb, x => x.Key, j => j.PlayerId, (x, j)
                          => new Stats
                             {
                                Name = j.GivenName,
                                pID = j.PlayerId,
                                TeamId = j.TeamId,
                                Count = x.Count()
                             })
                      .OrderByDescending(s => s.Count)
                      .ThenBy(s => s.Name)
                      .Take(10)
                      .ToListAsync();
</code>```

Body:
Here is my query as it stands now:

Goals = await (from p in _context.FixtureActivityTb
               where p.ActivityType.Trim() == "G"
               group p by p.PlayerId into x
               join j in _context.PlayerTb on x.Key equals j.PlayerId
               select new Stats
               {
                   Name = j.GivenName,
                   pID = j.PlayerId,
                   TeamId = j.TeamId,
                   Count = x.Count()
               })
   .OrderByDescending(s => s.Count)
   .ThenBy(s => s.Name)
   .Take(10)
   .ToListAsync();

As you can see this is a mix of method and query. I should be able to do a join, where, and add the data to a custom class all in Method, however so far I have not been able to put it all together. Any guidance will be appreciated.

I will include these other items, however, I think they are beside the point.

Variable Declaration:

public IList<Stats> Goals { get; set; }

Class:

public class Stats
{
    public Guid pID { get; set; }
    public string TeamId { get; set; }
    public string Name { get; set; }
    public int Count { get; set; }
}

Body:
If i understand your question (and the lack of coffee isn't affecting me), to get this all to a Linq chain method, it should be as simple as

Goals = await _context.FixtureActivityTb.Where(p => p.ActivityType.Trim() == "G")
                      .GroupBy(p => p.PlayerId)
                      .Join(_context.PlayerTb, x => x.Key, j => j.PlayerId, (x, j)
                          => new Stats
                             {
                                Name = j.GivenName,
                                pID = j.PlayerId,
                                TeamId = j.TeamId,
                                Count = x.Count()
                             })
                      .OrderByDescending(s => s.Count)
                      .ThenBy(s => s.Name)
                      .Take(10)
                      .ToListAsync();


问:
Record processing using apache NiFi
I have a csv with following data :

```<code>id,name,loan,to_pay,paid
1,sachith,"house,cc,vehicle","10000,24500,233300","2000,5000,2030"
2,nalaka,"edu,cc","3400,5000","200,450"
</code>```

Here one user can have multiple loans (max 5). I want to split this into multiple rows.

```<code>id,name,loan,to_pay,paid
1,sachith,house,10000,2000
1,sachith,cc,24500,5000
1,sachith,vehicle,233300,2030
2,nalaka,edu,3400,200
....
</code>```

Is there a specific processor for doing this?

Edit : Warning message in ExecuteGroovyScript after @daggett answer:

```<code>GroovyScript is invalid because
ord.codehaus.groovy.control.MultiCompilationErrorsException: startup failed:
General error during conversion : Error grabbing Grapes  --[unresolved dependency: org.apache.commons#commons-csv;1.8not found] java.lang/RuntimeExceptopm
</code>```

答:
use ExecuteGroovyScript processor:

//for complex csv let's use apache library for parsing/printing
@Grab(group='org.apache.commons', module='commons-csv', version='1.8')
import org.apache.commons.csv.*

def ff=session.get()
if(!ff)return

ff.write{streamIn, streamOut->
    streamOut.withWriter("UTF-8"){w->
        def printer = CSVFormat.EXCEL.withHeader("id","name","loan","to_pay","paid").print(w)
        streamIn.withReader("UTF-8"){r->
            def parser = CSVFormat.EXCEL.withHeader().parse(r)
            parser.each{row->
                //split multivalues and print them in a loop
                def loan   = row.loan.split(',')
                def to_pay = row.to_pay.split(',')
                def paid   = row.paid.split(',')
                for(int i=0;i<loan.size();i++){
                    printer.printRecord(row.id, row.name, loan[i], to_pay[i], paid[i])
                }
            }
        }
        printer.flush()
    }
}
REL_SUCCESS<<ff
```

Title: Record processing using apache NiFi

Body:
I have a csv with following data :

id,name,loan,to_pay,paid
1,sachith,"house,cc,vehicle","10000,24500,233300","2000,5000,2030"
2,nalaka,"edu,cc","3400,5000","200,450"

Here one user can have multiple loans (max 5). I want to split this into multiple rows.

id,name,loan,to_pay,paid
1,sachith,house,10000,2000
1,sachith,cc,24500,5000
1,sachith,vehicle,233300,2030
2,nalaka,edu,3400,200
....

Is there a specific processor for doing this?

Edit : Warning message in ExecuteGroovyScript after @daggett answer:

GroovyScript is invalid because
ord.codehaus.groovy.control.MultiCompilationErrorsException: startup failed:
General error during conversion : Error grabbing Grapes  --[unresolved dependency: org.apache.commons#commons-csv;1.8not found] java.lang/RuntimeExceptopm


问:
How to dispatch events from an OpenLayers overlay to the map
When adding an overlay element to a map in OpenLayers, I can set the stopEvent property of the overlay to true. This enables me to handle different events like mouse moves, clicks etc. on the overlay element.

But I also would like some events not be stopped, especially the wheel event. I would like to have this event propagated, so that the zoom behaviour of the map works even when the mouse is over the overlay.

How can I achieve this? I can intercept the wheel event in the overlay, how can I send this to the map element or wherever it is needed to trigger the noemal scroll behaviour?

答:
Just for the records:

As I am using this for a JavaFX integration (mapjfx) I capture the wheel event, send it to the Java side of the integration and in/decrease the zoom level there and send it back to Javascript. So I don't need to worry about handling it in the Javascript layer.


答:
If your input is called x:

```<code>r = np.full(len(x),2)
d = np.diff(x)==1
r[1:]-=d
r[:-1]-=d
np.repeat(x,r).reshape(-1,2)
</code>```

Output:

```<code>array([[  1,   2],
       [  6,   6],
       [ 12,  14],
       [ 16,  16],
...
</code>```

This works by repeating each item twice (default) but subtract 1 time for each left or right direct neighbor: So if I'm at the left or right end of a stretch I get repeated once, if I'm inside I get repeated zero times.

Title: Get Start and Stop Values For Incrementing Groups in NumPy Vector

Body:
I have a NumPy vector that is sorted and contains no repeats like:

[  1,   2,   6,  12,  13,  14,  16,  18,  19,  22,  23,  26,  29,
  31,  32,  34,  37,  38,  39,  40,  42,  43,  44,  49,  50,  52,
  55,  63,  64,  67,  68,  75,  78,  82,  84,  86,  88,  90,  93,
  95,  97,  98, 100, 103, 104, 106, 114, 119, 123, 124, 127, 129,
 130, 131, 134, 137, 139, 141, 142, 146, 149, 151, 153, 154, 155,
 159, 160, 161, 162, 165, 166, 167, 171, 173, 180, 181, 184, 186,
 189, 191, 194, 195, 196, 202, 208, 210, 212, 215, 216, 218, 223,
 224, 225, 226, 231, 233, 235, 239, 240, 241, 245, 248, 252, 253,
 259, 260, 261, 264, 271, 272, 273, 276, 279, 280, 285, 287, 290,
 291, 292, 293, 296, 297, 301, 304, 306, 307, 311, 312, 313, 319,
 320, 323, 324, 325, 326, 332, 335, 336, 337, 338, 339, 341, 342,
 345, 346, 349, 352, 355, 359, 364, 365, 367, 369, 373, 376, 378,
 380, 382, 386, 387, 388, 391, 399, 400, 401, 405, 408, 409, 410,
 413, 414, 415, 416, 423, 427, 428, 429, 432, 433, 434, 435, 437,
 439, 440, 443, 448, 449, 451, 453, 455, 459, 461, 464, 465, 466,
 467, 468, 470, 471, 473, 476, 478, 482, 487, 488, 491, 495, 498,
 501, 502, 503, 505, 506, 507, 514, 518, 519, 520, 522, 523, 525,
 528, 530, 532, 534, 538, 539, 540, 544, 550, 551, 556, 558, 568,
 571, 573, 577, 578, 582, 584, 585, 592, 597, 599, 603, 605, 607,
 609, 610, 612, 616, 618, 621, 623, 625, 626, 628, 630, 631, 632,
 633, 636, 637, 639, 642, 644, 647, 651, 653, 654, 656, 661, 662,
 666, 668, 670, 672, 673, 674, 675, 676, 682, 684, 687, 688, 690,
 692, 693, 694, 696, 697, 698, 699, 705, 706, 707, 708, 713, 714,
 719, 726, 727, 729, 730, 736, 737, 739, 740, 741, 742, 744, 748,
 749, 753, 758, 759, 762, 766, 771, 772, 774, 775, 778, 780, 782,
 786, 787, 789, 791, 793, 796, 797, 798, 799, 803, 804, 807, 809,
 811, 814, 815, 817, 819, 821, 827, 831, 833, 837, 842, 846, 849,
 851, 854, 855, 858, 865, 866, 867, 868, 870, 872, 873, 874, 880,
 881, 882, 884, 885, 890, 892, 893, 894, 895, 896, 897, 899, 900,
 902, 908, 912, 913, 915, 916, 920, 921, 924, 927, 930, 933, 941,
 942, 946, 950, 953, 957, 960, 963, 964, 967, 969, 972, 973, 975,
 978, 981, 983, 985, 986, 991, 992, 993, 995]

What I need is to find the start and stop values where consecutive (increment by one) numbers exist. So the output would be something like:

[[  1,  2],
 [  6,  6],
 [ 12, 14],
 [ 16, 16],
 [ 18, 19],
 [ 22, 23],
 [ 26, 26],
 [ 29, 29],
 [ 31, 32],
 [ 34, 34],
 [ 37, 40],
 [ 42, 44],
 .
 .
 .]

I think that I could do something like (x[:-1] - x[1:]) == 1 to build a True/False vector but then I'd have to loop through this vector to identify the start/stop values. I can't seem to come up with a vectorized solution beyond this.

Body:
If your input is called x:

r = np.full(len(x),2)
d = np.diff(x)==1
r[1:]-=d
r[:-1]-=d
np.repeat(x,r).reshape(-1,2)

Output:

array([[  1,   2],
       [  6,   6],
       [ 12,  14],
       [ 16,  16],
...

This works by repeating each item twice (default) but subtract 1 time for each left or right direct neighbor: So if I'm at the left or right end of a stretch I get repeated once, if I'm inside I get repeated zero times.


问:
Getting rid of redundant 2D points without losing order
I have the following points:

```<code>import numpy as np
points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])
</code>```

When I plot them, I get this shape:

```<code>import matplotlib.pyplot as plt
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)
</code>```

As you can see from the list of points, some of them are redundant (i.e look at point 1 and 2 (starting at 0)).

To only keep the non-redundant points, I reverted to the answer from this question:
Removing duplicate columns and rows from a NumPy  2D array

```<code>def unique_2D(a):
    order = np.lexsort(a.T)
    a = a[order]
    diff = np.diff(a, axis=0)
    ui = np.ones(len(a), 'bool')
    ui[1:] = (diff != 0).any(axis=1)
    return a[ui]
</code>```

I apply this function to my points and I get:

```<code>non_redundant_points = unique_2D(points)
</code>```

Here is the printed list of retained points:

```<code>[[ 50.51  66.04]
 [ 49.85  66.17]
 [ 49.69  66.21]
 [ 49.79  66.35]
 [ 49.8   66.35]
 [ 44.68  67.2 ]
 [ 44.63  67.21]
 [ 44.48  67.24]
 [ 44.65  67.25]]
</code>```

However, now I face the following issue: When I plot them, the order is somehow not preserved...

```<code>x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)
</code>```

Do you know how I could solve this?

For easier copy and paste, here is the full code:

```<code>import numpy as np
import matplotlib.pyplot as plt

points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])

x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

def unique_2D(a):
        order = np.lexsort(a.T)
        a = a[order]
        diff = np.diff(a, axis=0)
        ui = np.ones(len(a), 'bool')
        ui[1:] = (diff != 0).any(axis=1)
        return a[ui]

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)
</code>```

答:
You can use np.unique to get the unique elements and return_index=True to get the indices of the original array. You can then use them to sort the returned unique array to get the original index order

```<code>points = np.array([[49.8, 66.35],
                   [49.79, 66.35],
                   [49.79, 66.35], ... ] # Your original input array

points, idx = np.unique(points, axis=0, return_index=True)
print (idx)
# [ 6  7  3  8  9  1  0 10 11]

arr = points[np.argsort(idx), :]

print (arr)

# [[49.8  66.35]
#  [49.79 66.35]
#  [44.65 67.25]
#  [44.48 67.24]
#  [44.63 67.21]
#  [44.68 67.2 ]
#  [49.69 66.21]
#  [49.85 66.17]
#  [50.51 66.04]]
</code>```

Plotting them

```<code>plt.plot(arr[:, 0], arr[:, 1])
</code>```

Body:
I have the following points:

import numpy as np
points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])

When I plot them, I get this shape:

import matplotlib.pyplot as plt
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

As you can see from the list of points, some of them are redundant (i.e look at point 1 and 2 (starting at 0)).

To only keep the non-redundant points, I reverted to the answer from this question:
Removing duplicate columns and rows from a NumPy  2D array

def unique_2D(a):
    order = np.lexsort(a.T)
    a = a[order]
    diff = np.diff(a, axis=0)
    ui = np.ones(len(a), 'bool')
    ui[1:] = (diff != 0).any(axis=1)
    return a[ui]

I apply this function to my points and I get:

non_redundant_points = unique_2D(points)

Here is the printed list of retained points:

[[ 50.51  66.04]
 [ 49.85  66.17]
 [ 49.69  66.21]
 [ 49.79  66.35]
 [ 49.8   66.35]
 [ 44.68  67.2 ]
 [ 44.63  67.21]
 [ 44.48  67.24]
 [ 44.65  67.25]]

However, now I face the following issue: When I plot them, the order is somehow not preserved...

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)

Do you know how I could solve this?

For easier copy and paste, here is the full code:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])

x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

def unique_2D(a):
        order = np.lexsort(a.T)
        a = a[order]
        diff = np.diff(a, axis=0)
        ui = np.ones(len(a), 'bool')
        ui[1:] = (diff != 0).any(axis=1)
        return a[ui]

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)

Body:
You can use np.unique to get the unique elements and return_index=True to get the indices of the original array. You can then use them to sort the returned unique array to get the original index order

points = np.array([[49.8, 66.35],
                   [49.79, 66.35],
                   [49.79, 66.35], ... ] # Your original input array

points, idx = np.unique(points, axis=0, return_index=True)
print (idx)
# [ 6  7  3  8  9  1  0 10 11]

arr = points[np.argsort(idx), :]

print (arr)

# [[49.8  66.35]
#  [49.79 66.35]
#  [44.65 67.25]
#  [44.48 67.24]
#  [44.63 67.21]
#  [44.68 67.2 ]
#  [49.69 66.21]
#  [49.85 66.17]
#  [50.51 66.04]]

Plotting them

plt.plot(arr[:, 0], arr[:, 1])


问:
What does this "Lambda Expression" do?
Just come across the following line of code and having a hard time finding documentation for it, is it a lambda expression? What does this do?

```<code>temp = Regex.Replace(url, REGEX_COOKIE_REPLACE,match => cookie.Values[match.Groups["CookieVar"].Value]);
</code>```

Specifically interested in the =>.

答:
The RegEx.Replace runs the lambda for every match of REGEX_COOKIE_REPLACE in url and "replaces" the match with the lambdas result.

The lambda (or shorthand delegate)

```<code>match => cookie.Values[match.Groups["CookieVar"].Value]
</code>```

uses the Value of the "CookieVar"Group,of theMatch,to look up a substitution in thecookie.Valuescollection. The lookup value replaces the match.

To tell you more about the "CookieVar" group we would need to see an evaluation of REGEX_COOKIE_REPLACE.

Title: What does this "Lambda Expression" do?

Body:
Just come across the following line of code and having a hard time finding documentation for it, is it a lambda expression? What does this do?

temp = Regex.Replace(url, REGEX_COOKIE_REPLACE,match => cookie.Values[match.Groups["CookieVar"].Value]);

Specifically interested in the =>.

Body:
The RegEx.Replace runs the lambda for every match of REGEX_COOKIE_REPLACE in url and "replaces" the match with the lambdas result.

The lambda (or shorthand delegate)

match => cookie.Values[match.Groups["CookieVar"].Value]

uses the Value of the "CookieVar"Group,of theMatch,to look up a substitution in thecookie.Valuescollection. The lookup value replaces the match.

To tell you more about the "CookieVar" group we would need to see an evaluation of REGEX_COOKIE_REPLACE.


问:
Convolve a 3D array with three kernels (x, y, z) in python
I have a 3D image and three kernels k1, k2, k3 in the x, y and z direction.

```<code>img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension
</code>```

I can use numpy.convolve iteratively to calculate the convolution like this:

```<code>for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[1])
      oneline=img[i,j,:]
      img[i,j,:]=np.convolve(oneline, k1, mode='same')

for i in np.arange(img.shape[1])
   for j in np.arange(img.shape[2])
      oneline=img[:,i,j]
      img[:,i,j]=np.convolve(oneline, k2, mode='same')

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[2])
      oneline=img[i,:,j]
      img[i,:,j]=np.convolve(oneline, k3, mode='same')
</code>```

Is there an easier way to do it? Thanks.

答:
You can use scipy.ndimage.convolve1d which allows you to specify an axis argument.

```<code>import numpy as np
import scipy

img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension

# Convolve over all three axes in a for loop
out = img.copy()
for i, k in enumerate((k1, k2, k3)):
    out = scipy.ndimage.convolve1d(out, k, axis=i)
</code>```

Body:
I have a 3D image and three kernels k1, k2, k3 in the x, y and z direction.

img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension

I can use numpy.convolve iteratively to calculate the convolution like this:

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[1])
      oneline=img[i,j,:]
      img[i,j,:]=np.convolve(oneline, k1, mode='same')

for i in np.arange(img.shape[1])
   for j in np.arange(img.shape[2])
      oneline=img[:,i,j]
      img[:,i,j]=np.convolve(oneline, k2, mode='same')

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[2])
      oneline=img[i,:,j]
      img[i,:,j]=np.convolve(oneline, k3, mode='same')

Is there an easier way to do it? Thanks.

Body:
You can use scipy.ndimage.convolve1d which allows you to specify an axis argument.

import numpy as np
import scipy

img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension

# Convolve over all three axes in a for loop
out = img.copy()
for i, k in enumerate((k1, k2, k3)):
    out = scipy.ndimage.convolve1d(out, k, axis=i)


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

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

Could this throw a random compile or runtime error?

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

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

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

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

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

答:
In addition to Andreas' answer...

There is 1 situation where you definitely (or, at least, most likely) don't want to leave a semi colon, and it's after a "then". The following code will show "B" in the message box.

```<code>procedure TForm3.FormCreate(Sender: TObject);
var
  S : String;
begin
  S := 'A';
  if 1 = 2 then;
    S := 'B';

  ShowMessage(S);
end;
</code>```

From the top of my head, that's the only case where inserting a semi colon changes the code generations by itself.

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

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

Could this throw a random compile or runtime error?

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

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

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

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

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

Body:
In addition to Andreas' answer...

There is 1 situation where you definitely (or, at least, most likely) don't want to leave a semi colon, and it's after a "then". The following code will show "B" in the message box.

procedure TForm3.FormCreate(Sender: TObject);
var
  S : String;
begin
  S := 'A';
  if 1 = 2 then;
    S := 'B';

  ShowMessage(S);
end;

From the top of my head, that's the only case where inserting a semi colon changes the code generations by itself.


问:
How to add attribute to all documents in a collection, with same data of another attribute in MongoDB?
I've seen this question and it could be useful, but I need some extra steps.

I have a collection of Sites filled with name, data and a field called infoBox that is an object.

```<code>infoBox: {
    coordX: {
      type: Number,
    },
    coordY: {
      type: Number,
    },
    type: {
      type: Number,
      enum: [InfoBoxType.line, InfoBoxType.horizontal, InfoBoxType.vertical],
    },
    midPoint: {
      coordX: {
        type: Number,
      },
      coordY: {
        type: Number,
      },
    },
</code>```

So, I need to add another attibute to all infoboxes of the sites called "levels" that is an array, and this field must contains two objects like InfoBox, with the same values, but with empty 'levels'. (both infobox 1 & 2 with same values).This is to initialize the DB, later these values will be editted by the users.

Trying to be clear, I actually have:

```<code>Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy
</code>```

and I need

```<code>Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy
        levels
            infobox1
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)
            infobox2
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)
</code>```

How can I accomplish this?

Extra info:
Mongo version 4.2

EDIT

I am trying to make it with something like this, but with no luck yet:

```<code>let sites = await this.siteModel.find({});
 const firstZoom = site.infoBox;
 const secondZoom =  site.infoBox;

  const levelss = [
    firstZoom,
    secondZoom,
  ];

await this.siteModel.update({ _id: site._id }, { $set: { 'infoBox.levels.$': levelss } });
</code>```

答:
Just use . to create a new object key.

```<code>Site.levels = {}
Site.levels.infobox1 = Site.infobox
Site.levels.infobox2 = Site.infobox
</code>```

Body:
I've seen this question and it could be useful, but I need some extra steps.

I have a collection of Sites filled with name, data and a field called infoBox that is an object.

infoBox: {
    coordX: {
      type: Number,
    },
    coordY: {
      type: Number,
    },
    type: {
      type: Number,
      enum: [InfoBoxType.line, InfoBoxType.horizontal, InfoBoxType.vertical],
    },
    midPoint: {
      coordX: {
        type: Number,
      },
      coordY: {
        type: Number,
      },
    },

So, I need to add another attibute to all infoboxes of the sites called "levels" that is an array, and this field must contains two objects like InfoBox, with the same values, but with empty 'levels'. (both infobox 1 & 2 with same values).This is to initialize the DB, later these values will be editted by the users.

Trying to be clear, I actually have:

Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy

and I need

Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy
        levels
            infobox1
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)
            infobox2
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)

How can I accomplish this?

Extra info:
Mongo version 4.2

EDIT

I am trying to make it with something like this, but with no luck yet:

let sites = await this.siteModel.find({});
 const firstZoom = site.infoBox;
 const secondZoom =  site.infoBox;

  const levelss = [
    firstZoom,
    secondZoom,
  ];

await this.siteModel.update({ _id: site._id }, { $set: { 'infoBox.levels.$': levelss } });

Body:
Just use . to create a new object key.

Site.levels = {}
Site.levels.infobox1 = Site.infobox
Site.levels.infobox2 = Site.infobox


问:
How can I extend the FindObjectsByTag to filter multiple parents of the found objects?
```<code>private List<GameObject> FindDoors(string[] parents)
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        List<GameObject> toRemove = new List<GameObject>();
        for (int i = 0; i < allDoors.Count; i++)
        {
            for (int x = 0; x < parents.Length; x++)
            {
                if (allDoors[i].transform.parent.name != parents[x])
                {
                    toRemove.Add(allDoors[i]);
                }
            }
        }
        foreach (var it in toRemove)
        {
            allDoors.Remove(it);
        }

        foreach (GameObject door in allDoors)
        {
            Debug.Log("Door Parent : " + door.transform.parent);
        }

        return allDoors;
    }
</code>```

Usage :

```<code>var allDoors = FindDoors(new string[]{ "Wall_Door_Long_01", "Wall_Door_Long_02" });
</code>```

But in the function FindDoors the return allDoors is empty. I think the problem is at this IF :

```<code>if (allDoors[i].transform.parent.name != parents[x])
</code>```

Once it's Wall_Door_Long_01 so if it's Wall_Door_Long_01 it will not remove the item but next it's Wall_Door_Long_02 so now the it's true and will remove the even if the parent name is Wall_Door_Long_01 and same if it's Wall_Door_Long_02

And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall_Door_Long_01 and not Wall_Door_Long_02

答:
Why your way didnt work: The way you did it, you looped through all the doors possible parents and said if you arent it remove, well, it could be say A or B, if it was B it would have been removed because it wasnt A.

Along the lines of previously From your previous question: Just like before you can do .Where(o => parents.Contains(o.transform.parent.name)); if parents is a list, itss late and its been a hard day I dont remember if linq lets you do the same with arrays (sorry, but its a small thing)

Body:
private List<GameObject> FindDoors(string[] parents)
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        List<GameObject> toRemove = new List<GameObject>();
        for (int i = 0; i < allDoors.Count; i++)
        {
            for (int x = 0; x < parents.Length; x++)
            {
                if (allDoors[i].transform.parent.name != parents[x])
                {
                    toRemove.Add(allDoors[i]);
                }
            }
        }
        foreach (var it in toRemove)
        {
            allDoors.Remove(it);
        }

        foreach (GameObject door in allDoors)
        {
            Debug.Log("Door Parent : " + door.transform.parent);
        }

        return allDoors;
    }

Usage :

var allDoors = FindDoors(new string[]{ "Wall_Door_Long_01", "Wall_Door_Long_02" });

But in the function FindDoors the return allDoors is empty. I think the problem is at this IF :

if (allDoors[i].transform.parent.name != parents[x])

Once it's Wall_Door_Long_01 so if it's Wall_Door_Long_01 it will not remove the item but next it's Wall_Door_Long_02 so now the it's true and will remove the even if the parent name is Wall_Door_Long_01 and same if it's Wall_Door_Long_02

And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall_Door_Long_01 and not Wall_Door_Long_02


问:
Why is proxy pattern Structural Pattern and why is State Pattern behavioral pattern?
why is proxy pattern a structural pattern and why is state pattern a behavioral pattern. What is the criteria for determining a new pattern should be considered structural or behavioral?</p>

答:
Lets begin with the definition of Structural and Behaviroal patterns.

Structural Patterns: Structural patterns focus on how classes and objects are composed to form larger structures. Inheritance is the mechanism the structural class patterns use to compose implementations or interfaces. Structural object patterns illustrate ways to compose objects in ways that provide them with new functionality.

Behavioral Patterns: Behavioral patterns are patterns that implement algorithms and are concerned with assigning responsibilities between objects. They also describe patterns of communications between object and classes. By using behavioral patterns the designer is able channel his/her focus away from flow of control and center his/her attention on the way the objects are interconnected. Behavioral class patterns distribute behavior among classes by using the object-oriented technique of inheritance. Behavioral object patterns on the other hand use object composition to perform their functions.

If you ponder over these the whole premise is if its to do with modelling a class/object structure go for Structural Patterns and if you are dealing with changing behaviour then Behavioral patterns will come to your rescue.

In case of Proxy, you are just wrapping the target and forwarding the call. In case of State you actually use inheritance (as described in definition above) and hence polymorphism to change the run time behavior.

Hope that helps.


问:
Update SQLite Database Android RecyclerView Iterate
I have one activity named cart (Shopping Cart). I use SQLite to store the items and I display the data in the RecyclerView. My problem is when I need to increase or decrease the quantity because my code takes the default quantity (1) and the increase is equal with 2 all-time and decreases with 0. I need to update my DataBase I know that, but I really don't understand how. I see 2 alternatives with Sqlexec and ContentValues, but I really don't know how to implement it. If someone can help me, I will really appreciate it. I put my adapter class and DB here.

```<code>public class cartItemRecyclerView extends RecyclerView.Adapter<cartItemRecyclerView.ViewHolder>{

ArrayList<items> itemsList;
Context context;

interface IImageButtonListener{
    void onImageButtonClick(View view,int pos,boolean isDecrease);
}

public cartItemRecyclerView(Context context, ArrayList<items> itemsList){
    this.context = context;
    this.itemsList = itemsList;
}

public cartItemRecyclerView(ArrayList<items> item) {
    this.itemsList = item;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View contactView = inflater.inflate(R.layout.list_cart_item_view,parent,false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(contactView);

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    // Get the data model based on position
    items itm = itemsList.get(position);

    // Set item views based on your view and data model

    holder.nameC.setText(itm.getlName());
    holder.iconC.setImageResource(itm.getlImageId());
    holder.priceC.setText(itm.getlPrice()+ "");
    holder.quantityC.setText(itm.getQuantity()+"");

    holder.setListener(new IImageButtonListener() {
        @Override
        public void onImageButtonClick(View view, int pos, boolean isDecrease) {
            if(isDecrease){
                int i = itemsList.get(pos).getQuantity();
                i++;
                // Update in database
                holder.quantityC.setText(i+"");

            }
            else {
                int i = itemsList.get(pos).getQuantity();
                i--;
                // Update in database
                holder.quantityC.setText(i+"");
            }

        }
    });

}

@Override
public int getItemCount() {
    return itemsList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    public TextView nameC, priceC, quantityC;
    public ImageView increaseC, decreaseC, iconC;
    IImageButtonListener listener;

    public void setListener(IImageButtonListener listener){
        this.listener = listener;
    }

    public ViewHolder(View itemView){
        super(itemView);

        nameC = itemView.findViewById(R.id.name_item_cart);
        priceC = itemView.findViewById(R.id.price_item_cart);
        quantityC = itemView.findViewById(R.id.textview_quantity_items);
        increaseC = itemView.findViewById(R.id.image_increase_quantity);
        decreaseC = itemView.findViewById(R.id.image_decrease_quantity);
        iconC = itemView.findViewById(R.id.icon_item_cart);

        // Event
        increaseC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onImageButtonClick(v, getAdapterPosition(),true);
            }
        });

        decreaseC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onImageButtonClick(v, getAdapterPosition(),false);
            }
        });
    }
}
</code>```

And this is the DB SQLite code.

```<code>public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "favorites.db";
public static final String TABLE_NAME_CART = "cart_table";

public static final String COL_1 = "IMAGE";
public static final String COL_2 = "NAME";
public static final String COL_3 = "PRICE";
public static final String COL_4 = "DETAILS";
public static final String COL_5 = "MODEL";
public static final String COL_6 = "IMAGEE";
public static final String COL_7 = "IMAGEEE";
public static final String COL_8 = "QUANTITY";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

private static DatabaseHelper sDatabaseHelper;

public static DatabaseHelper getInstance(Context context) {
    if (sDatabaseHelper == null) {
        sDatabaseHelper = new DatabaseHelper(context);
    }
    return sDatabaseHelper;
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE " + TABLE_NAME_CART + " (" + COL_1 + " INTEGER, " + COL_2 + " VARCHAR, " + COL_3 + " INTEGER, " + COL_4 + " VARCHAR, " + COL_5 + " VARCHAR, " + COL_6 + " INTEGER, " + COL_7 + " INTEGER, " + COL_8 + " INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CART);
    onCreate(db);
}

// Insert Data in cart table
public boolean insertDataCart(items items) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, items.getlImageId());
    contentValues.put(COL_2, items.getlName());
    contentValues.put(COL_3, items.getlPrice());
    contentValues.put(COL_4, items.getlDetails());
    contentValues.put(COL_5, items.getlModel());
    contentValues.put(COL_6, items.getlImageId1());
    contentValues.put(COL_7, items.getlImageId2());
    contentValues.put(COL_8, items.getQuantity());

    long result = db.insert(TABLE_NAME_CART, null, contentValues);

    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

// See Data Cart
public ArrayList<items> getAllDataCart() {
    ArrayList<items> favItem = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME_CART, null);

    while (res.moveToNext()) {
        int img = res.getInt(0);
        String name = res.getString(1);
        int price = res.getInt(2);
        String details = res.getString(3);
        String model = res.getString(4);
        int img1 = res.getInt(5);
        int img2 = res.getInt(6);
        int quantity = res.getInt(7);
        items newItems = new items(name, price, img, img1, img2, details, model,quantity);
        favItem.add(newItems);
    }
    return favItem;
}
</code>```

Here I use the RecyclerView

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

private DatabaseHelper favoriteDbHelper;
private ArrayList<items> item;
private cartItemRecyclerView cartItemRecyclerView;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cart);

    recyclerView = (RecyclerView) findViewById(R.id.cart_recycler);

    favoriteDbHelper = new DatabaseHelper(this);
    item = favoriteDbHelper.getAllDataCart();

    cartItemRecyclerView = new cartItemRecyclerView(item,favoriteDbHelper,this);
    recyclerView.setAdapter(cartItemRecyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
</code>```

}

答:
You can try this.

Add to DatabaseHelper

```<code>    public boolean updateDataCard(int id, int quantity) {

    ContentValues val = new ContentValues();

    val.put(COL_8, quantity);

    int result =  db.update(TABLE_NAME_CART, val, "IMAGE=" + id, null);
    if (result == -1) {
     return false;
    } else {
     return true;
    }
}
</code>```

You must pass your database object. You can use with constructor method.

```<code>ArrayList<items> itemsList;
Context context;
YourDBObject db;

interface IImageButtonListener{
 void onImageButtonClick(View view,int pos,boolean isDecrease);
 }

 public cartItemRecyclerView(Context context, ArrayList<items>
  itemsList,YourDBObject db){
     this.context = context;
     this.itemsList = itemsList;
     this.db = db;
}
</code>```

And Then you can call.

```<code>   if(isDecrease){
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i++;
            // Update in database
            if(i <= 2){
            db.updateDataCard(id,i)
            holder.quantityC.setText(i+"");
           }
        }
        else {
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i--;
            // Update in database
            if( i < 2 && i >= 0 ){
               db.updateDataCard(id,i)
               holder.quantityC.setText(i+"");
            }
</code>```

}

I hope i can help you.

Body:
I have one activity named cart (Shopping Cart). I use SQLite to store the items and I display the data in the RecyclerView. My problem is when I need to increase or decrease the quantity because my code takes the default quantity (1) and the increase is equal with 2 all-time and decreases with 0. I need to update my DataBase I know that, but I really don't understand how. I see 2 alternatives with Sqlexec and ContentValues, but I really don't know how to implement it. If someone can help me, I will really appreciate it. I put my adapter class and DB here.

public class cartItemRecyclerView extends RecyclerView.Adapter<cartItemRecyclerView.ViewHolder>{

ArrayList<items> itemsList;
Context context;

interface IImageButtonListener{
    void onImageButtonClick(View view,int pos,boolean isDecrease);
}

public cartItemRecyclerView(Context context, ArrayList<items> itemsList){
    this.context = context;
    this.itemsList = itemsList;
}

public cartItemRecyclerView(ArrayList<items> item) {
    this.itemsList = item;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View contactView = inflater.inflate(R.layout.list_cart_item_view,parent,false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(contactView);

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    // Get the data model based on position
    items itm = itemsList.get(position);

    // Set item views based on your view and data model

    holder.nameC.setText(itm.getlName());
    holder.iconC.setImageResource(itm.getlImageId());
    holder.priceC.setText(itm.getlPrice()+ "");
    holder.quantityC.setText(itm.getQuantity()+"");

    holder.setListener(new IImageButtonListener() {
        @Override
        public void onImageButtonClick(View view, int pos, boolean isDecrease) {
            if(isDecrease){
                int i = itemsList.get(pos).getQuantity();
                i++;
                // Update in database
                holder.quantityC.setText(i+"");

            }
            else {
                int i = itemsList.get(pos).getQuantity();
                i--;
                // Update in database
                holder.quantityC.setText(i+"");
            }

        }
    });

}

@Override
public int getItemCount() {
    return itemsList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    public TextView nameC, priceC, quantityC;
    public ImageView increaseC, decreaseC, iconC;
    IImageButtonListener listener;

    public void setListener(IImageButtonListener listener){
        this.listener = listener;
    }

    public ViewHolder(View itemView){
        super(itemView);

        nameC = itemView.findViewById(R.id.name_item_cart);
        priceC = itemView.findViewById(R.id.price_item_cart);
        quantityC = itemView.findViewById(R.id.textview_quantity_items);
        increaseC = itemView.findViewById(R.id.image_increase_quantity);
        decreaseC = itemView.findViewById(R.id.image_decrease_quantity);
        iconC = itemView.findViewById(R.id.icon_item_cart);

        // Event
        increaseC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onImageButtonClick(v, getAdapterPosition(),true);
            }
        });

        decreaseC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onImageButtonClick(v, getAdapterPosition(),false);
            }
        });
    }
}

And this is the DB SQLite code.

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "favorites.db";
public static final String TABLE_NAME_CART = "cart_table";

public static final String COL_1 = "IMAGE";
public static final String COL_2 = "NAME";
public static final String COL_3 = "PRICE";
public static final String COL_4 = "DETAILS";
public static final String COL_5 = "MODEL";
public static final String COL_6 = "IMAGEE";
public static final String COL_7 = "IMAGEEE";
public static final String COL_8 = "QUANTITY";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

private static DatabaseHelper sDatabaseHelper;

public static DatabaseHelper getInstance(Context context) {
    if (sDatabaseHelper == null) {
        sDatabaseHelper = new DatabaseHelper(context);
    }
    return sDatabaseHelper;
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE " + TABLE_NAME_CART + " (" + COL_1 + " INTEGER, " + COL_2 + " VARCHAR, " + COL_3 + " INTEGER, " + COL_4 + " VARCHAR, " + COL_5 + " VARCHAR, " + COL_6 + " INTEGER, " + COL_7 + " INTEGER, " + COL_8 + " INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CART);
    onCreate(db);
}

// Insert Data in cart table
public boolean insertDataCart(items items) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, items.getlImageId());
    contentValues.put(COL_2, items.getlName());
    contentValues.put(COL_3, items.getlPrice());
    contentValues.put(COL_4, items.getlDetails());
    contentValues.put(COL_5, items.getlModel());
    contentValues.put(COL_6, items.getlImageId1());
    contentValues.put(COL_7, items.getlImageId2());
    contentValues.put(COL_8, items.getQuantity());

    long result = db.insert(TABLE_NAME_CART, null, contentValues);

    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

// See Data Cart
public ArrayList<items> getAllDataCart() {
    ArrayList<items> favItem = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME_CART, null);

    while (res.moveToNext()) {
        int img = res.getInt(0);
        String name = res.getString(1);
        int price = res.getInt(2);
        String details = res.getString(3);
        String model = res.getString(4);
        int img1 = res.getInt(5);
        int img2 = res.getInt(6);
        int quantity = res.getInt(7);
        items newItems = new items(name, price, img, img1, img2, details, model,quantity);
        favItem.add(newItems);
    }
    return favItem;
}

Here I use the RecyclerView

 public class cart extends AppCompatActivity {

private DatabaseHelper favoriteDbHelper;
private ArrayList<items> item;
private cartItemRecyclerView cartItemRecyclerView;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cart);

    recyclerView = (RecyclerView) findViewById(R.id.cart_recycler);

    favoriteDbHelper = new DatabaseHelper(this);
    item = favoriteDbHelper.getAllDataCart();

    cartItemRecyclerView = new cartItemRecyclerView(item,favoriteDbHelper,this);
    recyclerView.setAdapter(cartItemRecyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

}

Body:
You can try this.

Add to DatabaseHelper

    public boolean updateDataCard(int id, int quantity) {

    ContentValues val = new ContentValues();

    val.put(COL_8, quantity);

    int result =  db.update(TABLE_NAME_CART, val, "IMAGE=" + id, null);
    if (result == -1) {
     return false;
    } else {
     return true;
    }
}

You must pass your database object. You can use with constructor method.

ArrayList<items> itemsList;
Context context;
YourDBObject db;

interface IImageButtonListener{
 void onImageButtonClick(View view,int pos,boolean isDecrease);
 }

 public cartItemRecyclerView(Context context, ArrayList<items>
  itemsList,YourDBObject db){
     this.context = context;
     this.itemsList = itemsList;
     this.db = db;
}

And Then you can call.

   if(isDecrease){
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i++;
            // Update in database
            if(i <= 2){
            db.updateDataCard(id,i)
            holder.quantityC.setText(i+"");
           }
        }
        else {
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i--;
            // Update in database
            if( i < 2 && i >= 0 ){
               db.updateDataCard(id,i)
               holder.quantityC.setText(i+"");
            }

}

I hope i can help you.


问:
Append/Prepend space on outer tag
I would like to append/prepend a space on the outer tags.

I tried the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ")
$elem.prepend(" ");

console.log($elem[0]);
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

As you can see only the inner tag has the spaces.

However, I would like to have it on the outer tag. Like the following:

```<code> <span data-function="addSynonym" data-options="[ test1, test2, test3]"><span style="background-color: yellow;">test4</span></span>

</code>```

Any suggestions how to do this?

I appreciate your replies!

答:
I would just reference the vanilla outerHTML manually.

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ");
$elem.prepend(" ");

console.log(" " + $elem[0].outerHTML + " ");
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Append/Prepend space on outer tag

Body:
I would like to append/prepend a space on the outer tags.

I tried the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ")
$elem.prepend(" ");

console.log($elem[0]);
console.log($elem[0].innerHTML);

As you can see only the inner tag has the spaces.

However, I would like to have it on the outer tag. Like the following:

 test4

Any suggestions how to do this?

I appreciate your replies!

Body:
I would just reference the vanilla outerHTML manually.

var $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('<span>', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append("&nbsp;");
$elem.prepend("&nbsp;");

console.log("&nbsp;" + $elem[0].outerHTML + "&nbsp;");
console.log($elem[0].innerHTML);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Cakephp 3 trouble modifying Collection
I'm making a collection and one of the tasks is to make it Match any campus_id that is not = to NULL and not equal to campus.campus_name of 'Online'

$onCampusesLocationsHc = $collection->match(['enrollment_type_id' => 1 ])->match(['location_id' => 1 ])->match(['campus_id' => !NULL]);

this works great so far but having trouble adding the "or not equal to campus.campus_name of 'Online'".

I've added

->match(['campus.campus_name' => 'Online']);

it will not work if the first condition is applied.

->match(['campus_id' => !NULL]);

but it will filter everything out but the Online category.
If this line is added instead of the !=NULL is present

I've tried to run the opposite but the result is empty.

->match(['campus.campus_name !=' => 'Online']);

It should return Six campuses.

Struggling to find something in the Collection Filters that will allow me to apply two filters to a column.

答:
Greg Schmidt lead me to the answer. I used the reject() filter

->reject(function ($notOnline, $key) { return $notOnline->campus->campus_name === 'Online'; })

by adding a reject function on the end I was able to reject anything that had a campus name of Online. The other six campuses now show up

Title: Cakephp 3 trouble modifying Collection


问:
Reason for Overflow (G++ vs Clang++)
When I'm compiling the following piece of C++ code using Clang++ and G++

```<code>void ScaleFactor(float32_t scale, int32_t &factor) {
    factor = floor(log2(abs(scale))+1)
    cout << factor << endl;
}
</code>```

where the value of scale equals 0.234375 and factor is passed by reference to an integer variable in another function, I'm getting the following different outputs for factor while debugging using GDB

```<code>(int32_t &) @0x7fffffffdaa0: -2147483648 (Clang++)
(int32_t &) @0x7fffffffda9c: -2 (G++)
</code>```

But, on replacing abs() with fabs() each output matches with the desired output

```<code>(int32_t &) @0x7fffffffdb90: -2 (Clang++)
(int32_t &) @0x7fffffffdddc: -2 (G++)
</code>```

What might be the reason for this discrepancy?

答:
Does this code produce the same results? It does not seem to, for me: https://godbolt.org/z/Wj9v6j

```<code>#include <iostream>
#include <cmath>

using namespace std;

using float32_t = float;

void ScaleFactor(float32_t scale, int32_t &factor) {
    factor = floor(log2(abs(/*(int)*/scale))+1);
    cout << factor << endl;
}

int main() {
    int32_t result;
    ScaleFactor(0.234375f, result);
    return 0;
}
</code>```

If it does not, are you sure that something else is not going wrong here? Maybe you are including the C versions of the math functions, where there is a difference between abs and fabs, when building with clang?

The weird result you get is exactly what I get if I cast the float to int when passing it to abs, exactly what you would expect if you were using the C version of abs.

Title: Reason for Overflow (G++ vs Clang++)

Body:
When I'm compiling the following piece of C++ code using Clang++ and G++

void ScaleFactor(float32_t scale, int32_t &factor) {
    factor = floor(log2(abs(scale))+1)
    cout << factor << endl;
}

where the value of scale equals 0.234375 and factor is passed by reference to an integer variable in another function, I'm getting the following different outputs for factor while debugging using GDB

(int32_t &) @0x7fffffffdaa0: -2147483648 (Clang++)
(int32_t &) @0x7fffffffda9c: -2 (G++)

But, on replacing abs() with fabs() each output matches with the desired output

(int32_t &) @0x7fffffffdb90: -2 (Clang++)
(int32_t &) @0x7fffffffdddc: -2 (G++)

What might be the reason for this discrepancy?

Body:
Does this code produce the same results? It does not seem to, for me: https://godbolt.org/z/Wj9v6j

#include <iostream>
#include <cmath>

using namespace std;

using float32_t = float;

void ScaleFactor(float32_t scale, int32_t &factor) {
    factor = floor(log2(abs(/*(int)*/scale))+1);
    cout << factor << endl;
}

int main() {
    int32_t result;
    ScaleFactor(0.234375f, result);
    return 0;
}

If it does not, are you sure that something else is not going wrong here? Maybe you are including the C versions of the math functions, where there is a difference between abs and fabs, when building with clang?

The weird result you get is exactly what I get if I cast the float to int when passing it to abs, exactly what you would expect if you were using the C version of abs.


问:
How to reference the default Outlook calendar using Excel VBA?
I am trying to create an event in Outlook using data from Excel.

```<code>Dim objOutlook As Object
Dim ObjAppt As Object
Dim objNamespace As Object
Dim objFolder As Object
Dim OpenMAPIFolder As Object
Dim objCalendar As Object

Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(9).Folders("Calendar")
Set ObjAppt = objFolder.Items.Add 'create task item
With ObjAppt
    .Body = Range("A1")
    .Start = Range("A17")
    .End = Range("B17")
    .AllDayEvent = True
    .ReminderSet = True
    .ReminderMinutesBeforeStart = 1440
    .Save
End With

Set ObjAppt = Nothing
Set objFolder = Nothing
Set objNamespace = Nothing
Set objOutlook = Nothing
</code>```

It says that the folder name is incorrect.

答:
To get to the default Calendar folder try

```<code>objNamespace.GetDefaultFolder(olFolderCalendar)
</code>```

NameSpace.GetDefaultFolder method (Outlook)

also see Reference Outlook folder from Excel

https://stackoverflow.com/a/41476442/4539709

Body:
I am trying to create an event in Outlook using data from Excel.

Dim objOutlook As Object
Dim ObjAppt As Object
Dim objNamespace As Object
Dim objFolder As Object
Dim OpenMAPIFolder As Object
Dim objCalendar As Object

Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(9).Folders("Calendar")
Set ObjAppt = objFolder.Items.Add 'create task item
With ObjAppt
    .Body = Range("A1")
    .Start = Range("A17")
    .End = Range("B17")
    .AllDayEvent = True
    .ReminderSet = True
    .ReminderMinutesBeforeStart = 1440
    .Save
End With

Set ObjAppt = Nothing
Set objFolder = Nothing
Set objNamespace = Nothing
Set objOutlook = Nothing

It says that the folder name is incorrect.

Body:
To get to the default Calendar folder try

objNamespace.GetDefaultFolder(olFolderCalendar)

NameSpace.GetDefaultFolder method (Outlook)

also see Reference Outlook folder from Excel

https://stackoverflow.com/a/41476442/4539709


问:
Missing values in ARFF (Weka)
How will classifiers (such as decision trees) in Weka interpret '?' (that stands for missing values in ARFF files) during learning stage?
Will Weka just replace it with some predefined value (e.g. '0' or 'false') or will it somehow affect the training process?</p>

答:
Apart from treating missing value as an attribute value on its own, in the case of the J48 classifier any split on an attribute with missing value will be done with weights proportional to frequencies of the observed non-missing values. This is documented in Witten and Frank's textbook, Data Mining Practical Machine Learning Tools and Techniques (2005, 2nd. ed., p. 63 and p. 191), who then reported that

eventually, the various parts of the instance will each reach a leaf node, and the decisions at these leaf nodes must be recombined using the weights that have percolated to the leaves.

More information about handling missing values in decision trees, like surrogate splits in CART (and contrary to C4.5 or its successor J48), can be found on the wiki section for Classification Trees; the use of imputation is also discussed in several articles, e.g.  Handling missing data in trees: surrogate splits or statistical imputation.

Title: Missing values in ARFF (Weka)


问:
SQL GROUP BY clause and getting floating point 2 precision on a DATESPAN calculation with AVG
I currently am trying to find the best way to get a percentage on a column that is a calculation of days between two dates. I then want to find the average.

```<code>SELECT
    [Filed1],
    [Field2],
    COUNT(items) AS [Total Items],
    CAST(AVG(
            (DATEDIFF(SECOND,
                    [DateStart],
                    [DateEnd])
            )/36000)
        )AS DECIMAL(10,2)) [Avg Days]
        FROM [MY DB]
</code>```

I cannot seem to get a accurate 3.5 days or 7.1 days, it only returns integers with two decimals as 5.00, 6.00 and so on. How can I handle a date span calculation, with decimal precision in the average?

答:
Likely, you are facing integer division: because both the division numerator and denominator are integers, the database forces the conversion of the result the division to an integer result.

Many databases implement that behavior - SQL Server is one of them, which I suspect that you are using (you also tagged your question MySQL, but this one doesn't do integer division - and your syntax with square brackets quoting also suggests that).

One way to solve this is to make one of the numbers decimal, like:

```<code>CAST(
    AVG(DATEDIFF(SECOND, [DateStart], [DateEnd])/36000.00)
    AS DECIMAL(10,2)
) [Avg Days]
</code>```

Body:
I currently am trying to find the best way to get a percentage on a column that is a calculation of days between two dates. I then want to find the average.

SELECT
    [Filed1],
    [Field2],
    COUNT(items) AS [Total Items],
    CAST(AVG(
            (DATEDIFF(SECOND,
                    [DateStart],
                    [DateEnd])
            )/36000)
        )AS DECIMAL(10,2)) [Avg Days]
        FROM [MY DB]

I cannot seem to get a accurate 3.5 days or 7.1 days, it only returns integers with two decimals as 5.00, 6.00 and so on. How can I handle a date span calculation, with decimal precision in the average?

Body:
Likely, you are facing integer division: because both the division numerator and denominator are integers, the database forces the conversion of the result the division to an integer result.

Many databases implement that behavior - SQL Server is one of them, which I suspect that you are using (you also tagged your question MySQL, but this one doesn't do integer division - and your syntax with square brackets quoting also suggests that).

One way to solve this is to make one of the numbers decimal, like:

CAST(
    AVG(DATEDIFF(SECOND, [DateStart], [DateEnd])/36000.00)
    AS DECIMAL(10,2)
) [Avg Days]