问:
python from 2D array to 3D coordinates array
I have a mXn numpy array called a:
I would like to write a function which returns an array with size (3, mxn) which contains for each couple (x,y) in the first array the correspondant value.

```<code>import numpy as np

m=5
n=10
a = np.random.random((m, n))
x = np.random.random((m, 1))                          # x coordinates
y = np.random.random((1, n))                          # y coordinates

b = np.empty((3, m*n))                # array to store coordinates
k=0
for i in range (0,m):
    for j in range (0,n):
        b[0,k] = a[i,0]
        b[1,k] = a[0,j]
        b[2,k] = a[i,j]
        k=k+1
</code>```

This seems to run ok, but is there a faster or better coded way to do this?

答:
Steps :

Initialize a 3D array, such that m and n are separate ones. This lets us broadcast values.

Index into the first three elements along the first axis of output with appropriate elements off a and make sure that those shapes are broadcastable.

Reshape the output back to 2D.

That's all the play is about here! Here's the vectorized implementation -

```<code>b_out = np.empty((3, m,n),dtype=a.dtype)  # 1. Initialize
b_out[0] = a[:,0,None]                    # 2. Assign
b_out[1] = a[0]
b_out[2] = a
b_out.shape = (3,m*n)                     # 3. Reshape back to 2D
</code>```

Runtime test

Approaches -

```<code>def loopy_app(a):
    m,n = a.shape
    b = np.empty((3, m*n),dtype=a.dtype)
    k=0
    for i in range (0,m):
        for j in range (0,n):
            b[0,k] = a[i,0]
            b[1,k] = a[0,j]
            b[2,k] = a[i,j]
            k=k+1
    return b

def vectorized_app(a):
    b_out = np.empty((3, m,n),dtype=a.dtype)
    b_out[0] = a[:,0,None]
    b_out[1] = a[0]
    b_out[2] = a
    b_out.shape = (3,m*n)
    return b_out
</code>```

Timings -

```<code>In [194]: m=5
     ...: n=10
     ...: a = np.random.random((m, n))
     ...:

In [195]: %timeit loopy_app(a)
     ...: %timeit vectorized_app(a)
     ...:
10000 loops, best of 3: 28.2 µs per loop
100000 loops, best of 3: 2.48 µs per loop

In [196]: m=50
     ...: n=100
     ...: a = np.random.random((m, n))
     ...:

In [197]: %timeit loopy_app(a)
     ...: %timeit vectorized_app(a)
     ...:
100 loops, best of 3: 2.56 ms per loop
100000 loops, best of 3: 6.31 µs per loop

In [198]: 2560/6.31
Out[198]: 405.7052297939778
</code>```

400x+ speedup on large datasets and more on larger ones!

Body:
I have a mXn numpy array called a:
I would like to write a function which returns an array with size (3, mxn) which contains for each couple (x,y) in the first array the correspondant value.

import numpy as np

m=5
n=10
a = np.random.random((m, n))
x = np.random.random((m, 1))                          # x coordinates
y = np.random.random((1, n))                          # y coordinates

b = np.empty((3, m*n))                # array to store coordinates
k=0
for i in range (0,m):
    for j in range (0,n):
        b[0,k] = a[i,0]
        b[1,k] = a[0,j]
        b[2,k] = a[i,j]
        k=k+1

This seems to run ok, but is there a faster or better coded way to do this?

Body:
Steps :

Initialize a 3D array, such that m and n are separate ones. This lets us broadcast values.

Index into the first three elements along the first axis of output with appropriate elements off a and make sure that those shapes are broadcastable.

Reshape the output back to 2D.

That's all the play is about here! Here's the vectorized implementation -

b_out = np.empty((3, m,n),dtype=a.dtype)  # 1. Initialize
b_out[0] = a[:,0,None]                    # 2. Assign
b_out[1] = a[0]
b_out[2] = a
b_out.shape = (3,m*n)                     # 3. Reshape back to 2D

Runtime test

Approaches -

def loopy_app(a):
    m,n = a.shape
    b = np.empty((3, m*n),dtype=a.dtype)
    k=0
    for i in range (0,m):
        for j in range (0,n):
            b[0,k] = a[i,0]
            b[1,k] = a[0,j]
            b[2,k] = a[i,j]
            k=k+1
    return b

def vectorized_app(a):
    b_out = np.empty((3, m,n),dtype=a.dtype)
    b_out[0] = a[:,0,None]
    b_out[1] = a[0]
    b_out[2] = a
    b_out.shape = (3,m*n)
    return b_out

Timings -

In [194]: m=5
     ...: n=10
     ...: a = np.random.random((m, n))
     ...:

In [195]: %timeit loopy_app(a)
     ...: %timeit vectorized_app(a)
     ...:
10000 loops, best of 3: 28.2 µs per loop
100000 loops, best of 3: 2.48 µs per loop

In [196]: m=50
     ...: n=100
     ...: a = np.random.random((m, n))
     ...:

In [197]: %timeit loopy_app(a)
     ...: %timeit vectorized_app(a)
     ...:
100 loops, best of 3: 2.56 ms per loop
100000 loops, best of 3: 6.31 µs per loop

In [198]: 2560/6.31
Out[198]: 405.7052297939778

400x+ speedup on large datasets and more on larger ones!


来源: stackexchange

问:
how to compare the two fields in same input xml data using xslt?
Can anyone please help me out from this.
Actually thing is when you compare with "ID"s, if "ID"s are equals ,it return "bb" or what are input we having in input xml. if it has not equal,some thing will return.I will be all input and xslt coding provided in screenshot.

Thanks for advance.

Myxslt:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="Emps/Emp">
<xsl:variable name="Result1" select="Id[1]"></xsl:variable>
<xsl:variable name="Result2" select="Id[2]"></xsl:variable>
</xsl:for-each>
<xsl:choose>
   <xsl:when test='compare($Result1) = ($Result2)'>
     <xsl:value-of-select="$Result1"/>
   </xsl:when>
   <xsl:otherwise>
     <xsl:value-of-select="$Result2"/>
   </xsl:otherwise>
</xsl:choose>
  </xsl:template>
</xsl:stylesheet>
</code>```

Required Output:
 <Name>bb</Name>

答:
You are defining your Result1 and Result2 variables inside a xsl:for-each construct. That means they will be local in scope to that block, and not accessible outside it. Additionally, where you use Id[2] that will be looking for the second Id element under the current Emp element, when you really want the Id element under the second Emp element.

So, replace your xsl:for-each with this...

```<code><xsl:variable name="Result1" select="Emps/Emp[1]/Id" />
<xsl:variable name="Result2" select="Emps/Emp[2]/Id" />
</code>```

Furthermore, to compare Result1 and Result2 you just do <xsl:when test="$Result1 = $Result2">

And finally, doing <xsl:value-of select="$Result1"/> will output the Id value. To output the Name you can do this...

```<code> <xsl:value-of select="$Result1/following-sibling::Name"/>
</code>```

Try this XSLT

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <xsl:variable name="Result1" select="Emps/Emp[1]/Id" />
  <xsl:variable name="Result2" select="Emps/Emp[2]/Id" />
  <xsl:choose>
    <xsl:when test="$Result1 = $Result2">
      <xsl:value-of select="$Result1/following-sibling::Name"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$Result2/following-sibling::Name"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
</xsl:stylesheet>
</code>```

Note, you don't really need variables here. Try this XSLT too

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <xsl:choose>
    <xsl:when test="Emps/Emp[1]/Id = Emps/Emp[2]/Id">
      <xsl:value-of select="Emps/Emp[1]/Name"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="Emps/Emp[2]/Name"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
