问:
How put a Confirmation in Hyperlink DataGridView
I want is to have a confirmation before deleting a records in my datagridview. Please check my codes.. Thanks.

here's my asp.net code:

```<code><ItemTemplate><asp:HyperLink ID="hlnk_Delete" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
    NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>
</code>```

Sqldatasource:

```<code><asp:SqlDataSource ID="sds_PublishedBookListings" runat="server" ConnectionString="<%$ ConnectionStrings:learningisfunConnectionString %>"

SelectCommand="SELECT dbo.lif_bookshascategory.lbhc_lc_id,dbo.lif_books.lb_sku, dbo.lif_bookshascategory.lbhc_lb_sku, dbo.lif_category.lc_category, dbo.lif_books.lb_title,
                      dbo.lif_bookshascategory.lbhc_level
FROM         dbo.lif_bookshascategory INNER JOIN
                      dbo.lif_category ON dbo.lif_bookshascategory.lbhc_lc_id = dbo.lif_category.lc_id INNER JOIN
                      dbo.lif_books ON dbo.lif_bookshascategory.lbhc_lb_sku = dbo.lif_books.lb_sku
WHERE     (dbo.lif_books.lb_status = 'publish') and lbhc_level = 1
"

DeleteCommand="DELETE FROM lif_books FROM lif_books INNER JOIN lif_bookshascategory ON lif_books.lb_sku = lif_bookshascategory.lbhc_lb_sku WHERE (lif_books.lb_sku = @lbhc_lb_sku) OR (lif_bookshascategory.lbhc_lb_sku = @lbhc_lb_sku)">
<DeleteParameters>
<asp:Parameter Name="lb_sku" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
</code>```

答: Try JavaScript Confirm DialogBox.</p>

Body:
I want is to have a confirmation before deleting a records in my datagridview. Please check my codes.. Thanks.

here's my asp.net code:

<ItemTemplate><asp:HyperLink ID="hlnk_Delete" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
    NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>

Sqldatasource:

<asp:SqlDataSource ID="sds_PublishedBookListings" runat="server" ConnectionString="<%$ ConnectionStrings:learningisfunConnectionString %>"

SelectCommand="SELECT dbo.lif_bookshascategory.lbhc_lc_id,dbo.lif_books.lb_sku, dbo.lif_bookshascategory.lbhc_lb_sku, dbo.lif_category.lc_category, dbo.lif_books.lb_title,
                      dbo.lif_bookshascategory.lbhc_level
FROM         dbo.lif_bookshascategory INNER JOIN
                      dbo.lif_category ON dbo.lif_bookshascategory.lbhc_lc_id = dbo.lif_category.lc_id INNER JOIN
                      dbo.lif_books ON dbo.lif_bookshascategory.lbhc_lb_sku = dbo.lif_books.lb_sku
WHERE     (dbo.lif_books.lb_status = 'publish') and lbhc_level = 1
"

DeleteCommand="DELETE FROM lif_books FROM lif_books INNER JOIN lif_bookshascategory ON lif_books.lb_sku = lif_bookshascategory.lbhc_lb_sku WHERE (lif_books.lb_sku = @lbhc_lb_sku) OR (lif_bookshascategory.lbhc_lb_sku = @lbhc_lb_sku)">
<DeleteParameters>
<asp:Parameter Name="lb_sku" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>

Body: Try JavaScript Confirm DialogBox.


来源: stackexchange

问:
getting npm issue while running the project
I'm getting the following issue all the time while going to run my project using npm start. Even after downgrading my node version to 8.4.0 (npm version 5.3.0) still getting the same issue. I know there are same questions present in stackoverflow as well as stackexchange with so many solutions given. I tried with all, like after removing the node_modules to run npm cache clean --force and then again npm install, the solutions are not working. I have shared the log below:

```<code>> subhojits-components@0.0.1 start
/home/subhojit/Desktop/myproject
> node server/index

Unspecified environment, booting dev server
Booting dev server....
module.js:491
throw err;
^

Error: Cannot find module 'internal/fs'
at Function.Module._resolveFilename (module.js:489:15)
at Function.Module._load (module.js:439:25)
at Module.require (module.js:517:17)
at require (internal/module.js:11:18)
at evalmachine.<anonymous>:40:20
at Object.<anonymous> (/home/subhojit/Desktop/myproject/node_modules/express-handlebars/node_modules/graceful-fs/fs.js:11:1)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! subhojits-components@0.0.1 start: `node server/index`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the subhojits-components@0.0.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

Note: I'm using graceful-fs version 4.1.15.

Any help would be appreciated.

答:
Try this

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following issue all the time while going to run my project using npm start. Even after downgrading my node version to 8.4.0 (npm version 5.3.0) still getting the same issue. I know there are same questions present in stackoverflow as well as stackexchange with so many solutions given. I tried with all, like after removing the node_modules to run npm cache clean --force and then again npm install, the solutions are not working. I have shared the log below:

> subhojits-components@0.0.1 start
/home/subhojit/Desktop/myproject
> node server/index

Unspecified environment, booting dev server
Booting dev server....
module.js:491
throw err;
^

Error: Cannot find module 'internal/fs'
at Function.Module._resolveFilename (module.js:489:15)
at Function.Module._load (module.js:439:25)
at Module.require (module.js:517:17)
at require (internal/module.js:11:18)
at evalmachine.<anonymous>:40:20
at Object.<anonymous> (/home/subhojit/Desktop/myproject/node_modules/express-handlebars/node_modules/graceful-fs/fs.js:11:1)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! subhojits-components@0.0.1 start: `node server/index`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the subhojits-components@0.0.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Note: I'm using graceful-fs version 4.1.15.

Any help would be appreciated.


问:
How do I create a TfvcLabel using TfvcHttpClient in Azure DevOps Services?
We are a team trying to upgrade our windows application to use Azure DevOps Services' new REST based .NET Client Libraries instead of Client OM that uses SOAP.

The part of the application that we are upgrading does the following:

Checks out all AssemblyInfoVersion.cs files.

Updates the version on those files.

Checks in all the files.

Create a Label with information about that the version was updated.

We managed to do the first three steps with the new REST based .NET Client Libraries using the CreateChangesetAsync method.

But we can not find any information about how to create a Label so we have not been able to do the last step. Is this really not supported?

答:
Currenlty you can't create a new label with the new Azure DevOps Rest API, you can only get labels.

As workaround, you can use tf.exe with the command label to label the files.

In your code add something like this (using System.Diagnostic):

```<code>string tfExePath = "path/to/exe";
string tfArgs = "label test /version:45 $test/src"
Process.Start(tfExePath, tfArgs)
</code>```

Body:
Currenlty you can't create a new label with the new Azure DevOps Rest API, you can only get labels.

As workaround, you can use tf.exe with the command label to label the files.

In your code add something like this (using System.Diagnostic):

string tfExePath = "path/to/exe";
string tfArgs = "label test /version:45 $test/src"
Process.Start(tfExePath, tfArgs)


问:
Combination using goroutine
I'm trying to get a code to work that pretty much involves channels in goroutine (in a yield-like behavior in C#)

The code involves getting an iterable matrix from a slice like so:

```<code>elements := []float64{1, 2, 3, 4}

expected := [][]float64{
    {1},
    {2},
    {3},
    {4},
    {1, 2},
    {1, 3},
    {2, 3},
    {1, 4},
    {2, 4},
    {3, 4},
    {1, 2, 3},
    {1, 2, 4},
    {1, 3, 4},
    {2, 3, 4},
    {1, 2, 3, 4},
}
</code>```

I've tried applying Knuth's by doing:

```<code>func Combinadic(values []float64) <-chan []float64 {
    ch := make(chan []float64)
    go func() {
        for i := 0; i < len(values); i++ {

            for value := range CombinadicK(values, i+1) {
                ch <- value
            }

        }
        close(ch)
    }()

    return ch

}

func CombinadicK(values []float64, k int) <-chan []float64 {
    chnl := make(chan []float64)
    go func() {
        n := len(values)

        t := k

        c := make([]int, t+3)
        current := make([]float64, t)

        x := 0
        j := 0

        for j = 1; j <= t; j++ {
            c[j] = j - 1
        }

        c[t+1] = n
        c[t+2] = 0

        j = t

        for {
            for i := 0; i < len(current); i++ {
                current[i] = values[c[i+1]]
            }

            chnl <- current

            if j > 0 {
                x = j
            } else {
                if c[1]+1 < c[2] {
                    c[1]++
                    continue
                } else {
                    j = 2
                }
            }

            for {
                c[j-1] = j - 2
                x = c[j] + 1
                if x == c[j+1] {
                    j++
                } else {
                    break
                }
            }

            c[j] = x
            j--

            if j >= t {
                break
            }
        }

        close(chnl)
    }()

    return chnl
}
</code>```

It appears to give out random number per row, but the structure of the expected (the count of items per row) appears to be ok.

The code in Go Playground

答:
You have a data race. Your results are undefined.

```<code>$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00c00009c010 by main goroutine:
  reflect.typedmemmove()
      /home/peter/go/src/runtime/mbarrier.go:177 +0x0
  reflect.packEface()
      /home/peter/go/src/reflect/value.go:119 +0x103
  reflect.valueInterface()
      /home/peter/go/src/reflect/value.go:1027 +0x16f
  fmt.(*pp).printValue()
      /home/peter/go/src/reflect/value.go:997 +0x38f7
  fmt.(*pp).printValue()
      /home/peter/go/src/fmt/print.go:868 +0xec7
  fmt.(*pp).printArg()
      /home/peter/go/src/fmt/print.go:715 +0x2ee
  fmt.(*pp).doPrintln()
      /home/peter/go/src/fmt/print.go:1172 +0xad
  fmt.Fprintln()
      /home/peter/go/src/fmt/print.go:263 +0x65
  main.main()
      /home/peter/go/src/fmt/print.go:273 +0x14b