</xsl:stylesheet>
</code>```

Of course, both of these assume only two Emp elements in your XML. I can't help thinking that perhaps you are trying to eliminate duplicate Ids from your XML. If so, you should read up on a technique called Muenchian Grouping (If you are using XSLT 1.0, that is. If you are using XSLT 2.0, you can use xsl:for-each-group).

ContentLicense: CC BY-SA 3.0

Body:
Can anyone please help me out from this.
Actually thing is when you compare with "ID"s, if "ID"s are equals ,it return "bb" or what are input we having in input xml. if it has not equal,some thing will return.I will be all input and xslt coding provided in screenshot.

Thanks for advance.

Myxslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="Emps/Emp">
<xsl:variable name="Result1" select="Id[1]"></xsl:variable>
<xsl:variable name="Result2" select="Id[2]"></xsl:variable>
</xsl:for-each>
<xsl:choose>
   <xsl:when test='compare($Result1) = ($Result2)'>
     <xsl:value-of-select="$Result1"/>
   </xsl:when>
   <xsl:otherwise>
     <xsl:value-of-select="$Result2"/>
   </xsl:otherwise>
</xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Required Output:
 <Name>bb</Name>

Body:
You are defining your Result1 and Result2 variables inside a xsl:for-each construct. That means they will be local in scope to that block, and not accessible outside it. Additionally, where you use Id[2] that will be looking for the second Id element under the current Emp element, when you really want the Id element under the second Emp element.

So, replace your xsl:for-each with this...

<xsl:variable name="Result1" select="Emps/Emp[1]/Id" />
<xsl:variable name="Result2" select="Emps/Emp[2]/Id" />

Furthermore, to compare Result1 and Result2 you just do <xsl:when test="$Result1 = $Result2">

And finally, doing <xsl:value-of select="$Result1"/> will output the Id value. To output the Name you can do this...

 <xsl:value-of select="$Result1/following-sibling::Name"/>

Try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <xsl:variable name="Result1" select="Emps/Emp[1]/Id" />
  <xsl:variable name="Result2" select="Emps/Emp[2]/Id" />
  <xsl:choose>
    <xsl:when test="$Result1 = $Result2">
      <xsl:value-of select="$Result1/following-sibling::Name"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$Result2/following-sibling::Name"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
</xsl:stylesheet>

Note, you don't really need variables here. Try this XSLT too

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <xsl:choose>
    <xsl:when test="Emps/Emp[1]/Id = Emps/Emp[2]/Id">
      <xsl:value-of select="Emps/Emp[1]/Name"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="Emps/Emp[2]/Name"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
</xsl:stylesheet>

Of course, both of these assume only two Emp elements in your XML. I can't help thinking that perhaps you are trying to eliminate duplicate Ids from your XML. If so, you should read up on a technique called Muenchian Grouping (If you are using XSLT 1.0, that is. If you are using XSLT 2.0, you can use xsl:for-each-group).


问:
Scan C disk and copy files
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

```<code>Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"
</code>```

How should I fix the last couple of things on my list?
Thanks

答:
I believe the issue is that after the files are copied, the object is gone from the pipeline.

This works:

```<code>Get-ChildItem -Path C:\ -Include *.pst -ErrorAction SilentlyContinue | Select-Object FullName, LastWriteTime | Export-Csv -Path "\fileserver01\temp\test\MyCSV.csv"
</code>```

Title: Scan C disk and copy files

Body:
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"

How should I fix the last couple of things on my list?
Thanks

Body:
I believe the issue is that after the files are copied, the object is gone from the pipeline.

This works:

Get-ChildItem -Path C:\ -Include *.pst -ErrorAction SilentlyContinue | Select-Object FullName, LastWriteTime | Export-Csv -Path "\fileserver01\temp\test\MyCSV.csv"


问:
Check response of validation in codeception
I created, using laravel, a php with this method:

```<code>  public function register(Request $request) {
    try {
        $validator = \Validator::make($request->input(), [
                    'email' => 'required|email|unique:users_x_communities',
                    'first_name' => array('required', 'regex:/^[\pL\s]+$/u'),
                    'last_name' => array('required', 'regex:/^[\pL\s]+$/u'),
                    'community_id' => 'required|exists:communities,id',
                        ], [
                    'email.required' => 'El correo electrónico es requerido.',
                    'email.email' => 'El correo electrónico es inválido.',
                    'email.unique' => 'El correo electrónico ya esta en uso.',
                    'first_name.required' => 'Los nombres son requeridos.',
                    'first_name.regex' => 'Los nombres deben ser un texto.',
                    'last_name.required' => 'Los apellidos son requeridos.',
                    'last_name.regex' => 'Los apellidos deben ser un texto.',
                    'community_id.required' => 'La comunidad es requerida.',
                    'community_id.exists' => 'La comunidad no existe.'
                        ]
        );
        if ($validator->fails()) {
            return $this->errorBadRequest($validator->messages());
        }
        $email = strtolower($request->get('email'));
        $firstName = $request->get('first_name');
        $lastName = $request->get('last_name');
        $communityId = $request->get('community_id');
        $status = $this->auth->register($firstName, $lastName, $email, $communityId);
        $message = "OK!";

        return $this->response->array(compact('status', 'message'));
    } catch (Exception $e) {
        Log::error('AuthController@register: ' . $e->getMessage());
        return $this->validException($e);
    }
}
</code>```

Im interested in making some test in codeception to validate my function, in this case that the 4 fields, email, first_name, last_name and community_id are required.

ive managed this in codeception (ResgisterCest.php):

```<code>    public function validateifmailisrequired(ApiTester $I) //200
    {

            //Method created to validate if the mail is required

            $I->wantTo('Validate that the mail field is required');
            $I->sendPOST($this->url, [
                'email' => '',
            ]);

    }
</code>```

But im kind of new and im not quite sure how to check the response that the email, for example, is required. Im new in this and a bit confused with codeception... how can i achive this? to have codeception tell me that if i sendPost with an empty mail returns me a response of field required or some response that let me test that my email and others are required....

答:
Use seeResponseContainsJson method.

```<code>$I->sendPOST($this->url, ['email' => '']);
$I->seeResponseContainsJson(['error' => 'El correo electrónico es requerido.']);
</code>```

Make the structure of expected array match the structure of response
(but don't specify all keys, only those that matter for this test).

Body:
I created, using laravel, a php with this method:

  public function register(Request $request) {
    try {
        $validator = \Validator::make($request->input(), [
                    'email' => 'required|email|unique:users_x_communities',
                    'first_name' => array('required', 'regex:/^[\pL\s]+$/u'),
                    'last_name' => array('required', 'regex:/^[\pL\s]+$/u'),
                    'community_id' => 'required|exists:communities,id',
                        ], [
                    'email.required' => 'El correo electrónico es requerido.',
                    'email.email' => 'El correo electrónico es inválido.',
                    'email.unique' => 'El correo electrónico ya esta en uso.',
                    'first_name.required' => 'Los nombres son requeridos.',
                    'first_name.regex' => 'Los nombres deben ser un texto.',
                    'last_name.required' => 'Los apellidos son requeridos.',
                    'last_name.regex' => 'Los apellidos deben ser un texto.',
                    'community_id.required' => 'La comunidad es requerida.',
                    'community_id.exists' => 'La comunidad no existe.'
                        ]
        );
        if ($validator->fails()) {
            return $this->errorBadRequest($validator->messages());
        }
        $email = strtolower($request->get('email'));
        $firstName = $request->get('first_name');
        $lastName = $request->get('last_name');
        $communityId = $request->get('community_id');
        $status = $this->auth->register($firstName, $lastName, $email, $communityId);
        $message = "OK!";

        return $this->response->array(compact('status', 'message'));
    } catch (Exception $e) {
        Log::error('AuthController@register: ' . $e->getMessage());
        return $this->validException($e);
    }
}

Im interested in making some test in codeception to validate my function, in this case that the 4 fields, email, first_name, last_name and community_id are required.

ive managed this in codeception (ResgisterCest.php):

    public function validateifmailisrequired(ApiTester $I) //200
    {

            //Method created to validate if the mail is required

            $I->wantTo('Validate that the mail field is required');
            $I->sendPOST($this->url, [
                'email' => '',
            ]);

    }

But im kind of new and im not quite sure how to check the response that the email, for example, is required. Im new in this and a bit confused with codeception... how can i achive this? to have codeception tell me that if i sendPost with an empty mail returns me a response of field required or some response that let me test that my email and others are required....

Body:
Use seeResponseContainsJson method.

$I->sendPOST($this->url, ['email' => '']);
$I->seeResponseContainsJson(['error' => 'El correo electrónico es requerido.']);

Make the structure of expected array match the structure of response
(but don't specify all keys, only those that matter for this test).


问:
Why the below code does not compile with gcc but compiles fine with clang
Below code compiles fine with clang but not gcc , any explanation is this a bug in gcc?

Its just a class which contains a vector of unique_ptr and std::function as member and when I create vector of this class , I cant say reserve or resize on this. push_back works fine with std::move, while this only happens with gcc and not clang.

```<code>#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class ABC
{
public:
    ABC()
          {}
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

int main()
{
    ABC a;
    std::vector<ABC> vec;
    vec.reserve(1);
}
</code>```

Error message looks like below for gcc

```<code>In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_tempbuf.h:60:0,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_algo.h:62,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/algorithm:62,
                 from prog.cc:1:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::unique_ptr<int>; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}]':
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:331:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:10:7:   required from 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = ABC; _Args = {const ABC&}]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; _Tp = ABC]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:1263:35:   required from 'std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = const ABC*; _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::pointer = ABC*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/vector.tcc:73:40:   required from 'void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
prog.cc:24:18:   required from here
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h:75:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/memory:80:0,
                 from prog.cc:2:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/unique_ptr.h:388:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^~~~~~~~~~
</code>```

答:
I think that GCC is being picky about constructors; it blocks the generation of the move-ctor1. It stops complaining after you provide them explicitely:

```<code>class ABC
{
public:
    ABC() = default;        // <--
    ABC(ABC&&) = default;   // <--
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};
</code>```

1 I think (again, I'm not sure), that his happens because the default copy-ctor of ABC is defined as noexcept and is as such preferred over the default move-ctor (it's still ill-formed because we're dealing with non-copyable members here). Trying to generate a defaulted noexcept move-ctor result in:

```<code>main.cpp:14:4: note: 'ABC::ABC(ABC&&) noexcept' is implicitly deleted because its exception-specification does not match the implicit exception-specification ''
    ABC(ABC&&) noexcept = default;
    ^~~
</code>```

As such, forcing the generation of no-noexcept move-ctor allows it to be picked. Why Clang doesn't have a problem with that - I don't know.

One explanation for the above is hinted by the fact that removing std::function allows the defaulted noexcept move-ctor to be generated. std::function doesn't have a noexcept move-ctor (which sucks tremendously), so the whole class falls back to the copy-ctor. Since unique_ptr doesn't have one, the whole thing breaks.

Body:
Below code compiles fine with clang but not gcc , any explanation is this a bug in gcc?

Its just a class which contains a vector of unique_ptr and std::function as member and when I create vector of this class , I cant say reserve or resize on this. push_back works fine with std::move, while this only happens with gcc and not clang.

#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class ABC
{
public:
    ABC()
          {}
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

int main()
{
    ABC a;
    std::vector<ABC> vec;
    vec.reserve(1);
}

Error message looks like below for gcc

In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_tempbuf.h:60:0,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_algo.h:62,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/algorithm:62,
                 from prog.cc:1:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::unique_ptr<int>; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}]':
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:331:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:10:7:   required from 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = ABC; _Args = {const ABC&}]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; _Tp = ABC]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:1263:35:   required from 'std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = const ABC*; _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::pointer = ABC*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/vector.tcc:73:40:   required from 'void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
prog.cc:24:18:   required from here
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h:75:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/memory:80:0,
                 from prog.cc:2:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/unique_ptr.h:388:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^~~~~~~~~~

Body:
I think that GCC is being picky about constructors; it blocks the generation of the move-ctor1. It stops complaining after you provide them explicitely:

class ABC
{
public:
    ABC() = default;        // <--
    ABC(ABC&&) = default;   // <--
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

1 I think (again, I'm not sure), that his happens because the default copy-ctor of ABC is defined as noexcept and is as such preferred over the default move-ctor (it's still ill-formed because we're dealing with non-copyable members here). Trying to generate a defaulted noexcept move-ctor result in:

main.cpp:14:4: note: 'ABC::ABC(ABC&&) noexcept' is implicitly deleted because its exception-specification does not match the implicit exception-specification ''
    ABC(ABC&&) noexcept = default;
    ^~~

As such, forcing the generation of no-noexcept move-ctor allows it to be picked. Why Clang doesn't have a problem with that - I don't know.

One explanation for the above is hinted by the fact that removing std::function allows the defaulted noexcept move-ctor to be generated. std::function doesn't have a noexcept move-ctor (which sucks tremendously), so the whole class falls back to the copy-ctor. Since unique_ptr doesn't have one, the whole thing breaks.


问:
How much memory is allocated for static primitive type and static reference type in Java
I have two different class with static variables. One class with static reference type variables and another class with static primitive type variables. When i calculated the size of the each static variables using Instrumentation.getObjectSize() method it returns the same size. But from my understanding, class object has header section and padding section additional to its global variables so this reference type is always should be great in memory while compared to primitive type. Please find my code below:

ObjectSizeFetcher.java

```<code>import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}
</code>```

DaysOfWeek1.java

```<code>public class DaysOfWeek1 {
    public static final DaysOfWeek1 Sunday = new DaysOfWeek1(1);
    public static final DaysOfWeek1 Monday = new DaysOfWeek1(2);
    public static final DaysOfWeek1 Tuesday = new DaysOfWeek1(4);
    public static final DaysOfWeek1 Wednesday = new DaysOfWeek1(8);
    public static final DaysOfWeek1 Thursday = new DaysOfWeek1(16);
    public static final DaysOfWeek1 Friday = new DaysOfWeek1(32);
    public static final DaysOfWeek1 Saturday = new DaysOfWeek1(64);

    private int intValue;

    private DaysOfWeek(int value) {
        intValue = value;
    }
}
</code>```

DaysOfWeek2.java

```<code>public final class DaysOfWeek2 {
    public static final int Sunday = (1);
    public static final int Monday = (2);
    public static final int Tuesday = (4);
    public static final int Wednesday = (8);
    public static final int Thursday = (16);
    public static final int Friday = (32);
    public static final int Saturday = (64);

}
</code>```

Test.java

```<code>public class Test {
    public static void main(String[] args) throws Exception {
        int i=10;
        long value = ObjectSizeFetcher.getObjectSize(DaysOfWeek1.Friday);
        System.out.println(value);// provide 16 bytes

        long value1 = ObjectSizeFetcher.getObjectSize(DaysOfWeek2.Sunday);
        System.out.println(value1);// provide 16 bytes

        long value2 = ObjectSizeFetcher.getObjectSize(i);
        System.out.println(value2);// provide 16 bytes
    }
}
</code>```

Can anyone explain me how JVM allocates memory for the above scenario?

Thanks in advance.

Regards,
Sarath

答:
getObjectSize() is meant to give an approximation of the size of objects of the specified type. They aren't affected by static fields, because static fields exist on a per-type basis rather than a per-object basis.

Add as many static fields as you like, and I wouldn't expect getObjectSize to change.

Body:
I have two different class with static variables. One class with static reference type variables and another class with static primitive type variables. When i calculated the size of the each static variables using Instrumentation.getObjectSize() method it returns the same size. But from my understanding, class object has header section and padding section additional to its global variables so this reference type is always should be great in memory while compared to primitive type. Please find my code below:

ObjectSizeFetcher.java

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

DaysOfWeek1.java

public class DaysOfWeek1 {
    public static final DaysOfWeek1 Sunday = new DaysOfWeek1(1);
    public static final DaysOfWeek1 Monday = new DaysOfWeek1(2);
    public static final DaysOfWeek1 Tuesday = new DaysOfWeek1(4);
    public static final DaysOfWeek1 Wednesday = new DaysOfWeek1(8);
    public static final DaysOfWeek1 Thursday = new DaysOfWeek1(16);
    public static final DaysOfWeek1 Friday = new DaysOfWeek1(32);
    public static final DaysOfWeek1 Saturday = new DaysOfWeek1(64);

    private int intValue;

    private DaysOfWeek(int value) {
        intValue = value;
    }
}

DaysOfWeek2.java

public final class DaysOfWeek2 {
    public static final int Sunday = (1);
    public static final int Monday = (2);
    public static final int Tuesday = (4);
    public static final int Wednesday = (8);
    public static final int Thursday = (16);
    public static final int Friday = (32);
    public static final int Saturday = (64);

}

Test.java

public class Test {
    public static void main(String[] args) throws Exception {
        int i=10;
        long value = ObjectSizeFetcher.getObjectSize(DaysOfWeek1.Friday);
        System.out.println(value);// provide 16 bytes

        long value1 = ObjectSizeFetcher.getObjectSize(DaysOfWeek2.Sunday);
        System.out.println(value1);// provide 16 bytes

        long value2 = ObjectSizeFetcher.getObjectSize(i);
        System.out.println(value2);// provide 16 bytes
    }
}

Can anyone explain me how JVM allocates memory for the above scenario?

Thanks in advance.

Regards,
Sarath


问:
How can I get variable from another function?
My case like this :

Html code (This is modal) :

```<code><div class="modal-body">
    ...
    <input type="file" id="change-image" name="replace">
    ...
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>
</div>
</code>```

If I click input type file, it will run the javascript code :

```<code>$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});
</code>```

There exist variable data image

If I run this :

```<code>$('#confirm-edit-image').on("click",function(){
    // get variable data
});
</code>```

I want to get the variable data image

How can I do it?

答:
Declaring data outside those functions is enough to share the variable itself. Here's a live snippet.

For further details about variable scope in javascript, you can refer to this answer What is the scope of variables in JavaScript?.

var data = new FormData();

$('#change-image').change(function (e) {
    data.append('file', $('#change-image')[0].files[0]);
});

$('#confirm-edit-image').on("click",function(){
    var empty = true;
    for (entry of data.entries()) {
      console.log(entry);
      empty = false;
    }
    if(empty) { console.log("Please add a file first!\n"); }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
    ...
    <input type="file" id="change-image" name="replace">
    ...
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>
</div></code>```

Body:
My case like this :

Html code (This is modal) :

    ...
    <input type="file" id="change-image" name="replace">
    ...
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>

If I click input type file, it will run the javascript code :

$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});

There exist variable data image

If I run this :

$('#confirm-edit-image').on("click",function(){
    // get variable data
});

I want to get the variable data image

How can I do it?

Body:
Declaring data outside those functions is enough to share the variable itself. Here's a live snippet.

For further details about variable scope in javascript, you can refer to this answer What is the scope of variables in JavaScript?.

var data = new FormData();

$('#change-image').change(function (e) {
    data.append('file', $('#change-image')[0].files[0]);
});