Previous write at 0x00c00009c010 by goroutine 8:
  main.CombinadicK.func1()
      /home/peter/racer.go:48 +0x1e6

Goroutine 8 (running) created at:
  main.CombinadicK()
      /home/peter/racer.go:26 +0x96
  main.Combinadic.func1()
      /home/peter/racer.go:12 +0xda
==================
[3]
[3]
[4]
[4]
[2 3]
[2 4]
[1 4]
[3 4]
[3 4]
[3 4]
[1 3 4]
[1 3 4]
[1 3 4]
[2 3 4]
[1 2 3 4]
Found 1 data race(s)
exit status 66
$
</code>```

racer.go:

```<code>package main

import (
    "fmt"
)

func Combinadic(values []float64) <-chan []float64 {
    ch := make(chan []float64)
    go func() {
        for i := 0; i < len(values); i++ {

            for value := range CombinadicK(values, i+1) {
                ch <- value
            }

        }
        close(ch)
    }()

    return ch

}

func CombinadicK(values []float64, k int) <-chan []float64 {
    chnl := make(chan []float64)
    go func() {
        n := len(values)

        t := k

        c := make([]int, t+3)
        current := make([]float64, t)

        x := 0
        j := 0

        for j = 1; j <= t; j++ {
            c[j] = j - 1
        }

        c[t+1] = n
        c[t+2] = 0

        j = t

        for {
            for i := 0; i < len(current); i++ {
                current[i] = values[c[i+1]]
            }

            chnl <- current

            if j > 0 {
                x = j
            } else {
                if c[1]+1 < c[2] {
                    c[1]++
                    continue
                } else {
                    j = 2
                }
            }

            for {
                c[j-1] = j - 2
                x = c[j] + 1
                if x == c[j+1] {
                    j++
                } else {
                    break
                }
            }

            c[j] = x
            j--

            if j >= t {
                break
            }
        }

        close(chnl)
    }()

    return chnl
}

func main() {
    elements := []float64{1, 2, 3, 4}
    for v := range Combinadic(elements) {
        fmt.Println(v)
    }
}
</code>```

Playground: https://play.golang.org/p/hhQgVdqe6l1

Go: Data Race Detector

Title: Combination using goroutine

Body:
I'm trying to get a code to work that pretty much involves channels in goroutine (in a yield-like behavior in C#)

The code involves getting an iterable matrix from a slice like so:

elements := []float64{1, 2, 3, 4}

expected := [][]float64{
    {1},
    {2},
    {3},
    {4},
    {1, 2},
    {1, 3},
    {2, 3},
    {1, 4},
    {2, 4},
    {3, 4},
    {1, 2, 3},
    {1, 2, 4},
    {1, 3, 4},
    {2, 3, 4},
    {1, 2, 3, 4},
}

I've tried applying Knuth's by doing:

func Combinadic(values []float64) <-chan []float64 {
    ch := make(chan []float64)
    go func() {
        for i := 0; i < len(values); i++ {

            for value := range CombinadicK(values, i+1) {
                ch <- value
            }

        }
        close(ch)
    }()

    return ch

}

func CombinadicK(values []float64, k int) <-chan []float64 {
    chnl := make(chan []float64)
    go func() {
        n := len(values)

        t := k

        c := make([]int, t+3)
        current := make([]float64, t)

        x := 0
        j := 0

        for j = 1; j <= t; j++ {
            c[j] = j - 1
        }

        c[t+1] = n
        c[t+2] = 0

        j = t

        for {
            for i := 0; i < len(current); i++ {
                current[i] = values[c[i+1]]
            }

            chnl <- current

            if j > 0 {
                x = j
            } else {
                if c[1]+1 < c[2] {
                    c[1]++
                    continue
                } else {
                    j = 2
                }
            }

            for {
                c[j-1] = j - 2
                x = c[j] + 1
                if x == c[j+1] {
                    j++
                } else {
                    break
                }
            }

            c[j] = x
            j--

            if j >= t {
                break
            }
        }

        close(chnl)
    }()

    return chnl
}

It appears to give out random number per row, but the structure of the expected (the count of items per row) appears to be ok.

The code in Go Playground

Body:
You have a data race. Your results are undefined.

$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00c00009c010 by main goroutine:
  reflect.typedmemmove()
      /home/peter/go/src/runtime/mbarrier.go:177 +0x0
  reflect.packEface()
      /home/peter/go/src/reflect/value.go:119 +0x103
  reflect.valueInterface()
      /home/peter/go/src/reflect/value.go:1027 +0x16f
  fmt.(*pp).printValue()
      /home/peter/go/src/reflect/value.go:997 +0x38f7
  fmt.(*pp).printValue()
      /home/peter/go/src/fmt/print.go:868 +0xec7
  fmt.(*pp).printArg()
      /home/peter/go/src/fmt/print.go:715 +0x2ee
  fmt.(*pp).doPrintln()
      /home/peter/go/src/fmt/print.go:1172 +0xad
  fmt.Fprintln()
      /home/peter/go/src/fmt/print.go:263 +0x65
  main.main()
      /home/peter/go/src/fmt/print.go:273 +0x14b

Previous write at 0x00c00009c010 by goroutine 8:
  main.CombinadicK.func1()
      /home/peter/racer.go:48 +0x1e6

Goroutine 8 (running) created at:
  main.CombinadicK()
      /home/peter/racer.go:26 +0x96
  main.Combinadic.func1()
      /home/peter/racer.go:12 +0xda
==================
[3]
[3]
[4]
[4]
[2 3]
[2 4]
[1 4]
[3 4]
[3 4]
[3 4]
[1 3 4]
[1 3 4]
[1 3 4]
[2 3 4]
[1 2 3 4]
Found 1 data race(s)
exit status 66
$

racer.go:

package main

import (
    "fmt"
)

func Combinadic(values []float64) <-chan []float64 {
    ch := make(chan []float64)
    go func() {
        for i := 0; i < len(values); i++ {

            for value := range CombinadicK(values, i+1) {
                ch <- value
            }

        }
        close(ch)
    }()

    return ch

}

func CombinadicK(values []float64, k int) <-chan []float64 {
    chnl := make(chan []float64)
    go func() {
        n := len(values)

        t := k

        c := make([]int, t+3)
        current := make([]float64, t)

        x := 0
        j := 0

        for j = 1; j <= t; j++ {
            c[j] = j - 1
        }

        c[t+1] = n
        c[t+2] = 0

        j = t

        for {
            for i := 0; i < len(current); i++ {
                current[i] = values[c[i+1]]
            }

            chnl <- current

            if j > 0 {
                x = j
            } else {
                if c[1]+1 < c[2] {
                    c[1]++
                    continue
                } else {
                    j = 2
                }
            }

            for {
                c[j-1] = j - 2
                x = c[j] + 1
                if x == c[j+1] {
                    j++
                } else {
                    break
                }
            }

            c[j] = x
            j--

            if j >= t {
                break
            }
        }

        close(chnl)
    }()

    return chnl
}

func main() {
    elements := []float64{1, 2, 3, 4}
    for v := range Combinadic(elements) {
        fmt.Println(v)
    }
}

Playground: https://play.golang.org/p/hhQgVdqe6l1

Go: Data Race Detector


问:
Where is the fault?
complier error
    Error   C2440    '=': cannot convert from 'const std::basic_string,std::allocator>' to 'const char *'

int main(void)
{

    /*
    complier error
    Error   C2440    '=': cannot convert from 'const std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'
    primer  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\VC\Tools\MSVC\14.22.27706\include\xutility  1745
    */
    list<string> names = {"A","B"};
    vector<const char*> vnames;
    vnames.assign(names.cbegin(), names.cend());//OK
    /*for (auto it = names.cbegin(); it != names.cend(); ++it)
    {
        cout << *it << endl;
    }*/
    for (auto it = vnames.cbegin(); it != vnames.cend(); ++it)
    {
        cout << *it << endl;
    }
    cout << "hello world" << endl;
    return 0;
}
```

答:
This:

```<code>vnames.assign(names.cbegin(), names.cend());//OK
</code>```

Your comment says "OK", but it's not OK. You can't assign std::string objects to const char* ones. If you want to get the C string pointers of each std::string and put it into vnames, then you have to:

```<code>for (const auto& i : names) {
    vnames.push_back(i.c_str());
}
</code>```

After that, you need to be very careful not to modify the names vector in any way that would cause a reallocation. Doing so will invalidate the pointers stored in vnames.

Title: Where is the fault?

Body:
This:

vnames.assign(names.cbegin(), names.cend());//OK

Your comment says "OK", but it's not OK. You can't assign std::string objects to const char* ones. If you want to get the C string pointers of each std::string and put it into vnames, then you have to:

for (const auto& i : names) {
    vnames.push_back(i.c_str());
}

After that, you need to be very careful not to modify the names vector in any way that would cause a reallocation. Doing so will invalidate the pointers stored in vnames.


问:
Visual Studio removing extension doesn't work
I am writing an extension for Visual Studio 2015. I had a number of test extensions that I'd try directly, other than in the experimental instance. In fact, a couple of these versions were good enough for my team members to try, which is why I gave them the vsix file each time and had them install it with that.

Problem is that I can't get these to uninstall. I'm not doing anything strange.  In fact, most of it is just for a couple of t4 templates. When I run an experimental instance, I keep seeing an old version show up rather than the latest.

I've reset the experimental instance numerous times using :

```<code>C:\Program Files (x86)\Microsoft Visual Studio\14.0\VSSDK\VisualStudioIntegration\Tools\Bin>CreateExpInstance /Reset /VSInstance=14.0 /RootSuffix=Exp
</code>```

But the old version is still in there. If I try to uninstall, it's still in there showing as disabled. If I close the experimental instance and reopen it, it's back. Even after resetting the experimental instance.

So I tried going into the folder with the extensions and deleting all of the ones that have my tests. When I reopened visual studio and clicked on Extensions, it just gave me an error, so I undeleted the folders.

I tried using

```<code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>VSIXInstaller  /u:
</code>```

with the key for my test. It says it's uninstalling but it doesn't remove the one that's giving me the problem. It does remove the latest one though.

I started checking the registry, and I'm finding a section with "pending deletions" with all the tests I've created. But nothing I do seems to get it to actually process them.

Normally I run visual studio as administrator. I enabled the flag on the shortcut, because some of the projects I work on require it and I don't want to have to remember to use 'run as'. But it doesn't seem to matter. If I run just without it, those 'pending deletions' don't seem to process either.

I'm going to poke around some more but maybe someone else has a solution for this?

答:
I've found an old article from 2009 on Daniel Cazzulino's Blog with few simple steps and they seemed to work for me on VS 2017:

Resetting Visual Studio Experimental Instance to its super-clean initial state.

In case the link will ever go dead, I'm pasting an essence:

In order to get a super-clean environment, here’s what you need to do:

Close any running instance of VS Experimental.

Delete the entire folder %LocalAppData%\Microsoft\VisualStudio\10.0Exp

Run regedit.exe

Delete the registry key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0Exp

Delete the registry key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0Exp_Config

Run the command “Reset the Microsoft Visual Studio 2010 Experimental instance” from your start menu.

Few extra notes from me:

I didn't have 10.0Exp, I had 14.0Exp and 15.0Exp - I removed both. The probably referred to VS 2015 and VS 2017

I wasn't aware that there is such a MS tool "“Reset the Microsoft Visual Studio 2010 Experimental instance” in windows Start menu, but apparently there is :)

ContentLicense: CC BY-SA 3.0

Body:
I am writing an extension for Visual Studio 2015. I had a number of test extensions that I'd try directly, other than in the experimental instance. In fact, a couple of these versions were good enough for my team members to try, which is why I gave them the vsix file each time and had them install it with that.

Problem is that I can't get these to uninstall. I'm not doing anything strange.  In fact, most of it is just for a couple of t4 templates. When I run an experimental instance, I keep seeing an old version show up rather than the latest.

I've reset the experimental instance numerous times using :

C:\Program Files (x86)\Microsoft Visual Studio\14.0\VSSDK\VisualStudioIntegration\Tools\Bin>CreateExpInstance /Reset /VSInstance=14.0 /RootSuffix=Exp

But the old version is still in there. If I try to uninstall, it's still in there showing as disabled. If I close the experimental instance and reopen it, it's back. Even after resetting the experimental instance.

So I tried going into the folder with the extensions and deleting all of the ones that have my tests. When I reopened visual studio and clicked on Extensions, it just gave me an error, so I undeleted the folders.

I tried using

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>VSIXInstaller  /u:

with the key for my test. It says it's uninstalling but it doesn't remove the one that's giving me the problem. It does remove the latest one though.

I started checking the registry, and I'm finding a section with "pending deletions" with all the tests I've created. But nothing I do seems to get it to actually process them.

Normally I run visual studio as administrator. I enabled the flag on the shortcut, because some of the projects I work on require it and I don't want to have to remember to use 'run as'. But it doesn't seem to matter. If I run just without it, those 'pending deletions' don't seem to process either.

I'm going to poke around some more but maybe someone else has a solution for this?


问:
Removing Conda environment
I want to remove a certain environment created with conda. How can I achieve that? Let's say I have an active testenv environment. I tried, by following documentation, with:

```<code>$ conda env remove

CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove again
</code>```

I then deactivate it:

```<code>$ source deactivate
</code>```

I try running again the command to remove it and I still get the same error. What is going wrong here?

答:
Official documentation way worked for me:

```<code>conda remove --name myenv --all
</code>```

Or just conda env remove --name myenv.

To verify that the environment was removed, in your terminal window or an Anaconda Prompt, run:

```<code>conda info --envs
</code>```

The environments list that displays should not show the removed environment.

You anaconda3 enviroments folder might list an empty folder of deleted environment in your anaconda3 installation folder, like:

```<code>/opt/anaconda3/envs
</code>```

Title: Removing Conda environment

Body:
I want to remove a certain environment created with conda. How can I achieve that? Let's say I have an active testenv environment. I tried, by following documentation, with:

$ conda env remove

CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove again

I then deactivate it:

$ source deactivate

I try running again the command to remove it and I still get the same error. What is going wrong here?

Body:
Official documentation way worked for me:

conda remove --name myenv --all

Or just conda env remove --name myenv.

To verify that the environment was removed, in your terminal window or an Anaconda Prompt, run:

conda info --envs

The environments list that displays should not show the removed environment.

You anaconda3 enviroments folder might list an empty folder of deleted environment in your anaconda3 installation folder, like:

/opt/anaconda3/envs


问:
Is it possible not to load the bootstrapping mechanism at every call?
This is not a PHP question, but my expertise is with PHP frameworks.

A lot of frameworks have a bootstrapping (loading of classes and files) mechanism. (Drupal, Zend Framework to name a few)

Everytime that you make a request, the complete bootloading process needs to be repeated. And it can be optimized using APC by automatically caching some intermediate code

The general question is:

For any language, is there any way to not load the complete bootstrapping process? Is there any way of "caching" the state (or starting at) at the end of the bootstraping process to not load everything again? (maybe the answer is in some other language/framework/pattern)

It looks to me as extremely inefficient.

答:
The short answer is: in PHP there's no good way to skip the bootstrapping. (Technically you could run a PHP service 24/7 that ran forked children to handle requests, but that's not going to make your life any better.)

A good framework shouldn't do much in bootstrapping. In my personal one that I use, it simply registers an autoload function for classes, loads the config settings from MemCache, and connects to a database.

At that point, it parses the request and sends it to the proper controller / action. While creating the new router object every time is a "waste," the actual process of handling the request needs to be done regardless if the bootstrapping process is magically "cached" between requests.

So I would measure the time it takes between starting the page and getting to the action method to see if it's even a problem. If the framework is doing expensive things related to configuration and class loading, you should be able to minimize that via storing the end results in memcache.

Note that you should always be using an opcode cache (e.g. APC) and a persistent SAPI (e.g., php-fpm) in production. Otherwise, there is a lot of overhead with starting up and shutting down.


问:
When Google Chrome spawns a new process?
When I see the task manager of Google's Chrome I could see few (each) tabs run under individual process and group of tabs run under a single process. Out of curiosity, I searched to know why it runs as multiple process instead of multiple threads. And one thing which brought to my attention is when it runs as a single process and spawns multiple threads there could be few limitations/drawbacks like,

1) Limitation on number of threads that could be created

2) When a single tab becomes unresponsive the entire application would be come useless and we have to quit chrome and restart it due to some misbehaving site.

A few mentioned that Chrome uses single process per domain, but here it doesn't seem to be true.

I'm still not clear on,

1) When Chrome decides to spawn a new process?

2) What are the other advantage of running individual tabs under separate process?

3) How cookies are shared between tabs when each of them run under different process? Is this happening via interprocess communication? If yes, will it be too costly? And will it impact the other tab's (ie' the web page) performance?

答:
After asking this question, I came to see this article (Multi Process Architecture of Chromium) and it answered my question (1).

When Chrome decides to spawn a new process?

Once Google Chrome has created its browser process, it will generally create one renderer process for each instance of a web site you visit.  This approach aims to keep pages from different web sites isolated from each other.