$('#confirm-edit-image').on("click",function(){
    var empty = true;
    for (entry of data.entries()) {
      console.log(entry);
      empty = false;
    }
    if(empty) { console.log("Please add a file first!\n"); }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
    ...
    <input type="file" id="change-image" name="replace">
    ...
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>
</div>


问:
Appcompatv7 - v21 Navigation drawer not showing hamburger icon
I am implementing the lollipop style navigation drawer with latest appcompat support library but the problem is the hamburger icon is never displayed . Only back icon is shown.

This is my activity code

```<code>import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class Home extends ActionBarActivity {

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;

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

private void initViews(){

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
    setSupportActionBar(toolbar);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar ,  R.string.drawer_open, R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            //getActionBar().setTitle(mTitle);
            //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            //getActionBar().setTitle(mDrawerTitle);
            //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    // Set the drawer toggle as the DrawerListener
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

 }
}
</code>```

This is my styles file

```<code> <resources>
 <!-- Application theme. -->
<style name="Theme.Test" parent="@style/Theme.AppCompat.Light">

    <!-- customize the color palette -->
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="windowActionBar">false</item>
    <item name="drawerArrowStyle">@style/Theme.Test.DrawerArrowStyle</item>
</style>

<style name="Theme.Test.DrawerArrowStyle" parent="@style/Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>
</code>```

The layout file

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar">

    <!-- The main content view -->

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

</RelativeLayout>
</code>```

In both cases only back arrow is shown , i have read many posts but nothing seems to make a difference . Any help would be appreciated.

答:
I also got similar problem, in my case problem was,
when initiating actionbartoggle,
I was not passing valid toolbar argument (toolbar was initialized later),
without a proper, non-null toolbar, ActionBarToggle will fail to create a hamburger icon.</p>

```<code>actionBarToggle = ActionBarDrawerToggle(this, mDrawer, toolbar,
R.string.drawer_open, R.string.drawer_close);
</code>```

Body:
I am implementing the lollipop style navigation drawer with latest appcompat support library but the problem is the hamburger icon is never displayed . Only back icon is shown.

This is my activity code

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class Home extends ActionBarActivity {

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;

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

private void initViews(){

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
    setSupportActionBar(toolbar);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar ,  R.string.drawer_open, R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            //getActionBar().setTitle(mTitle);
            //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            //getActionBar().setTitle(mDrawerTitle);
            //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    // Set the drawer toggle as the DrawerListener
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

 }
}

This is my styles file

 <resources>

The layout file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

</RelativeLayout>

In both cases only back arrow is shown , i have read many posts but nothing seems to make a difference . Any help would be appreciated.

Body:
I also got similar problem, in my case problem was,
when initiating actionbartoggle,
I was not passing valid toolbar argument (toolbar was initialized later),
without a proper, non-null toolbar, ActionBarToggle will fail to create a hamburger icon.

actionBarToggle = ActionBarDrawerToggle(this, mDrawer, toolbar,
R.string.drawer_open, R.string.drawer_close);


问:
Passing non-const arguments to const function parameters in C
I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:

```<code>int func1(const char *some_string)
{
    // Do something non-destructive with some_string
}
</code>```

I pass a non-const variable as an argument to func1:

```<code>int func2(void)
{
    char *my_string = "my text";
    func1(my_string);
}
</code>```

gcc reports:

```<code>warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
</code>```

What is the correct way to deal with this situation? Creating a const copy of my_string seems a bit much, but simply casting seems like burying the warning.

答: You could use const char *my_string = "my text"; instead of char *my_string = "my text";

Body:
I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:

int func1(const char *some_string)
{
    // Do something non-destructive with some_string
}

I pass a non-const variable as an argument to func1:

int func2(void)
{
    char *my_string = "my text";
    func1(my_string);
}

gcc reports:

warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

What is the correct way to deal with this situation? Creating a const copy of my_string seems a bit much, but simply casting seems like burying the warning.


问:
Scrollbar location is moving visible/nonvisible changing controls
I have a form with a scrollable panel and two controls sitting right on top of each other - one visible one not. Based on a certain condition when that form is activated I might swap the visible properties of the two controls. These controls are at the bottom of the scrollable panel. If when I leave that form I leave it scrolled to the bottom, go change the condition that will cause the controls' visibility to swap and go back to that form the visible control will have dropped about 200px down the page leaving a large gap. Anyone know what could be causing this? I tried resetting the scrollbar position to the top on form close but that just causes a smaller gap and sometimes the control to move higher into other controls. Any ideas?</p>

答: No repro.  Sounds to me that you are doing more than just changing the Visible property.  Whenever you assign the Location property, you have to add the AutoScrollPosition to compensate for the scroll state.  Post code if this doesn't help.</p>

ContentLicense: CC BY-SA 2.5


问:
How to continue in a loop when the file does not exist?
This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found. </p>

```<code>for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       download(d)

 end
end
</code>```

<p>Any ideas? Thanks </p>

答:
You could add an 'if' statement before the download(d) statement to ask whether the file exists.  Something like:

```<code>for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       if exist(d)   % where d is the file
          download(d)
       else
          continue  % Jump to next loop iteration if file doesn't exist
       end
   end
end
</code>```

Assuming that 'd' is the file in question that you want to download.  You might need to use the file's whole address to make sure Matlab can find it.

Body:
This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found.

for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       download(d)

 end
end

Any ideas? Thanks

Body:
You could add an 'if' statement before the download(d) statement to ask whether the file exists.  Something like:

for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       if exist(d)   % where d is the file
          download(d)
       else
          continue  % Jump to next loop iteration if file doesn't exist
       end
   end
end

Assuming that 'd' is the file in question that you want to download.  You might need to use the file's whole address to make sure Matlab can find it.


问:
Set AUTO_INCREMENT in all tables within a MySQL DB to the largest inserted increment value
Is it possible to set AUTO_INCREMENT value for all tables within a database to the latest insert value?

UPDATE
For example if my table had 1000 records with increment values from 1..1000 and I have deleted last 900 records the last increment value in the field would be 100. I would like to set the AUTO_INCREMENT to the 101. And this for all tables within DB.

答:
This is automatically done.

Quoting the manual:

You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.


问:
What's the best practice for naming Swift files that add extensions to existing objects?
It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.

As a result, it's possible to create extensions such as:

```<code>extension String {
    var utf8data:NSData {
        return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    }
}
</code>```

However, what's the best naming practice for Swift source files containing such extensions?

In the past, the convention was to use extendedtype+categoryname.m for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it String.swift doesn't seem appropriate.

So the question is: given the above String extension, what should the swift source file be called?

答:
If you have a team-agreed set of common and miscellaneous enhancements, lumping them together as an Extensions.swift works as Keep-It-Simple first level solution.  However, as your complexity grows, or the extensions become more involved, a hierarchy is needed to encapsulate the complexity.  In such circumstances I recommend the following practice with an example.

I had a class which talks to my back-end, called Server.  It started to grow bigger to cover two different target apps.  Some people like a large file but just logically split up with extensions.  My preference is to keep each file relatively short so I chose the following solution.  Server originally conformed to CloudAdapterProtocol and implemented all its methods.  What I did was to turn the protocol into a hierarchy, by making it refer to subordinate protocols:

```<code>protocol CloudAdapterProtocol: ReggyCloudProtocol, ProReggyCloudProtocol {
    var server: CloudServer {
        get set
    }
    func getServerApiVersion(handler: @escaping (String?, Error?) -> Swift.Void)
}
</code>```

In Server.swift I have

```<code>import Foundation
import UIKit
import Alamofire
import AlamofireImage

class Server: CloudAdapterProtocol {
.
.
func getServerApiVersion(handler: @escaping (String?, Error?) -> Swift.Void) {
.
.
}
</code>```

Server.swift then just implements the core server API for setting the server and getting the API version.  The real work is split into two files:

```<code>Server_ReggyCloudProtocol.swift
Server_ProReggyCloudProtocol.swift
</code>```

These implement the respective protocols.

It means you need to have import declarations in the other files (for Alamofire in this example) but its a clean solution in terms of segregating interfaces in my view.

I think this approach works equally well with externally specified classes as well as your own.

Body:
It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.

As a result, it's possible to create extensions such as:

extension String {
    var utf8data:NSData {
        return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    }
}

However, what's the best naming practice for Swift source files containing such extensions?

In the past, the convention was to use extendedtype+categoryname.m for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it String.swift doesn't seem appropriate.

So the question is: given the above String extension, what should the swift source file be called?

Body:
If you have a team-agreed set of common and miscellaneous enhancements, lumping them together as an Extensions.swift works as Keep-It-Simple first level solution.  However, as your complexity grows, or the extensions become more involved, a hierarchy is needed to encapsulate the complexity.  In such circumstances I recommend the following practice with an example.

I had a class which talks to my back-end, called Server.  It started to grow bigger to cover two different target apps.  Some people like a large file but just logically split up with extensions.  My preference is to keep each file relatively short so I chose the following solution.  Server originally conformed to CloudAdapterProtocol and implemented all its methods.  What I did was to turn the protocol into a hierarchy, by making it refer to subordinate protocols:

protocol CloudAdapterProtocol: ReggyCloudProtocol, ProReggyCloudProtocol {
    var server: CloudServer {
        get set
    }
    func getServerApiVersion(handler: @escaping (String?, Error?) -> Swift.Void)
}

In Server.swift I have

import Foundation
import UIKit
import Alamofire
import AlamofireImage

class Server: CloudAdapterProtocol {
.
.
func getServerApiVersion(handler: @escaping (String?, Error?) -> Swift.Void) {
.
.
}

Server.swift then just implements the core server API for setting the server and getting the API version.  The real work is split into two files:

Server_ReggyCloudProtocol.swift
Server_ProReggyCloudProtocol.swift

These implement the respective protocols.

It means you need to have import declarations in the other files (for Alamofire in this example) but its a clean solution in terms of segregating interfaces in my view.

I think this approach works equally well with externally specified classes as well as your own.


问:
How do I set text-overflow to ellipsis in CSS grid layout?
I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div></code>```

答:
1) when use text-overflow: ellipsis; must use overflow: hidden; too.

2)white-space: nowrap; Does not allow text break in new line.

So, Change Like This :

```<code>.long {
  text-overflow: ellipsis;
  overflow: hidden;/*/<------------new/*/
  white-space: nowrap;/*/<---------new/*/
}
</code>```

Body:
I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}

Left

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Right

  <content>
  </content>

Body:
1) when use text-overflow: ellipsis; must use overflow: hidden; too.

2)white-space: nowrap; Does not allow text break in new line.

So, Change Like This :

.long {
  text-overflow: ellipsis;
  overflow: hidden;/*/<------------new/*/
  white-space: nowrap;/*/<---------new/*/
}


问:
Android Facebook Share Button asking for password again
I'm logged in in my app with a parse session linked with facebook. When I try to share a post to facebook it shows me the facebook window to login again. Why does it do that if I'm already logged in? I checked and the AccessToken.getCurrentAccessToken() is not null when I call the ShareDialog, so there is the session. What's wrong?

WelcomeActivity

```<code>public void initializeFacebookButton() {

    if (AccessToken.getCurrentAccessToken() == null)
        ParseFacebookUtils.initialize(this);

    mLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
            ParseFacebookUtils.logInWithReadPermissionsInBackground(WelcomeActivity.this,
                    read_permissions, new LogInCallback() {
                        @Override
                        public void done(ParseUser user, ParseException e) {
                            progressBar.setVisibility(View.GONE);
                            if (e == null && user !=  null){
                                ParseFacebookUtils.linkWithPublishPermissionsInBackground(user,
                                        WelcomeActivity.this, publish_permission);
                                Log.d(TAG, "logged in");
                                   presenter.getUserFacebook(AccessToken.getCurrentAccessToken(),
                                        user);
                            } else {
                                Log.e(TAG, "Error logging in ");
                            }
                        }
                    });
        }
    });
}
</code>```

ShareActivity

```<code>Button shareButton;

shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
                .putString("og:type", "fitness.course")
                .putString("og:title", title)
                .putString("og:description", description)
                .putInt("fitness:duration:value", time_in_seconds)
                .putString("fitness:duration:units", "s")
                .putDouble("fitness:metrics:location:latitude", latitude)
                .putDouble("fitness:metrics:location:longitude", longitude)
                .build();
        ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
                .setActionType("fitness.runs")
                .putObject("fitness:course", object)
                .build();
        ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
                .setPreviewPropertyName("fitness:course")
                .setAction(action)
                .build();

                ShareDialog.show(ShareActivity.this, content);
            }
        });
</code>```

答:
Did you logged out somewhere before shareButton clicked?
Check below code.</p>

```<code>LoginManager.getInstance().logOut();
</code>```

Body:
I'm logged in in my app with a parse session linked with facebook. When I try to share a post to facebook it shows me the facebook window to login again. Why does it do that if I'm already logged in? I checked and the AccessToken.getCurrentAccessToken() is not null when I call the ShareDialog, so there is the session. What's wrong?

WelcomeActivity

public void initializeFacebookButton() {

    if (AccessToken.getCurrentAccessToken() == null)
        ParseFacebookUtils.initialize(this);

    mLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
            ParseFacebookUtils.logInWithReadPermissionsInBackground(WelcomeActivity.this,
                    read_permissions, new LogInCallback() {
                        @Override
                        public void done(ParseUser user, ParseException e) {
                            progressBar.setVisibility(View.GONE);
                            if (e == null && user !=  null){
                                ParseFacebookUtils.linkWithPublishPermissionsInBackground(user,
                                        WelcomeActivity.this, publish_permission);
                                Log.d(TAG, "logged in");
                                   presenter.getUserFacebook(AccessToken.getCurrentAccessToken(),
                                        user);
                            } else {
                                Log.e(TAG, "Error logging in ");
                            }
                        }
                    });
        }
    });
}

ShareActivity

Button shareButton;

shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
                .putString("og:type", "fitness.course")
                .putString("og:title", title)
                .putString("og:description", description)
                .putInt("fitness:duration:value", time_in_seconds)
                .putString("fitness:duration:units", "s")
                .putDouble("fitness:metrics:location:latitude", latitude)
                .putDouble("fitness:metrics:location:longitude", longitude)
                .build();
        ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
                .setActionType("fitness.runs")
                .putObject("fitness:course", object)
                .build();
        ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
                .setPreviewPropertyName("fitness:course")
                .setAction(action)
                .build();

                ShareDialog.show(ShareActivity.this, content);
            }
        });

Body:
Did you logged out somewhere before shareButton clicked?
Check below code.

LoginManager.getInstance().logOut();


问:
How to install caffe in anaconda in Mac OS?
I am trying to use caffe module with OpenCV. I am creating environment using Anaconda. I am not finding this module in Anaconda. Tried conda install caffe, it didn't work.

I am new to OpenCV and Python, please guide or provide reference on how to install caffe.

答: Please see the official install documentation directly on Caffe's site. You need to compile Caffe itself, and then compile the Python wrappers.</p>


问:
LD_PRELOAD does not loaded on systemd
I am trying to inject a SO into a process that starts using systemd init system (using LD_PRELOAD), but it does not loaded into the new process.

I complied a basic SO (unrandom.c):

```<code>int rand(){
    return 42; //the most random number in the universe
}
</code>```

with the command line:

```<code>gcc -shared -fPIC unrandom.c -o unrandom.so
</code>```

I changed the .service file to include:

```<code>Environment="LD_PRELOAD=/tmp/unrandom.so"
</code>```

After starting the service the LD_PRELOAD environment variable is exist in the process, but the SO does not injected

```<code>cat /proc/<PID>/maps
</code>```

Am I missing something?

My machine is RHEL7

答:
Setuid processes restrict usage of LD_PRELOAD (and some other env. variables) due to security reasons.

Loaded library must be specified via name only and be located in one of the directories listed in /etc/ld.so.conf (see e.g. this link). For example on Debian-based systems

```<code>sudo cp library.so /usr/lib/x86_64-linux-gnu
LD_PRELOAD=library.so daemon
</code>```

Another approach is to put full path to library to /etc/ld.so.preload:

```<code>sudo echo path/to/library.so >> /etc/ld.so.preload
</code>```

but then it'll be preloaded to all new processes (which has a high chance of breaking your system if you are not extremely careful).

Title: LD_PRELOAD does not loaded on systemd

Body:
I am trying to inject a SO into a process that starts using systemd init system (using LD_PRELOAD), but it does not loaded into the new process.

I complied a basic SO (unrandom.c):

int rand(){
    return 42; //the most random number in the universe
}

with the command line:

gcc -shared -fPIC unrandom.c -o unrandom.so

I changed the .service file to include:

Environment="LD_PRELOAD=/tmp/unrandom.so"

After starting the service the LD_PRELOAD environment variable is exist in the process, but the SO does not injected

cat /proc/<PID>/maps

Am I missing something?

My machine is RHEL7

Body:
Setuid processes restrict usage of LD_PRELOAD (and some other env. variables) due to security reasons.

Loaded library must be specified via name only and be located in one of the directories listed in /etc/ld.so.conf (see e.g. this link). For example on Debian-based systems

sudo cp library.so /usr/lib/x86_64-linux-gnu
LD_PRELOAD=library.so daemon

Another approach is to put full path to library to /etc/ld.so.preload:

sudo echo path/to/library.so >> /etc/ld.so.preload

but then it'll be preloaded to all new processes (which has a high chance of breaking your system if you are not extremely careful).


问:
unable to compile JNI Program to install rJava Package
I am using Red Hat 5, and unable to install rJava Package

I ran the following command:

```<code>$ R CMD javareconf -e
</code>```

I get the following error:-

trying to compile and link a JNI program detected JNI cpp flags    :

detected JNI linker flags :

gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include

  -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c conftest.c -o conftest.o

conftest.c:1:17: fatal error: jni.h: No such file or directory

compilation terminated.

make: *** [conftest.o] Error 1

Unable to compile a JNI program

java -version is below:-

java version "1.8.0_91"

Java(TM) SE Runtime Environment (build 1.8.0_91-b14)

Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mod

JAVA_HOME = /usr/java/jdk1.8.0_91/jre

Can anyone please help me to compile JNI Program

答:
You need to use JDK instead of JRE. JDK contains libs and headers required for JNI compilation.