You can think of this as using a different process for each tab in the browser, but allowing two tabs to share a process if they are related to each other and are showing the same site.  For example, if one tab opens another tab using JavaScript, or if you open a link to the same site in a new tab, the tabs will share a renderer process.  This lets the pages in these tabs communicate via JavaScript and share cached objects.  Conversely, if you type the URL of a different site into the location bar of a tab, they will swap in a new renderer process for the tab.

They place a limit on the number of renderer processes that they create (as 20 in most cases).  Once they hit this limit, they'll start re-using the existing renderer processes for new tabs.

What are the advantage of running tabs under different process?

Google Chrome takes advantage of these properties and puts web apps and plug-ins in separate processes from the browser itself.  This means that a rendering engine crash in one web app won't affect the browser or other web apps.  It means the OS can run web apps in parallel to increase their responsiveness, and it means the browser itself won't lock up if a particular web app or plug-in stops responding.  It also means they can run the rendering engine processes in a restrictive sandbox that helps limit the damage if an exploit does occur.

Interestingly, using multiple processes means Google Chrome can have its own Task Manager (shown below), which you can get to by right clicking on the browser's title bar.  This Task Manager lets you track resource usage for each web app and plug-in, rather than for the entire browser.  It also lets you kill any web apps or plug-ins that have stopped responding, without having to restart the entire browser.


问:
How to list instances that have tag1:<anyvalue> AND tag2:<anyvalue> AND tag3:<anyvalue>
I need to identify in my infrastructure which hosts have tag1 and tag2 and tag3.
I'm new to datadog but it seems that when filtering I have to specify a value for a specific tag.
I also need to identify the inverse, list hosts that have tag1 but are missing tag2 OR tag3.

I have setup a dashboard for each of the tags, I seem to be limited by up 2 tags.
e.g filter by -> env:dev

    group by -> tag1 , tag2

I would expect to be able to see what hosts have tag1 AND tag2 AND tag3

And the inverse -> what hosts do not have all 3 tags.

答:
```<code>aws ec2 describe-instances --filters "Name=tag:Department,Values=RnD" --filters "Name=tag:Name,Values=Server1"
</code>```


问:
Ensuring template argument type matches that of its variadic constructor
I would like to have a class like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};
</code>```

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

```<code>Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory
</code>```

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };
</code>```

And when trying to use it:

```<code> int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };
</code>```

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

答:
enable_if and is_same won't store anything anywhere, they are only compile-time constructs and do not yield to any code in the binary executable.

Regardless of the syntax, what your code is essentially doing is trying to take the address of a constructor argument (which is a temporary). This will be a dangling pointer as soon as the constructor exits.

Either Foo owns the memory area and must allocate in constructor and delete in destructor (if any doubt: use std::vector!), or it aliases some external memory, and must receive a pointer to that memory.

Now regarding syntax:

std::is_same is a template that provides a value boolean constant and is to be used like so: std::is_same<T1, T2>::value. Alternatively you can use std::is_same_v<T1, T2>.

std::enable_if provides a type type member, only if the constant expression (1st template parameter) is true. Use it like std::enable_if<expr, T>::type. If expr is true, type is a typedef to T. Otherwise it is not defined and yields a substitution failure. Alternatively you can use std::enable_if_t<expr, T>

You can have a look here for a similar approach of yours.

But you can also simplify all this by using a member vector. In that case, the vector constructor ensures that all arguments have compatible types. Here is a complete example:

```<code>#include <string>
#include <vector>
#include <iostream>
#include <type_traits>

using namespace std;

template<typename T>
struct Foo {
    vector<T> data_;

    template<typename ...Ts>
    explicit Foo(Ts... ts) : data_{ ts... } {}

    void print() {
        for (const auto &v : data_) {
            cout << v << " ";
        }
        cout << endl;
    }
};

int main() {

    Foo<int> ints { 1, 2, 3, 4, 5 };
    Foo<string> strings { "a", "b", "c", "d", "e"};
    // Foo<string> incorrect { "a", 2, "c", 4, "e"};

    ints.print();
    strings.print();
    // incorrect.print();

    return 0;
}
</code>```

Body:
I would like to have a class like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };

And when trying to use it:

 int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

Body:
enable_if and is_same won't store anything anywhere, they are only compile-time constructs and do not yield to any code in the binary executable.

Regardless of the syntax, what your code is essentially doing is trying to take the address of a constructor argument (which is a temporary). This will be a dangling pointer as soon as the constructor exits.

Either Foo owns the memory area and must allocate in constructor and delete in destructor (if any doubt: use std::vector!), or it aliases some external memory, and must receive a pointer to that memory.

Now regarding syntax:

std::is_same is a template that provides a value boolean constant and is to be used like so: std::is_same<T1, T2>::value. Alternatively you can use std::is_same_v<T1, T2>.

std::enable_if provides a type type member, only if the constant expression (1st template parameter) is true. Use it like std::enable_if<expr, T>::type. If expr is true, type is a typedef to T. Otherwise it is not defined and yields a substitution failure. Alternatively you can use std::enable_if_t<expr, T>

You can have a look here for a similar approach of yours.

But you can also simplify all this by using a member vector. In that case, the vector constructor ensures that all arguments have compatible types. Here is a complete example:

#include <string>
#include <vector>
#include <iostream>
#include <type_traits>

using namespace std;

template<typename T>
struct Foo {
    vector<T> data_;

    template<typename ...Ts>
    explicit Foo(Ts... ts) : data_{ ts... } {}

    void print() {
        for (const auto &v : data_) {
            cout << v << " ";
        }
        cout << endl;
    }
};

int main() {

    Foo<int> ints { 1, 2, 3, 4, 5 };
    Foo<string> strings { "a", "b", "c", "d", "e"};
    // Foo<string> incorrect { "a", 2, "c", 4, "e"};

    ints.print();
    strings.print();
    // incorrect.print();

    return 0;
}


问:
Thread.sleep inside infinite while loop in lambda doesn't require 'catch (InterruptedException)' - why not?
My question is about InterruptedException, which is thrown from the Thread.sleep method. While working with ExecutorService I noticed some weird behaviour that I don't understand; here is what I mean:

```<code>ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(true)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });
</code>```

With this code, the compiler doesn't give me any error or message that InterruptedException from Thread.sleep should be caught. But when I am trying to change the loop condition and replace "true" with some variable like this:

```<code>ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(tasksObserving)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });
</code>```

The compiler constantly complains that InterruptedException has to be handled. Can someone explain to me why this happens, and why if the condition is set to true the compiler ignores the InterruptedException?

答:
Briefly

ExecutorService has both submit(Callable) and submit(Runnable) methods.

In the first case (with the while (true)), both submit(Callable) and submit(Runnable) match, so the compiler has to choose between them

submit(Callable) is chosen over submit(Runnable) because Callable is more specific than Runnable

Callable has throws Exception in call(), so it is not necessary to catch an exception inside it

In the second case (with the while (tasksObserving)) only submit(Runnable) match, so the compiler chooses it

Runnable has no throws declaration on its run() method, so it is a compilation error to not catch the exception inside the run() method.

The full story

Java Language Specification describes how the method is chosen during program compilation in $15.2.2 :

Identify Potentially Applicable Methods ($15.12.2.1) which is done in 3 phases for strict, loose and variable arity invocation

Choose the Most Specific Method ($15.12.2.5) from the methods found on the first step.

Let's analyze the situation with 2 submit() methods in two code snippets provided by the OP:

```<code>ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(true)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });
</code>```

and

```<code>ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(tasksObserving)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });
</code>```

(where tasksObserving is not a final variable).

Identify Potentially Applicable Methods

First, the compiler has to identify the potentially applicable methods: $15.12.2.1

If the member is a fixed arity method with arity n, the arity of the method invocation is equal to n, and for all i (1 ≤ i ≤ n), the i'th argument of the method invocation is potentially compatible, as defined below, with the type of the i'th parameter of the method.

and a bit further in the same section

An expression is potentially compatible with a target type according to the following rules:

A lambda expression (§15.27) is potentially compatible with a functional interface type (§9.8) if all of the following are true:

The arity of the target type's function type is the same as the arity of the lambda expression.

If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).

If the target type's function type has a (non-void) return type, then the lambda body is either an expression or a value-compatible block (§15.27.2).

Let's note that in both cases, the lambda is a block lambda.

Let's also note that Runnable has void return type, so to be potentially compatible with Runnable, a block lambda must be void-compatible block. At the same time, Callable has a non-void return type, so to be potentially comtatible with Callable, a block lambda must be value-compatible block.

$15.27.2 defines what a void-compatible-block and value-compatible-block are.

A block lambda body is void-compatible if every return statement in the block has the form return;.

A block lambda body is value-compatible if it cannot complete normally (§14.21) and every return statement in the block has the form return Expression;.

Let's look at $14.21, paragraph about while loop:

A while statement can complete normally iff at least one of the following is true:

The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

There is a reachable break statement that exits the while statement.

In borh cases, lambdas are actually block lambdas.

In the first case, as it can be seen, there is a while loop with a constant expression with value true (without break statements), so it cannot complete normallly (by $14.21); also it has no return statements, hence the first lambda is value-compatible.

At the same time, there are no return statements at all, so it is also void-compatible. So, in the end, in the first case, the lambda is both void- and value-compatible.

In the second case, the while loop can complete normally from the point of view of the compiler (because the loop expression is not a constant expression anymore), so the lambda in its entirety can complete normally, so it is not a value-compatible block. But it is still a void-compatible block because it contains no return statements.

The intermediate result is that in the first case the lambda is both a void-compatible block and a value-compatible block; in the second case it is only a void-compatible block.

Recalling what we noted earlier, this means that in the first case, the lambda will be potentially compatible both with Callable and Runnable; in the second case, the lambda will only be potentially compatible with Runnable.

Choose the Most Specific Method

For the first case, the compiler has to choose between the two methods because both are potentially applicable. It does so using the procedure called 'Choose the Most Specific Method' and described in $15.12.2.5. Here is an excerpt:

A functional interface type S is more specific than a functional interface type T for an expression e if T is not a subtype of S and one of the following is true (where U1 ... Uk and R1 are the parameter types and return type of the function type of the capture of S, and V1 ... Vk and R2 are the parameter types and return type of the function type of T):

If e is an explicitly typed lambda expression (§15.27.1), then one of the following is true:

R2 is void.

First of all,

A lambda expression with zero parameters is explicitly typed.

Also, neither of Runnable and Callable is a subclass of one another, and Runnable return type is void, so we have a match: Callable is more specific than Runnable. This means that between submit(Callable) and submit(Runnable) in the first case the method with Callable will be chosen.

As for the second case, there we only have one potentially applicable method, submit(Runnable), so it is chosen.

So why does the change surface?

So, in the end, we can see that in these cases different methods are chosen by the compiler. In the first case, the lambda is inferred to be a Callable which has throws Exception on its call() method, so that sleep() call compiles. In the second case, it's Runnable which run() does not declare any throwable exceptions, so the compiler complains about an exception not being caught.

Body:
My question is about InterruptedException, which is thrown from the Thread.sleep method. While working with ExecutorService I noticed some weird behaviour that I don't understand; here is what I mean:

ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(true)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });

With this code, the compiler doesn't give me any error or message that InterruptedException from Thread.sleep should be caught. But when I am trying to change the loop condition and replace "true" with some variable like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(tasksObserving)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });

The compiler constantly complains that InterruptedException has to be handled. Can someone explain to me why this happens, and why if the condition is set to true the compiler ignores the InterruptedException?

Body:
Briefly

ExecutorService has both submit(Callable) and submit(Runnable) methods.

In the first case (with the while (true)), both submit(Callable) and submit(Runnable) match, so the compiler has to choose between them

submit(Callable) is chosen over submit(Runnable) because Callable is more specific than Runnable

Callable has throws Exception in call(), so it is not necessary to catch an exception inside it

In the second case (with the while (tasksObserving)) only submit(Runnable) match, so the compiler chooses it

Runnable has no throws declaration on its run() method, so it is a compilation error to not catch the exception inside the run() method.

The full story

Java Language Specification describes how the method is chosen during program compilation in $15.2.2 :

Identify Potentially Applicable Methods ($15.12.2.1) which is done in 3 phases for strict, loose and variable arity invocation

Choose the Most Specific Method ($15.12.2.5) from the methods found on the first step.

Let's analyze the situation with 2 submit() methods in two code snippets provided by the OP:

ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(true)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });

and

ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(tasksObserving)
        {
            //DO SOMETHING
            Thread.sleep(5000);
        }
    });

(where tasksObserving is not a final variable).

Identify Potentially Applicable Methods

First, the compiler has to identify the potentially applicable methods: $15.12.2.1

If the member is a fixed arity method with arity n, the arity of the method invocation is equal to n, and for all i (1 ≤ i ≤ n), the i'th argument of the method invocation is potentially compatible, as defined below, with the type of the i'th parameter of the method.

and a bit further in the same section

An expression is potentially compatible with a target type according to the following rules:

A lambda expression (§15.27) is potentially compatible with a functional interface type (§9.8) if all of the following are true:

The arity of the target type's function type is the same as the arity of the lambda expression.

If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).

If the target type's function type has a (non-void) return type, then the lambda body is either an expression or a value-compatible block (§15.27.2).

Let's note that in both cases, the lambda is a block lambda.

Let's also note that Runnable has void return type, so to be potentially compatible with Runnable, a block lambda must be void-compatible block. At the same time, Callable has a non-void return type, so to be potentially comtatible with Callable, a block lambda must be value-compatible block.

$15.27.2 defines what a void-compatible-block and value-compatible-block are.

A block lambda body is void-compatible if every return statement in the block has the form return;.

A block lambda body is value-compatible if it cannot complete normally (§14.21) and every return statement in the block has the form return Expression;.

Let's look at $14.21, paragraph about while loop:

A while statement can complete normally iff at least one of the following is true:

The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

There is a reachable break statement that exits the while statement.

In borh cases, lambdas are actually block lambdas.

In the first case, as it can be seen, there is a while loop with a constant expression with value true (without break statements), so it cannot complete normallly (by $14.21); also it has no return statements, hence the first lambda is value-compatible.

At the same time, there are no return statements at all, so it is also void-compatible. So, in the end, in the first case, the lambda is both void- and value-compatible.

In the second case, the while loop can complete normally from the point of view of the compiler (because the loop expression is not a constant expression anymore), so the lambda in its entirety can complete normally, so it is not a value-compatible block. But it is still a void-compatible block because it contains no return statements.

The intermediate result is that in the first case the lambda is both a void-compatible block and a value-compatible block; in the second case it is only a void-compatible block.

Recalling what we noted earlier, this means that in the first case, the lambda will be potentially compatible both with Callable and Runnable; in the second case, the lambda will only be potentially compatible with Runnable.

Choose the Most Specific Method

For the first case, the compiler has to choose between the two methods because both are potentially applicable. It does so using the procedure called 'Choose the Most Specific Method' and described in $15.12.2.5. Here is an excerpt:

A functional interface type S is more specific than a functional interface type T for an expression e if T is not a subtype of S and one of the following is true (where U1 ... Uk and R1 are the parameter types and return type of the function type of the capture of S, and V1 ... Vk and R2 are the parameter types and return type of the function type of T):

If e is an explicitly typed lambda expression (§15.27.1), then one of the following is true:

R2 is void.

First of all,

A lambda expression with zero parameters is explicitly typed.

Also, neither of Runnable and Callable is a subclass of one another, and Runnable return type is void, so we have a match: Callable is more specific than Runnable. This means that between submit(Callable) and submit(Runnable) in the first case the method with Callable will be chosen.

As for the second case, there we only have one potentially applicable method, submit(Runnable), so it is chosen.

So why does the change surface?

So, in the end, we can see that in these cases different methods are chosen by the compiler. In the first case, the lambda is inferred to be a Callable which has throws Exception on its call() method, so that sleep() call compiles. In the second case, it's Runnable which run() does not declare any throwable exceptions, so the compiler complains about an exception not being caught.


问:
How parse String contains negative number in Rust?
I am taking input number from user and then check if the number is positive, negative or zero. Positive number and zero checking performed but having problem in Negative number checking.

```<code>use std::io::Write;

fn main(){
    print!("Enter Number: ");
    let mut number = String::new();
    std::io::stdout().flush();
    std::io::stdin().read_line(&mut number);
    let num: u32 = number.trim().parse().unwrap();
}
</code>```

when input is negative number, program becomes panic didn't parsing negative number.

答:
When you replace u32 by i32 in the last line your program is able to handle negative numbers.

u32 means unsigned integer with 32bit width so parse() panics when it encounters a negative number. i32 is a signed integer so it works.

Body:
I am taking input number from user and then check if the number is positive, negative or zero. Positive number and zero checking performed but having problem in Negative number checking.

use std::io::Write;

fn main(){
    print!("Enter Number: ");
    let mut number = String::new();
    std::io::stdout().flush();
    std::io::stdin().read_line(&mut number);
    let num: u32 = number.trim().parse().unwrap();
}

when input is negative number, program becomes panic didn't parsing negative number.


问:
Android: Check if EditText is Empty when inputType is set on Number/Phone
I have an EditText in android for users to input their AGE. It is set an inputType=phone.
I would like to know if there is a way to check if this EditText is null.

I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.

These, I've checked already and do not work:

```<code>(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.
</code>```

Thank you for your help.

答:
```<code>EditText textAge;
textAge = (EditText)findViewByID(R.id.age);
if (TextUtils.isEmpty(textAge))
{
Toast.makeText(this, "Age Edit text is Empty", Toast.LENGTH_SHORT).show();
//or type here the code you want
}
</code>```

Body:
I have an EditText in android for users to input their AGE. It is set an inputType=phone.
I would like to know if there is a way to check if this EditText is null.

I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.

These, I've checked already and do not work:

(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.

Thank you for your help.


问:
Load XML file to server
I have a simple php application that uses, among others, an hourly updated external XML file.

I need to use only one of the file's fields, thus, I used simplexml_load_file().

The problem is that this function only works with files currently saved on the server and not external ones.

How can I download the XML file periodically on the server (a download on every refresh would work too)? Thanks.

答:
```<code>file_put_contents('updated.xml',
                  file_get_contents('http://someulr.com/updated.xml')
                 );

simplexml_load_file('updated.xml');
</code>```

Title: Load XML file to server


问:
Message "flutter run: No connected devices"
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

```<code>flutter run
No connected devices.
</code>```

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.
```

Is there a solution to this problem?

答:
I found that my antivirus software (Avast) had quarantined the adb.exe file. I went to Avast -> protection -> virus chest. Removed the adb.exe file from the list.

Then added the Android_home variable + added it to the PATH variable. I restarted my machine and Android Studio picked up the device/emulator.

Body:
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

flutter run
No connected devices.

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.

Is there a solution to this problem?


问:
CNN: Forwarding batch of images - Stuck when using multiple kernels
I'm putting it first, I'm not using any frameworks and I started learning Convolutional layers like last week. I understand the basics of forward propagation, haven't even touched back but that's out of scope. Here's my confusion:

Suppose I have 4 images, with 3 channels of size 4x4: 4x3x4x4
And I have kernels with 3 channels of size 3x3: K*3x3x3

I'm trying to compute the convolutions on all 4 images but I always get lost in the dimensionality. Here's what I've tried:

```<code>import numpy as np

w = np.array(
    [
        # Img: 1, 4x4 image with 3 channels
        [
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ],
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ]
        ],
        # Img: 2, 4x4 image with 3 channels
        [
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ],
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ]
        ],
        # Img: 3, 4x4 image with 3 channels
        [
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ],
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ]
        ],
        # Img: 4, 4x4 image with 3 channels
        [
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ],
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ],
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ]
        ]
    ]
)

f = np.array(
    [
        # Filter: 1, 3x3 filter for 3 channels -> All 1s
        [
            [
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1]
            ],
            [
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1]
            ],
            [
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1]
            ]
        ],
        # Filter: 2, 3x3 filter for 3 channels -> All 2s
        [
            [
                [2, 2, 2],
                [2, 2, 2],
                [2, 2, 2]
            ],
            [
                [2, 2, 2],
                [2, 2, 2],
                [2, 2, 2]
            ],
            [
                [2, 2, 2],
                [2, 2, 2],
                [2, 2, 2]
            ]
        ]
    ]
)

hori_dimension = (w.shape[3] - f.shape[3]) // 1 + 1
vert_dimension = (w.shape[2] - f.shape[2]) // 1 + 1
r = np.zeros(shape=(w.shape[0], f.shape[0], vert_dimension, hori_dimension))
for i in range(vert_dimension):
    for j in range(hori_dimension):
        r[:, :, i, j] += np.sum(w[:, :, i:i+3, j:j+3] * f, axis=(1, 2, 3))
print(r)
</code>```

This doesn't work and I have problems with this part, when I have K number of kernels for N number of images.

If I have a single kernel however, then I can define my operation as (This works flawlessly):

```<code>hori_dimension = (w.shape[3] - f.shape[3]) // 1 + 1
vert_dimension = (w.shape[2] - f.shape[2]) // 1 + 1
r = np.zeros(shape=(w.shape[0], vert_dimension, hori_dimension))
for i in range(vert_dimension):
    for j in range(hori_dimension):
        r[:, i, j] += np.sum(w[:, :, i:i+3, j:j+3] * f, axis=(1, 2, 3))
print(r)
</code>```

which results in 2x2 feature for each image:

```<code>[[[27. 27.]
  [27. 27.]]

 [[27. 27.]
  [27. 27.]]

 [[27. 27.]
  [27. 27.]]

 [[27. 27.]
  [27. 27.]]]
</code>```

This seems right, I have 1 kernel so I'll have 1 feature map for each image, yielding 4 feature maps of 2 dimensions. In the above I would expect, another dimension. Having 4 feature maps for each kernel, but I can't figure this one out.

@Update:

This seems like doing the job:

```<code>p = 0
s = 1
number_of_input_images, number_of_image_channels, height_of_image, width_of_image = w.shape
number_of_kernels, number_of_kernel_channels, height_of_kernel, width_of_kernel = f.shape
assert(number_of_image_channels == number_of_kernel_channels)

width_of_features = (width_of_image - width_of_kernel + 2*p) // s + 1
height_of_features = (height_of_image - height_of_kernel + 2*p) // s + 1
feature_maps = np.zeros(shape=(number_of_input_images, number_of_kernels, height_of_features, width_of_features))

for k in range(f.shape[0]):
    for i in range(height_of_features):
        for j in range(width_of_features):
            feature_maps[:, k, i, j] += np.sum(w[:, :, i:i+3, j:j+3] * f[k], axis=(1, 2, 3))