In general, you have to reconfigure R and make sure to point to proper Java installation.

Take a look here: http://www.owsiak.org/?p=3671 where you can find quite detailed explanation of all the steps you have to take in order to get R properly working with Java. Explanation was prepared for macOS, but it will work for Linux based systems as well - with little modifications.

Just to summarize:

install JDK

reconfigure R

```<code>sudo R CMD javareconf \
JAVA_HOME=${JAVA_HOME} \
JAVA=${JAVA_HOME/bin/java \
JAVAC=${JAVA_HOME}/bin/javac \
JAVAH=${JAVA_HOME}/bin/javah \
JAR=${JAVA_HOME}/bin/jar \
JAVA_LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/server \
JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux"
</code>```

start R and install packages that require Java

Body:
I am using Red Hat 5, and unable to install rJava Package

I ran the following command:

$ R CMD javareconf -e

I get the following error:-

trying to compile and link a JNI program detected JNI cpp flags    :

detected JNI linker flags :

gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include

  -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c conftest.c -o conftest.o

conftest.c:1:17: fatal error: jni.h: No such file or directory

compilation terminated.

make: *** [conftest.o] Error 1

Unable to compile a JNI program

java -version is below:-

java version "1.8.0_91"

Java(TM) SE Runtime Environment (build 1.8.0_91-b14)

Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mod

JAVA_HOME = /usr/java/jdk1.8.0_91/jre

Can anyone please help me to compile JNI Program

Body:
You need to use JDK instead of JRE. JDK contains libs and headers required for JNI compilation.

In general, you have to reconfigure R and make sure to point to proper Java installation.

Take a look here: http://www.owsiak.org/?p=3671 where you can find quite detailed explanation of all the steps you have to take in order to get R properly working with Java. Explanation was prepared for macOS, but it will work for Linux based systems as well - with little modifications.

Just to summarize:

install JDK

reconfigure R

sudo R CMD javareconf \
JAVA_HOME=${JAVA_HOME} \
JAVA=${JAVA_HOME/bin/java \
JAVAC=${JAVA_HOME}/bin/javac \
JAVAH=${JAVA_HOME}/bin/javah \
JAR=${JAVA_HOME}/bin/jar \
JAVA_LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/server \
JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux"

start R and install packages that require Java


答:
Define a height, set white-space to nowrap and overflow: hidden

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  height: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div></code>```

Title: How do I set text-overflow to ellipsis in CSS grid layout?

Body:
Define a height, set white-space to nowrap and overflow: hidden

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  height: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div>


问:
Call Child class method from Parent class method
Consider the following case

```<code>class A
{
    X()
    {
        //some code
        Y();
    }
}

class B extends A
{
    Y(){ //some code }
}
</code>```

If I create an object of the class B, and i try to use function X as it is extended from A, is it possible that the function X can access the function Y of the calling object of class B.

答:
only if A have a method with the same signature (or a super class has one), otherwise it can't find/use a method that is not defined in his context.

This could be done

with an implementation of the method in A

by using an abstract method in A(see ΦXocę 웃 Пepeúpa ツ answer).

The first solution is not always the best, as you could have a method that do nothing in A like :

```<code>class A{
    void Y(){}
}
</code>```

Note : if you have Y() in both class, the polymorphism assure you that an instance of B will use his own implementation.

The second solution can be problematic if you want to be able to create instance of A as it will be abstract.

Body:
Consider the following case

class A
{
    X()
    {
        //some code
        Y();
    }
}

class B extends A
{
    Y(){ //some code }
}

If I create an object of the class B, and i try to use function X as it is extended from A, is it possible that the function X can access the function Y of the calling object of class B.

Body:
only if A have a method with the same signature (or a super class has one), otherwise it can't find/use a method that is not defined in his context.

This could be done

with an implementation of the method in A

by using an abstract method in A(see ΦXocę 웃 Пepeúpa ツ answer).

The first solution is not always the best, as you could have a method that do nothing in A like :

class A{
    void Y(){}
}

Note : if you have Y() in both class, the polymorphism assure you that an instance of B will use his own implementation.

The second solution can be problematic if you want to be able to create instance of A as it will be abstract.


问:
Unity - Button Event to switch a value
I have followed this tutorial to create a simple clock: http://catlikecoding.com/unity/tutorials/clock/

Everything works perfectly fine but the tutorial has an internal switch for digital and analog display. Now I would like to add a simple button "ingame" to switch that bool to true/false.

How can I achieve that ?
thanks!

答:
Add a method to your script to change the value of analog.

```<code>public void OnClick()
{
   analog = !analog;
}
</code>```

Create a button in your scene and make sure it's under a canvas, select the button, then drag your script into the OnClick() section. Select your OnClick() method from the dropdown list.

You an add multiple on click events from here, and this method allows you easily see what methods are attached to your buttons without looking at your code, which can get complex over time.

Title: Unity - Button Event to switch a value

Body:
Add a method to your script to change the value of analog.

public void OnClick()
{
   analog = !analog;
}

Create a button in your scene and make sure it's under a canvas, select the button, then drag your script into the OnClick() section. Select your OnClick() method from the dropdown list.

You an add multiple on click events from here, and this method allows you easily see what methods are attached to your buttons without looking at your code, which can get complex over time.


问:
How to directly detect the window position?
I'm coding in c++ with Qt creator. I can get all windows on the screen but I would like to detect their movement directly. Is there any way to detect the movement thanks to a signal emitted by the window ?</p>

答:
You can try creating a QWindow from the target window and then wrap it in a QWidget using QWidget::createWindowContainer().

You can have a look at this QTBUG thread : https://bugreports.qt.io/browse/QTBUG-40320

It needs some effort to make it work properly. The captured window doesn't keep its initial dimensions, and releasing the window behave weirdly. Read the last QTBUG comments to find an improvement.

I added an event filter to this code to capture the window position in real time. But that might be unsatisfying.

```<code>class EventFilter : public QObject
{
   Q_OBJECT

public:
   EventFilter(){}
   virtual ~EventFilter(){}

protected:
     bool eventFilter(QObject *obj, QEvent *event);
 } ;

bool EventFilter::eventFilter(QObject *obj, QEvent *event)
{
   qDebug() << event->type() ;

    if (event->type() == QEvent::Move) {
        QMoveEvent *moveEvent = static_cast<QMoveEvent *>(event);
        qDebug() << "position" << moveEvent->pos() ;
        return true;
    } else {
        // standard event processing
        return QObject::eventFilter(obj, event);
    }
}
</code>```

I removed part 3 from the QTBUG snippet and installed the event handler on the inner widget. You can also remove the timers.

```<code>// From https://bugreports.qt.io/browse/QTBUG-40320
int main(int argc, char *argv[])
{
    // Windows: Find HWND by window title
    WId id = (WId)FindWindow(NULL, L"Calculator");
    if (!id)
        return -1;

    QApplication a(argc, argv);
    // Optional
    QTimer t;
    t.start(2500);

    // Part 1
    QWindow* window = QWindow::fromWinId(id);
    window->show();
    window->requestActivate();

    // Optional
    QObject::connect(&t, &QTimer::timeout, [=]
    {
        qDebug() << "=== Inner QWindow ===";
        qDebug() << "Geometry:" << window->geometry();
        qDebug() << "Active?:" << window->isActive();
        qDebug() << "Flags:" << window->flags();
    });

    // Part 2
    QWidget* widget = QWidget::createWindowContainer(window);
    widget->show();

    // Optional
    QObject::connect(&t, &QTimer::timeout, [=]
    {
        qDebug() << "=== Outer QWidget ===";
        qDebug() << "Geometry:" << widget->geometry();
        qDebug() << "Active?" << widget->isActiveWindow();
        qDebug() << "Flags:" << widget->windowFlags();
    });

    // Realtime position
    EventFilter filter ;
    widget->installEventFilter( &filter ) ;

    return a.exec();
}
</code>```

Output:

```<code>=== Inner QWindow ===
Geometry: QRect(0,0 640x480)
Active?: true
Flags: QFlags<Qt::WindowType>(ForeignWindow)
=== Outer QWidget ===
Geometry: QRect(2489,29 640x480)
Active? true
Flags: QFlags<Qt::WindowType>(Window|WindowTitleHint|WindowSystemMenuHint|WindowMinMaxButtonsHint|WindowCloseButtonHint)

QEvent::Type(Move)
position QPoint(2484,29)
QEvent::Type(Move)
position QPoint(2481,30)
QEvent::Type(Move)
position QPoint(2478,31)
QEvent::Type(Move)
position QPoint(2474,31)
</code>```

See also http://blog.qt.io/blog/2013/02/19/introducing-qwidgetcreatewindowcontainer/

Body:
You can try creating a QWindow from the target window and then wrap it in a QWidget using QWidget::createWindowContainer().

You can have a look at this QTBUG thread : https://bugreports.qt.io/browse/QTBUG-40320

It needs some effort to make it work properly. The captured window doesn't keep its initial dimensions, and releasing the window behave weirdly. Read the last QTBUG comments to find an improvement.

I added an event filter to this code to capture the window position in real time. But that might be unsatisfying.

class EventFilter : public QObject
{
   Q_OBJECT

public:
   EventFilter(){}
   virtual ~EventFilter(){}

protected:
     bool eventFilter(QObject *obj, QEvent *event);
 } ;

bool EventFilter::eventFilter(QObject *obj, QEvent *event)
{
   qDebug() << event->type() ;

    if (event->type() == QEvent::Move) {
        QMoveEvent *moveEvent = static_cast<QMoveEvent *>(event);
        qDebug() << "position" << moveEvent->pos() ;
        return true;
    } else {
        // standard event processing
        return QObject::eventFilter(obj, event);
    }
}

I removed part 3 from the QTBUG snippet and installed the event handler on the inner widget. You can also remove the timers.

// From https://bugreports.qt.io/browse/QTBUG-40320
int main(int argc, char *argv[])
{
    // Windows: Find HWND by window title
    WId id = (WId)FindWindow(NULL, L"Calculator");
    if (!id)
        return -1;

    QApplication a(argc, argv);
    // Optional
    QTimer t;
    t.start(2500);

    // Part 1
    QWindow* window = QWindow::fromWinId(id);
    window->show();
    window->requestActivate();

    // Optional
    QObject::connect(&t, &QTimer::timeout, [=]
    {
        qDebug() << "=== Inner QWindow ===";
        qDebug() << "Geometry:" << window->geometry();
        qDebug() << "Active?:" << window->isActive();
        qDebug() << "Flags:" << window->flags();
    });

    // Part 2
    QWidget* widget = QWidget::createWindowContainer(window);
    widget->show();

    // Optional
    QObject::connect(&t, &QTimer::timeout, [=]
    {
        qDebug() << "=== Outer QWidget ===";
        qDebug() << "Geometry:" << widget->geometry();
        qDebug() << "Active?" << widget->isActiveWindow();
        qDebug() << "Flags:" << widget->windowFlags();
    });

    // Realtime position
    EventFilter filter ;
    widget->installEventFilter( &filter ) ;

    return a.exec();
}

Output:

=== Inner QWindow ===
Geometry: QRect(0,0 640x480)
Active?: true
Flags: QFlags<Qt::WindowType>(ForeignWindow)
=== Outer QWidget ===
Geometry: QRect(2489,29 640x480)
Active? true
Flags: QFlags<Qt::WindowType>(Window|WindowTitleHint|WindowSystemMenuHint|WindowMinMaxButtonsHint|WindowCloseButtonHint)

QEvent::Type(Move)
position QPoint(2484,29)
QEvent::Type(Move)
position QPoint(2481,30)
QEvent::Type(Move)
position QPoint(2478,31)
QEvent::Type(Move)
position QPoint(2474,31)

See also http://blog.qt.io/blog/2013/02/19/introducing-qwidgetcreatewindowcontainer/


问:
Linqpad returns very elaborate SQL query when converting from LINQ
I wrote LINQ query using LinqPad to return users that should retrieve an invitation for a questionnaire. The query runs fine and returns the correct results.

However I need this query in SQL form. When I click on the SQL button in LinqPad it returns the SQL form but with a separate select statement for each individual record. Leaving me with an SQL query of 2000 lines.

This is my LINQ query

```<code>var result2 = AI_Conversations
.Where(f => f.End_DateTime.Value.Date == DateTime.Now.AddDays(-1).Date).GroupBy(f => f.Email)
.Where(f => f.GroupBy(z => z.Chatbot_Name).Count() == 1)
.ToList().Select(f =>
new
{
    Name = f.LastOrDefault().Disp_Name,
    f.LastOrDefault().Email,
    Reference = f.LastOrDefault().Report_ConvNumber
});

result2.Dump();
</code>```

Which in SQL returns the following

```<code>-- Region Parameters
DECLARE @p0 DateTime = '2017-06-07 00:00:00.000'
DECLARE @p1 Int = 1
-- EndRegion
SELECT [t1].[Email] AS [Key]
FROM (
    SELECT [t0].[Email]
    FROM [AI_Conversations] AS [t0]
    WHERE CONVERT(DATE, [t0].[End_DateTime]) = @p0
    GROUP BY [t0].[Email]
    ) AS [t1]
WHERE ((
    SELECT COUNT(*)
    FROM (
        SELECT NULL AS [EMPTY]
        FROM [AI_Conversations] AS [t2]
        WHERE ((([t1].[Email] IS NULL) AND ([t2].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t2].[Email] IS NOT NULL) AND ([t1].[Email] = [t2].[Email]))) AND (CONVERT(DATE, [t2].[End_DateTime]) = @p0)
        GROUP BY [t2].[Chatbot_Name]
        ) AS [t3]
    )) = @p1
GO
</code>```

And after the above statement another select statement is appended for each record returned by the linq query. (>200 times)

```<code>-- Region Parameters
DECLARE @p0 DateTime = '2017-06-07 00:00:00.000'
DECLARE @x1 VarChar(1000) = '(CENSORED)'
-- EndRegion
SELECT [t0].[rownames] AS [Rownames], [t0].[Report_ConvNumber], [t0].[Email], [t0].[AD_Num], [t0].[Disp_Name], [t0].[Start_DateTime], [t0].[End_DateTime], [t0].[NumOfMessages], [t0].[Duration], [t0].[Chatbot_Name], [t0].[feedback_score] AS [Feedback_score]
FROM [AI_Conversations] AS [t0]
WHERE (((@x1 IS NULL) AND ([t0].[Email] IS NULL)) OR ((@x1 IS NOT NULL) AND ([t0].[Email] IS NOT NULL) AND (@x1 = [t0].[Email]))) AND (CONVERT(DATE, [t0].[End_DateTime]) = @p0)
GO
</code>```

I would expect the SQL query returned to look similar to this

```<code>-- Region Parameters
DECLARE @p0 DateTime = DATEADD(dd, -1, cast(Getdate() as date))
DECLARE @p1 Int = 1
-- EndRegion
SELECT [t1].[Email],
       [t1].[Disp_Name] AS Name,
       [t1].[Report_ConvNumber] AS Reference
FROM (
    SELECT [t0].[Email],
           [t0].[Disp_Name],
           [t0].[Report_ConvNumber]
    FROM [AI_Conversations] AS [t0]
    WHERE CONVERT(DATE, [t0].[Start_DateTime]) = @p0
    GROUP BY [t0].[Email],
             [t0].[Disp_Name],
             [t0].[Report_ConvNumber]
    ) AS [t1]
WHERE ((
    SELECT COUNT(*)
    FROM (
        SELECT NULL AS [EMPTY]
        FROM [AI_Conversations] AS [t2]
        WHERE ((([t1].[Email] IS NULL) AND ([t2].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t2].[Email] IS NOT NULL) AND ([t1].[Email] = [t2].[Email]))) AND (CONVERT(DATE, [t2].[Start_DateTime]) = @p0)
        GROUP BY [t2].[Chatbot_Name]
        ) AS [t3]
    )) = @p1
GO
</code>```

Is anyone able to tell me why LinqPad is returning such a verbose SQL query?
How can I adjust the LINQ Query to return a 'simple' SQL query like my provided expectations?

It's an MSSQL 2014 server using Linqpad 5 if that matters

Edit:

After removing the .ToList() as Sgtmoore suggested I got the following SQL output which is more or less to my expectations.

```<code>    -- Region Parameters
DECLARE @p0 DateTime = '2017-05-04 00:00:00.000'
DECLARE @p1 Int = 1
-- EndRegion
SELECT (
    SELECT [t5].[AD_Num]
    FROM (
        SELECT TOP (1) [t4].[AD_Num]
        FROM [AI_Conversations] AS [t4]
        WHERE ((([t1].[Email] IS NULL) AND ([t4].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t4].[Email] IS NOT NULL) AND ([t1].[Email] = [t4].[Email]))) AND (CONVERT(DATE, [t4].[End_DateTime]) = @p0)
        ) AS [t5]
    ) AS [Name], (
    SELECT [t7].[Email]
    FROM (
        SELECT TOP (1) [t6].[Email]
        FROM [AI_Conversations] AS [t6]
        WHERE ((([t1].[Email] IS NULL) AND ([t6].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t6].[Email] IS NOT NULL) AND ([t1].[Email] = [t6].[Email]))) AND (CONVERT(DATE, [t6].[End_DateTime]) = @p0)
        ) AS [t7]
    ) AS [Email], (
    SELECT [t9].[Report_ConvNumber]
    FROM (
        SELECT TOP (1) [t8].[Report_ConvNumber]
        FROM [AI_Conversations] AS [t8]
        WHERE ((([t1].[Email] IS NULL) AND ([t8].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t8].[Email] IS NOT NULL) AND ([t1].[Email] = [t8].[Email]))) AND (CONVERT(DATE, [t8].[End_DateTime]) = @p0)
        ) AS [t9]
    ) AS [Reference]
FROM (
    SELECT [t0].[Email]
    FROM [AI_Conversations] AS [t0]
    WHERE CONVERT(DATE, [t0].[End_DateTime]) = @p0
    GROUP BY [t0].[Email]
    ) AS [t1]