print(feature_maps)
</code>```

It results in the following feature maps:

```<code>[
    # pic1
    [
        # kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        # kernel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
    # pic2
    [
        #kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        #kernel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
    #pic3
    [
        #kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        #kernel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
    #pic4
    [
        #kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        #kerbel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
]
</code>```

Is there a better way of doing it?  Is this even correct? To me it seems fine. Having a picture and multiple kernels, the result of convolution will be the feature map from each kernel put "after" another right? So having K amount of kernels where the feature maps has NN dimensions the output of the convolutional layer becomes KN*N. In that way, the above seems right, I guess? As I said I truly have messed up with these N dimensions...

@Update:

I ended up with the following code for valid(forward)/full(backprop) convolutions:

```<code>def convolve(sources: np.ndarray,
             kernels: np.ndarray,
             mode: str = 'valid',
             padding: typing.Tuple[int] = (0, 0),
             stride: int = 1):
    number_of_input_images, number_of_image_channels, height_of_image, width_of_image = sources.shape
    number_of_kernels, number_of_kernel_channels, height_of_kernel, width_of_kernel = kernels.shape
    assert(number_of_image_channels == number_of_kernel_channels)

    if mode == 'full':
        padding = (height_of_kernel, width_of_kernel)

    if padding:
        sources = np.pad(sources,
                         ((0, 0), (0, 0), (padding[0], padding[0]), (padding[1], padding[1])),
                         mode='constant', constant_values=0)

    kernels = np.rot90(kernels, k=2, axes=(2, 3))

    width_of_features = (width_of_image - width_of_kernel + 2*padding[1]) // stride + 1
    height_of_features = (height_of_image - height_of_kernel + 2*padding[0]) // stride + 1
    feature_maps = np.zeros(shape=(number_of_input_images, number_of_kernels, height_of_features, width_of_features))

    for k in range(f.shape[0]):
        for i in range(height_of_features):
            for j in range(width_of_features):
                feature_maps[:, k, i, j] = np.einsum('ncij,cij', sources[:, :, i:i+3, j:j+3],  kernels[k])

    return feature_maps
</code>```

Any feedback would be appreciated. I read that the kernels must be rotated when doing the convolution so I rotate twice by 90 degrees, also has the ability to use custom padding, and in order to have a full convolution I pad with the size of the kernel -1 so that all surrounding elements are zero and I get no index errors.

答:
Ended up with the following piece of code to handle the the batch convolution:</p>

```<code>def convolve(input_images, kernels, padding=0, stride=1):
    number_of_images, image_height, image_width, image_channels = input_images.shape
    number_of_kernels, kernel_height, kernel_width, kernel_depth = kernels.shape
    assert (image_channels == kernel_depth)

    input_images = np.pad(input_images, ((0, 0), (padding, padding), (padding, padding), (0, 0)),
                          mode='constant', constant_values=(0,))
    kernels = np.rot90(kernel, k=2, axes=(1, 2))

    fm_height = (image_height - kernel_height + 2*padding) // stride + 1
    fm_width = (image_width - kernel_width + 2*padding) // stride + 1
    feature_maps = np.zeros(shape=(number_of_images, fm_height, fm_width, number_of_kernels))
    for n in range(number_of_images):
        for i in range(fm_height):
            for j in range(fm_width):
                x = input_images[n, i * stride:i * stride + kernel_height, j * stride:j * stride + kernel_width, :]
                feature_maps[n, i, j, :] = np.einsum('ijk,mijk', x, kernels)
    return feature_maps
</code>```

Body:
I'm putting it first, I'm not using any frameworks and I started learning Convolutional layers like last week. I understand the basics of forward propagation, haven't even touched back but that's out of scope. Here's my confusion:

Suppose I have 4 images, with 3 channels of size 4x4: 4x3x4x4
And I have kernels with 3 channels of size 3x3: K*3x3x3

I'm trying to compute the convolutions on all 4 images but I always get lost in the dimensionality. Here's what I've tried:

import numpy as np

w = np.array(
    [
        # Img: 1, 4x4 image with 3 channels
        [
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ],
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ]
        ],
        # Img: 2, 4x4 image with 3 channels
        [
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ],
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ]
        ],
        # Img: 3, 4x4 image with 3 channels
        [
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ],
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ]
        ],
        # Img: 4, 4x4 image with 3 channels
        [
            [
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2],
                [2, 2, 2, 2]
            ],
            [
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
                [1, 1, 1, 1]
            ],
            [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ]
        ]
    ]
)

f = np.array(
    [
        # Filter: 1, 3x3 filter for 3 channels -> All 1s
        [
            [
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1]
            ],
            [
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1]
            ],
            [
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1]
            ]
        ],
        # Filter: 2, 3x3 filter for 3 channels -> All 2s
        [
            [
                [2, 2, 2],
                [2, 2, 2],
                [2, 2, 2]
            ],
            [
                [2, 2, 2],
                [2, 2, 2],
                [2, 2, 2]
            ],
            [
                [2, 2, 2],
                [2, 2, 2],
                [2, 2, 2]
            ]
        ]
    ]
)

hori_dimension = (w.shape[3] - f.shape[3]) // 1 + 1
vert_dimension = (w.shape[2] - f.shape[2]) // 1 + 1
r = np.zeros(shape=(w.shape[0], f.shape[0], vert_dimension, hori_dimension))
for i in range(vert_dimension):
    for j in range(hori_dimension):
        r[:, :, i, j] += np.sum(w[:, :, i:i+3, j:j+3] * f, axis=(1, 2, 3))
print(r)

This doesn't work and I have problems with this part, when I have K number of kernels for N number of images.

If I have a single kernel however, then I can define my operation as (This works flawlessly):

hori_dimension = (w.shape[3] - f.shape[3]) // 1 + 1
vert_dimension = (w.shape[2] - f.shape[2]) // 1 + 1
r = np.zeros(shape=(w.shape[0], vert_dimension, hori_dimension))
for i in range(vert_dimension):
    for j in range(hori_dimension):
        r[:, i, j] += np.sum(w[:, :, i:i+3, j:j+3] * f, axis=(1, 2, 3))
print(r)

which results in 2x2 feature for each image:

[[[27. 27.]
  [27. 27.]]

 [[27. 27.]
  [27. 27.]]

 [[27. 27.]
  [27. 27.]]

 [[27. 27.]
  [27. 27.]]]

This seems right, I have 1 kernel so I'll have 1 feature map for each image, yielding 4 feature maps of 2 dimensions. In the above I would expect, another dimension. Having 4 feature maps for each kernel, but I can't figure this one out.

@Update:

This seems like doing the job:

p = 0
s = 1
number_of_input_images, number_of_image_channels, height_of_image, width_of_image = w.shape
number_of_kernels, number_of_kernel_channels, height_of_kernel, width_of_kernel = f.shape
assert(number_of_image_channels == number_of_kernel_channels)

width_of_features = (width_of_image - width_of_kernel + 2*p) // s + 1
height_of_features = (height_of_image - height_of_kernel + 2*p) // s + 1
feature_maps = np.zeros(shape=(number_of_input_images, number_of_kernels, height_of_features, width_of_features))

for k in range(f.shape[0]):
    for i in range(height_of_features):
        for j in range(width_of_features):
            feature_maps[:, k, i, j] += np.sum(w[:, :, i:i+3, j:j+3] * f[k], axis=(1, 2, 3))

print(feature_maps)

It results in the following feature maps:

[
    # pic1
    [
        # kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        # kernel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
    # pic2
    [
        #kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        #kernel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
    #pic3
    [
        #kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        #kernel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
    #pic4
    [
        #kernel1
        [
            [27. 27.]
            [27. 27.]
        ]
        #kerbel2
        [
            [54. 54.]
            [54. 54.]
        ]
    ]
]

Is there a better way of doing it?  Is this even correct? To me it seems fine. Having a picture and multiple kernels, the result of convolution will be the feature map from each kernel put "after" another right? So having K amount of kernels where the feature maps has NN dimensions the output of the convolutional layer becomes KN*N. In that way, the above seems right, I guess? As I said I truly have messed up with these N dimensions...

@Update:

I ended up with the following code for valid(forward)/full(backprop) convolutions:

def convolve(sources: np.ndarray,
             kernels: np.ndarray,
             mode: str = 'valid',
             padding: typing.Tuple[int] = (0, 0),
             stride: int = 1):
    number_of_input_images, number_of_image_channels, height_of_image, width_of_image = sources.shape
    number_of_kernels, number_of_kernel_channels, height_of_kernel, width_of_kernel = kernels.shape
    assert(number_of_image_channels == number_of_kernel_channels)

    if mode == 'full':
        padding = (height_of_kernel, width_of_kernel)

    if padding:
        sources = np.pad(sources,
                         ((0, 0), (0, 0), (padding[0], padding[0]), (padding[1], padding[1])),
                         mode='constant', constant_values=0)

    kernels = np.rot90(kernels, k=2, axes=(2, 3))

    width_of_features = (width_of_image - width_of_kernel + 2*padding[1]) // stride + 1
    height_of_features = (height_of_image - height_of_kernel + 2*padding[0]) // stride + 1
    feature_maps = np.zeros(shape=(number_of_input_images, number_of_kernels, height_of_features, width_of_features))

    for k in range(f.shape[0]):
        for i in range(height_of_features):
            for j in range(width_of_features):
                feature_maps[:, k, i, j] = np.einsum('ncij,cij', sources[:, :, i:i+3, j:j+3],  kernels[k])

    return feature_maps

Any feedback would be appreciated. I read that the kernels must be rotated when doing the convolution so I rotate twice by 90 degrees, also has the ability to use custom padding, and in order to have a full convolution I pad with the size of the kernel -1 so that all surrounding elements are zero and I get no index errors.

Body:
Ended up with the following piece of code to handle the the batch convolution:

def convolve(input_images, kernels, padding=0, stride=1):
    number_of_images, image_height, image_width, image_channels = input_images.shape
    number_of_kernels, kernel_height, kernel_width, kernel_depth = kernels.shape
    assert (image_channels == kernel_depth)

    input_images = np.pad(input_images, ((0, 0), (padding, padding), (padding, padding), (0, 0)),
                          mode='constant', constant_values=(0,))
    kernels = np.rot90(kernel, k=2, axes=(1, 2))

    fm_height = (image_height - kernel_height + 2*padding) // stride + 1
    fm_width = (image_width - kernel_width + 2*padding) // stride + 1
    feature_maps = np.zeros(shape=(number_of_images, fm_height, fm_width, number_of_kernels))
    for n in range(number_of_images):
        for i in range(fm_height):
            for j in range(fm_width):
                x = input_images[n, i * stride:i * stride + kernel_height, j * stride:j * stride + kernel_width, :]
                feature_maps[n, i, j, :] = np.einsum('ijk,mijk', x, kernels)
    return feature_maps


问:
Angular dom not updating on changes
Getting issues with the view not recognizing value changes on a component
I've tried using ChangeDetectorRef and still not getting any results. tried a bunch of thing and iv'e spent way to much time on something that i think should just work. I have a feeling its something to do with the way the gapi is handeling the onsucess function but I've also tried binding it down, wrapping it in other functions, nothing seems to work.

The onsuccess runs almost immediately but alas even if i log out and log back in i get the same results.

Am I missing something here?

header.component.html

<mat-toolbar color="">
    Hub

      LogOut

      <app-google-signin></app-google-signin>

</mat-toolbar>

```

header.component.ts

```import {AfterViewInit, ChangeDetectorRef, Component, OnDestroy, OnInit} from '@angular/core';
import {AuthService} from '../auth/auth.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit, OnDestroy {
  private userIsAuthenticated = false;
  private loggingIn = false;
  private authStatusListenerSub: Subscription;
  private loggingInSub: Subscription;

  constructor(private authService: AuthService, private ref: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.userIsAuthenticated = this.authService.getIsAuthenticated();
    this.loggingInSub = this.authService.getLoggingInListener().subscribe(loggingIn => {
      this.loggingIn = loggingIn
      console.log(`Logging In: ${loggingIn}`)
      this.ref.markForCheck()
    })

    this.authStatusListenerSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
      this.userIsAuthenticated = isAuthenticated
      console.log(`Authenticated: ${isAuthenticated}`)
    });

  }

  ngOnDestroy() {
    this.authStatusListenerSub.unsubscribe();
  }
}

```

auth.service.ts

```import {EventEmitter, Injectable, Output} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Subject} from 'rxjs';

declare const gapi: any;

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public CLIENT_ID = '[clientId]';
  private isAuthenticated = false;
  private loggingIn = false;

  @Output() authStatus = new EventEmitter<boolean>()

  private authStatusListener = new Subject<boolean>();
  private loggingInListener = new Subject<boolean>();

  constructor(private http: HttpClient) {
  }

  onGoogleSignIn(googleUser) {
    this.loggingIn = true;
    this.loggingInListener.next(true)
    const googleToken = googleUser.getAuthResponse().id_token;
    this.http.post<{ message: string, access: boolean }>(
      '[login url]',
      {loginToken: googleToken},
      {withCredentials: true})
      .subscribe(
        res => {
          console.log(res.message);
          this.loggingIn = false;
          this.loggingInListener.next(false)
          this.isAuthenticated = true;
          this.authStatusListener.next(true);
        },
        (err) => {
          this.loggingIn = false;
          this.loggingInListener.next(false)
          this.logout();
        });
  }

  getIsAuthenticated() {
    return this.isAuthenticated;
  }

  getAuthStatusListener() {
    return this.authStatusListener.asObservable();
  }

  getLoggingInListener() {
    return this.loggingInListener.asObservable()
  }
}
```

google-signin.component.ts

```import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core';
import {AuthService} from '../auth.service';

declare const gapi: any;

@Component({
  selector: 'app-google-signin',
  templateUrl: './google-signin.component.html',
  styleUrls: ['./google-signin.component.scss']
})
export class GoogleSigninComponent implements OnInit, AfterViewInit {
  public auth2: any;

  constructor(
    private element: ElementRef,
    private authService: AuthService,
  ) {
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.googleInit();
  }

  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: this.authService.CLIENT_ID,
        cookie_policy: 'single_host_origin',
      });

      const element = gapi.signin2.render('app-google-signin', {
        scope: 'profile email',
        longtitle: true,
        theme: 'dark',
        onsuccess: this.authService.onGoogleSignIn.bind(this.authService),
        onfailure: err => console.log(err)
      });
    });
  }

}
```

答:
try to trigger change detection manually and use onPush change detection strategy</p>

```<code> @Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush // add this
})
export class HeaderComponent implements OnInit, OnDestroy {
  private userIsAuthenticated = false;
  private loggingIn = false;
  private authStatusListenerSub: Subscription;
  private loggingInSub: Subscription;

  constructor(private authService: AuthService, private cdr: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.userIsAuthenticated = this.authService.getIsAuthenticated();
    this.loggingInSub = this.authService.getLoggingInListener().subscribe(loggingIn => {
      this.loggingIn = loggingIn
      console.log(`Logging In: ${loggingIn}`)
      this.cdr.detectChanges(); // *trigger change here*
    })

    this.authStatusListenerSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
      this.userIsAuthenticated = isAuthenticated
      console.log(`Authenticated: ${isAuthenticated}`)
    });

  }

  ngOnDestroy() {
    this.authStatusListenerSub.unsubscribe();
  }
}
</code>```

Title: Angular dom not updating on changes

Body:
Getting issues with the view not recognizing value changes on a component
I've tried using ChangeDetectorRef and still not getting any results. tried a bunch of thing and iv'e spent way to much time on something that i think should just work. I have a feeling its something to do with the way the gapi is handeling the onsucess function but I've also tried binding it down, wrapping it in other functions, nothing seems to work.

The onsuccess runs almost immediately but alas even if i log out and log back in i get the same results.

Am I missing something here?

header.component.html

<mat-toolbar color="">
    Hub

      LogOut

      <app-google-signin></app-google-signin>

</mat-toolbar>

header.component.ts

import {AfterViewInit, ChangeDetectorRef, Component, OnDestroy, OnInit} from '@angular/core';
import {AuthService} from '../auth/auth.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit, OnDestroy {
  private userIsAuthenticated = false;
  private loggingIn = false;
  private authStatusListenerSub: Subscription;
  private loggingInSub: Subscription;

  constructor(private authService: AuthService, private ref: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.userIsAuthenticated = this.authService.getIsAuthenticated();
    this.loggingInSub = this.authService.getLoggingInListener().subscribe(loggingIn => {
      this.loggingIn = loggingIn
      console.log(`Logging In: ${loggingIn}`)
      this.ref.markForCheck()
    })

    this.authStatusListenerSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
      this.userIsAuthenticated = isAuthenticated
      console.log(`Authenticated: ${isAuthenticated}`)
    });

  }

  ngOnDestroy() {
    this.authStatusListenerSub.unsubscribe();
  }
}

auth.service.ts

import {EventEmitter, Injectable, Output} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Subject} from 'rxjs';