WHERE ((
    SELECT COUNT(*)
    FROM (
        SELECT NULL AS [EMPTY]
        FROM [AI_Conversations] AS [t2]
        WHERE ((([t1].[Email] IS NULL) AND ([t2].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t2].[Email] IS NOT NULL) AND ([t1].[Email] = [t2].[Email]))) AND (CONVERT(DATE, [t2].[End_DateTime]) = @p0)
        GROUP BY [t2].[Chatbot_Name]
        ) AS [t3]
    )) = @p1
</code>```

答:
I think the main issue is the .ToList() in the middle is the query. However if you remove that, the query will fail as Linq2Sql does not support LastOrDefault.

So I think you would need to use .FirstOrDefault() and if necessary reverse the sort order.

This produces simpler TSQL, but still isn't anything like your expected output. From that, it would look like you want to group by Email, Reference and Report_ConvNumber, ie something like

```<code>var result2 = AI_Conversations
  .Where(f => f.End_DateTime.Value.Date == DateTime.Now.AddDays(-1).Date)
  .GroupBy(f => new {f.Email, f.Reference, f.Report_ConvNumber)
  .Where(f => f.GroupBy(z => z.Chatbot_Name).Count() == 1)
  .Select(f => new
     {
     Name = f.Key.Disp_Name,
     f.Key.Email,
     Reference = f.KeyReport_ConvNumber
   });

 result2.Dump();
</code>```

Body:
I wrote LINQ query using LinqPad to return users that should retrieve an invitation for a questionnaire. The query runs fine and returns the correct results.

However I need this query in SQL form. When I click on the SQL button in LinqPad it returns the SQL form but with a separate select statement for each individual record. Leaving me with an SQL query of 2000 lines.

This is my LINQ query

var result2 = AI_Conversations
.Where(f => f.End_DateTime.Value.Date == DateTime.Now.AddDays(-1).Date).GroupBy(f => f.Email)
.Where(f => f.GroupBy(z => z.Chatbot_Name).Count() == 1)
.ToList().Select(f =>
new
{
    Name = f.LastOrDefault().Disp_Name,
    f.LastOrDefault().Email,
    Reference = f.LastOrDefault().Report_ConvNumber
});

result2.Dump();

Which in SQL returns the following

-- Region Parameters
DECLARE @p0 DateTime = '2017-06-07 00:00:00.000'
DECLARE @p1 Int = 1
-- EndRegion
SELECT [t1].[Email] AS [Key]
FROM (
    SELECT [t0].[Email]
    FROM [AI_Conversations] AS [t0]
    WHERE CONVERT(DATE, [t0].[End_DateTime]) = @p0
    GROUP BY [t0].[Email]
    ) AS [t1]
WHERE ((
    SELECT COUNT(*)
    FROM (
        SELECT NULL AS [EMPTY]
        FROM [AI_Conversations] AS [t2]
        WHERE ((([t1].[Email] IS NULL) AND ([t2].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t2].[Email] IS NOT NULL) AND ([t1].[Email] = [t2].[Email]))) AND (CONVERT(DATE, [t2].[End_DateTime]) = @p0)
        GROUP BY [t2].[Chatbot_Name]
        ) AS [t3]
    )) = @p1
GO

And after the above statement another select statement is appended for each record returned by the linq query. (>200 times)

-- Region Parameters
DECLARE @p0 DateTime = '2017-06-07 00:00:00.000'
DECLARE @x1 VarChar(1000) = '(CENSORED)'
-- EndRegion
SELECT [t0].[rownames] AS [Rownames], [t0].[Report_ConvNumber], [t0].[Email], [t0].[AD_Num], [t0].[Disp_Name], [t0].[Start_DateTime], [t0].[End_DateTime], [t0].[NumOfMessages], [t0].[Duration], [t0].[Chatbot_Name], [t0].[feedback_score] AS [Feedback_score]
FROM [AI_Conversations] AS [t0]
WHERE (((@x1 IS NULL) AND ([t0].[Email] IS NULL)) OR ((@x1 IS NOT NULL) AND ([t0].[Email] IS NOT NULL) AND (@x1 = [t0].[Email]))) AND (CONVERT(DATE, [t0].[End_DateTime]) = @p0)
GO

I would expect the SQL query returned to look similar to this

-- Region Parameters
DECLARE @p0 DateTime = DATEADD(dd, -1, cast(Getdate() as date))
DECLARE @p1 Int = 1
-- EndRegion
SELECT [t1].[Email],
       [t1].[Disp_Name] AS Name,
       [t1].[Report_ConvNumber] AS Reference
FROM (
    SELECT [t0].[Email],
           [t0].[Disp_Name],
           [t0].[Report_ConvNumber]
    FROM [AI_Conversations] AS [t0]
    WHERE CONVERT(DATE, [t0].[Start_DateTime]) = @p0
    GROUP BY [t0].[Email],
             [t0].[Disp_Name],
             [t0].[Report_ConvNumber]
    ) AS [t1]
WHERE ((
    SELECT COUNT(*)
    FROM (
        SELECT NULL AS [EMPTY]
        FROM [AI_Conversations] AS [t2]
        WHERE ((([t1].[Email] IS NULL) AND ([t2].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t2].[Email] IS NOT NULL) AND ([t1].[Email] = [t2].[Email]))) AND (CONVERT(DATE, [t2].[Start_DateTime]) = @p0)
        GROUP BY [t2].[Chatbot_Name]
        ) AS [t3]
    )) = @p1
GO

Is anyone able to tell me why LinqPad is returning such a verbose SQL query?
How can I adjust the LINQ Query to return a 'simple' SQL query like my provided expectations?

It's an MSSQL 2014 server using Linqpad 5 if that matters

Edit:

After removing the .ToList() as Sgtmoore suggested I got the following SQL output which is more or less to my expectations.

    -- Region Parameters
DECLARE @p0 DateTime = '2017-05-04 00:00:00.000'
DECLARE @p1 Int = 1
-- EndRegion
SELECT (
    SELECT [t5].[AD_Num]
    FROM (
        SELECT TOP (1) [t4].[AD_Num]
        FROM [AI_Conversations] AS [t4]
        WHERE ((([t1].[Email] IS NULL) AND ([t4].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t4].[Email] IS NOT NULL) AND ([t1].[Email] = [t4].[Email]))) AND (CONVERT(DATE, [t4].[End_DateTime]) = @p0)
        ) AS [t5]
    ) AS [Name], (
    SELECT [t7].[Email]
    FROM (
        SELECT TOP (1) [t6].[Email]
        FROM [AI_Conversations] AS [t6]
        WHERE ((([t1].[Email] IS NULL) AND ([t6].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t6].[Email] IS NOT NULL) AND ([t1].[Email] = [t6].[Email]))) AND (CONVERT(DATE, [t6].[End_DateTime]) = @p0)
        ) AS [t7]
    ) AS [Email], (
    SELECT [t9].[Report_ConvNumber]
    FROM (
        SELECT TOP (1) [t8].[Report_ConvNumber]
        FROM [AI_Conversations] AS [t8]
        WHERE ((([t1].[Email] IS NULL) AND ([t8].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t8].[Email] IS NOT NULL) AND ([t1].[Email] = [t8].[Email]))) AND (CONVERT(DATE, [t8].[End_DateTime]) = @p0)
        ) AS [t9]
    ) AS [Reference]
FROM (
    SELECT [t0].[Email]
    FROM [AI_Conversations] AS [t0]
    WHERE CONVERT(DATE, [t0].[End_DateTime]) = @p0
    GROUP BY [t0].[Email]
    ) AS [t1]
WHERE ((
    SELECT COUNT(*)
    FROM (
        SELECT NULL AS [EMPTY]
        FROM [AI_Conversations] AS [t2]
        WHERE ((([t1].[Email] IS NULL) AND ([t2].[Email] IS NULL)) OR (([t1].[Email] IS NOT NULL) AND ([t2].[Email] IS NOT NULL) AND ([t1].[Email] = [t2].[Email]))) AND (CONVERT(DATE, [t2].[End_DateTime]) = @p0)
        GROUP BY [t2].[Chatbot_Name]
        ) AS [t3]
    )) = @p1

Body:
I think the main issue is the .ToList() in the middle is the query. However if you remove that, the query will fail as Linq2Sql does not support LastOrDefault.

So I think you would need to use .FirstOrDefault() and if necessary reverse the sort order.

This produces simpler TSQL, but still isn't anything like your expected output. From that, it would look like you want to group by Email, Reference and Report_ConvNumber, ie something like

var result2 = AI_Conversations
  .Where(f => f.End_DateTime.Value.Date == DateTime.Now.AddDays(-1).Date)
  .GroupBy(f => new {f.Email, f.Reference, f.Report_ConvNumber)
  .Where(f => f.GroupBy(z => z.Chatbot_Name).Count() == 1)
  .Select(f => new
     {
     Name = f.Key.Disp_Name,
     f.Key.Email,
     Reference = f.KeyReport_ConvNumber
   });

 result2.Dump();