declare const gapi: any;

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public CLIENT_ID = '[clientId]';
  private isAuthenticated = false;
  private loggingIn = false;

  @Output() authStatus = new EventEmitter<boolean>()

  private authStatusListener = new Subject<boolean>();
  private loggingInListener = new Subject<boolean>();

  constructor(private http: HttpClient) {
  }

  onGoogleSignIn(googleUser) {
    this.loggingIn = true;
    this.loggingInListener.next(true)
    const googleToken = googleUser.getAuthResponse().id_token;
    this.http.post<{ message: string, access: boolean }>(
      '[login url]',
      {loginToken: googleToken},
      {withCredentials: true})
      .subscribe(
        res => {
          console.log(res.message);
          this.loggingIn = false;
          this.loggingInListener.next(false)
          this.isAuthenticated = true;
          this.authStatusListener.next(true);
        },
        (err) => {
          this.loggingIn = false;
          this.loggingInListener.next(false)
          this.logout();
        });
  }

  getIsAuthenticated() {
    return this.isAuthenticated;
  }

  getAuthStatusListener() {
    return this.authStatusListener.asObservable();
  }

  getLoggingInListener() {
    return this.loggingInListener.asObservable()
  }
}

google-signin.component.ts

import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core';
import {AuthService} from '../auth.service';

declare const gapi: any;

@Component({
  selector: 'app-google-signin',
  templateUrl: './google-signin.component.html',
  styleUrls: ['./google-signin.component.scss']
})
export class GoogleSigninComponent implements OnInit, AfterViewInit {
  public auth2: any;

  constructor(
    private element: ElementRef,
    private authService: AuthService,
  ) {
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.googleInit();
  }

  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: this.authService.CLIENT_ID,
        cookie_policy: 'single_host_origin',
      });

      const element = gapi.signin2.render('app-google-signin', {
        scope: 'profile email',
        longtitle: true,
        theme: 'dark',
        onsuccess: this.authService.onGoogleSignIn.bind(this.authService),
        onfailure: err => console.log(err)
      });
    });
  }

}

Body:
try to trigger change detection manually and use onPush change detection strategy

 @Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush // add this
})
export class HeaderComponent implements OnInit, OnDestroy {
  private userIsAuthenticated = false;
  private loggingIn = false;
  private authStatusListenerSub: Subscription;
  private loggingInSub: Subscription;

  constructor(private authService: AuthService, private cdr: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.userIsAuthenticated = this.authService.getIsAuthenticated();
    this.loggingInSub = this.authService.getLoggingInListener().subscribe(loggingIn => {
      this.loggingIn = loggingIn
      console.log(`Logging In: ${loggingIn}`)
      this.cdr.detectChanges(); // *trigger change here*
    })

    this.authStatusListenerSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
      this.userIsAuthenticated = isAuthenticated
      console.log(`Authenticated: ${isAuthenticated}`)
    });

  }

  ngOnDestroy() {
    this.authStatusListenerSub.unsubscribe();
  }
}


问:
Filling object fields value at runtime falls under which design pattern
just having a question in mind so thought lets get the views from expert. it might be a silly question.

Actually i am using Reflection Mechanism to fill the some of the fields value of a class at run time. lets say i have a class A with 5 fields. i'll set the value of 2 fields at compile time but the remaining three fields value i'll set at run time.

So my question is that does it fall under some Design pattern?

Regards,

Mahendra Athneria

答: I think that the answer depends on the semantic of your class and object stored. It makes me think to strategy design pattern ( strategy_pattern) where the context can hold a particular strategy object. Maybe this isn't your case.</p>


问:
How to simulate ```WHERE``` from SQL or ```grep``` in Python to iterate and change data with certain attributes?
I'm looking for a quick and simple tool to simulate WHERE from SQL. In a collection (list, set, dictionary, etc) of objects (each of which should be a list or class instance), I'd like to pick out just those with some certain properties/attributes and process them.

Example 1:

```<code>stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result
</code>```

In example 1, myfunc simulates return items in stuff WHERE len(item)==3 which looks for and returns objects with length 3 in the dictionary stuff.

Example 2:

```<code>class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result
</code>```

In example 2, func simulates return items in test_list WHERE (item.a % 2) == 1 which returns objects where object.a is odd.

In both examples, a collection of objects is scanned for certain attributes that meet certain conditions and return those objects to be processed.

答:
You could check in your loop if item is int, like</p>

```<code>isinstance(item, int)
</code>```

Body:
I'm looking for a quick and simple tool to simulate WHERE from SQL. In a collection (list, set, dictionary, etc) of objects (each of which should be a list or class instance), I'd like to pick out just those with some certain properties/attributes and process them.

Example 1:

stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result

In example 1, myfunc simulates return items in stuff WHERE len(item)==3 which looks for and returns objects with length 3 in the dictionary stuff.

Example 2:

class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result

In example 2, func simulates return items in test_list WHERE (item.a % 2) == 1 which returns objects where object.a is odd.

In both examples, a collection of objects is scanned for certain attributes that meet certain conditions and return those objects to be processed.

Body:
You could check in your loop if item is int, like

isinstance(item, int)