问:
Javascript convert objects to array
I have an array of arrays of objects like this:

```<code>var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]
</code>```

And I want to convert it to this:

```<code>[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]
</code>```

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...

答:
Here is another way to achieve this. Get values like values=Object.values(array) and iterate over these values using simple for loop.

var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]
var outPut =[]
var values=Object.values(array);
//console.log(values);
for(var i=0;i<values.length;i++){
 for(var j=0;j<values[i].length;j++){
   //console.log(values[i][j]);
   outPut.push(Object.values(values[i][j]));

 }
}
console.log(outPut);```

Title: Javascript convert objects to array

Body:
I have an array of arrays of objects like this:

var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]

And I want to convert it to this:

[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...


来源: stackexchange

问:
list with matrices times always the same vector
i am working with consumer price index CPI and in order to calculate it i have to multiply the index matrix with the corresponding weights:

```<code>grossCPI77_10 <- grossIND1977 %*% weights1910/100
grossCPI82_10 <- grossIND1982 %*% weights1910/100
</code>```

of course i would rather like to have a code like the one beyond:

```<code>grossIND1982 <- replicate(20, cbind(1:61))
grossIND1993 <- replicate(20, cbind(1:61))
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, weights1910_sc)
</code>```

the problem is that it gives me a 1200x20 matrix. i expected a normal matrix (61x20) vector (20x1) multiplication which should result in a 20x1 vector? could you explain me what i am doing wrong? thanks

答:
part of your problem is that you don't have matrices but 3D arrays, with one singleton dimension. The other issue is that mapply likes to try and combine the results into a matrix, and also that constant arguments should be passed via MoreArgs. But actually, this is more a case for lapply.</p>

```<code>grossIND1982 <- replicate(20, cbind(1:61))[,1,]
grossIND1993 <- replicate(20, cbind(1:61))[,1,]
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, MoreArgs=list(e2 = weights1910_sc), SIMPLIFY = FALSE)

totalCPI <- lapply(grossIND_list, "*",  e2 = weights1910_sc)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am working with consumer price index CPI and in order to calculate it i have to multiply the index matrix with the corresponding weights:

grossCPI77_10 <- grossIND1977 %*% weights1910/100
grossCPI82_10 <- grossIND1982 %*% weights1910/100

of course i would rather like to have a code like the one beyond:

grossIND1982 <- replicate(20, cbind(1:61))
grossIND1993 <- replicate(20, cbind(1:61))
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, weights1910_sc)

the problem is that it gives me a 1200x20 matrix. i expected a normal matrix (61x20) vector (20x1) multiplication which should result in a 20x1 vector? could you explain me what i am doing wrong? thanks

Body:
part of your problem is that you don't have matrices but 3D arrays, with one singleton dimension. The other issue is that mapply likes to try and combine the results into a matrix, and also that constant arguments should be passed via MoreArgs. But actually, this is more a case for lapply.

grossIND1982 <- replicate(20, cbind(1:61))[,1,]
grossIND1993 <- replicate(20, cbind(1:61))[,1,]
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, MoreArgs=list(e2 = weights1910_sc), SIMPLIFY = FALSE)

totalCPI <- lapply(grossIND_list, "*",  e2 = weights1910_sc)


问:
Atom search wildcard Fuzzy Find Files
Is there away to search for files using wildcard with the Fuzzy Find Files in Atom (cmd-t cmd-p)

e.g.
*query.js

shows
jquery.js

答:
Press Ctrl+Fand then Ctrl+Alt+/ for regex search

https://discuss.atom.io/t/search-wildcards-for-find-replace/16928

Title: Atom search wildcard Fuzzy Find Files


问:
Different sha256 between nix-hash and nix-prefetch-url
When I want to precompute the sha256 of a downloaded file foo.txt, the output of nix-hash on the manually downloaded file is different from the one that is printed by nix-prefetch-url.

How can I compute the same hash with nix-hash?

答:
The standard format of nix-hash is different from the one that nix-prefetch-url uses.

To get the same output from the manually downloaded file as nix-prefetch-url would give, run nix-hash like this:

```<code>nix-hash --type sha256 --flat --base32 <file>
</code>```

Body:
The standard format of nix-hash is different from the one that nix-prefetch-url uses.

To get the same output from the manually downloaded file as nix-prefetch-url would give, run nix-hash like this:

nix-hash --type sha256 --flat --base32 <file>


问:
React - Event bubbling
I am using react. I am not quite how should I write a event handling so when I click on a, I can alert data-href. Right now if I click on div or img, it will trigger an event, but since the target is actually not a it will alert null, which is not what I want.

```<code>test(e){alert(e.target.getAttribute('data-href'))}
<div>
  <ui>
    <li >
      <a data-href = 'http://cnn.com'  onClick = {e = > this.test(e)>
          <div>
            <img src = 'someimage.jpg'}>
            hi there
          </div>
      </a>
    <li>
  </ui>
</div>
</code>```

edit:

Something like this
conversationList() & selectConversation() is what I am talking about here~

```<code>import React from 'react';
import { connect, Provider } from 'react-redux';
import fetch from 'isomorphic-fetch';
import * as actions from './actions/index';

import io from 'socket.io-client';

class Chat extends React.Component{
    constructor(props){
        super(props);
        this.state = {recipientId: '', messageBuffer:'asdfadsfasdf'};
        this.userList = this.userList.bind(this);
        this.changeRecipient = this.changeRecipient.bind(this);
        this.insertText = this.insertText.bind(this);
    }
    componentWillMount(){
        this.props.loadConversationsSocket();
        this.props.loadConversations();
        this.props.loadRecipients();
    }

    participantsNames(participants){
        console.log('in par ');
        console.log(participants);
        return participants.map(participant => (<div key= {participant._id}>{participant.name}</div>));
    }

    selectConversation(e){
        e.preventDefault();
        console.log(this.tagName);
        let data = this.getAttribute('data-href');
        alert(data);
    }

    conversationList(){
        if(!(this.props.conversations.length === 0)){
            console.log('in conversation if');

            return this.props.conversations.map(conversation =>(<li key = {conversation.conversation._id} >
                <a data-href = {'http://localhost:8000/messaages/'+conversation.conversation._id} onClick = {(e)=>this.selectConversation(e)}>
                    <div>
                        participants: {this.participantsNames(conversation.conversation.participants)}
                    </div>
                    <div>
                        {conversation.message[0].auther}
                        {conversation.message[0].body}
                    </div>
                </a>

            </li>))
        }
    }

    render(){

        return (
            <div>
                <ul>
                    {this.conversationList()}
                </ul>
            </div>)
    }

}

function mapStateToProps(state) {
    return { recipients: state.recipients, conversations: state.conversations};
}

export default connect(mapStateToProps, actions)(Chat);
</code>```

答:
Your onClick handler is attached to the img, not to a. This is the first  problem.

Then you should update your code to query event.currentTarget.

event.currentTarget - identifies the current target for the event, as the event traverses
  the DOM. It always refers to the element to which the event handler
  has been attached, as opposed to event.target which identifies the
  element on which the event occurred.

You should write your event handler like this:

```<code>class Hello extends React.Component {

  test(e){
   alert(e.currentTarget.getAttribute('data-href'))
  }

  render() {
    return (
        <div>
          <a onClick={this.test} data-href="foo">
            <img src="https://vignette.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437" />
            <div>clickMe</div>
          </a>
        </div>
    );
  }
}
</code>```

I would suggest also reading this article about handling events.

Title: React - Event bubbling

Body:
I am using react. I am not quite how should I write a event handling so when I click on a, I can alert data-href. Right now if I click on div or img, it will trigger an event, but since the target is actually not a it will alert null, which is not what I want.

test(e){alert(e.target.getAttribute('data-href'))}

  <ui>

       this.test(e)>

            hi there

  </ui>

edit:

Something like this
conversationList() & selectConversation() is what I am talking about here~

import React from 'react';
import { connect, Provider } from 'react-redux';
import fetch from 'isomorphic-fetch';
import * as actions from './actions/index';

import io from 'socket.io-client';

class Chat extends React.Component{
    constructor(props){
        super(props);
        this.state = {recipientId: '', messageBuffer:'asdfadsfasdf'};
        this.userList = this.userList.bind(this);
        this.changeRecipient = this.changeRecipient.bind(this);
        this.insertText = this.insertText.bind(this);
    }
    componentWillMount(){
        this.props.loadConversationsSocket();
        this.props.loadConversations();
        this.props.loadRecipients();
    }

    participantsNames(participants){
        console.log('in par ');
        console.log(participants);
        return participants.map(participant => (
{participant.name}
));
    }

    selectConversation(e){
        e.preventDefault();
        console.log(this.tagName);
        let data = this.getAttribute('data-href');
        alert(data);
    }

    conversationList(){
        if(!(this.props.conversations.length === 0)){
            console.log('in conversation if');

            return this.props.conversations.map(conversation =>(

                this.selectConversation(e)}>

                        participants: {this.participantsNames(conversation.conversation.participants)}

                        {conversation.message[0].auther}
                        {conversation.message[0].body}

))
        }
    }

    render(){

        return (

                    {this.conversationList()}

)
    }

}

function mapStateToProps(state) {
    return { recipients: state.recipients, conversations: state.conversations};
}

export default connect(mapStateToProps, actions)(Chat);

Body:
Your onClick handler is attached to the img, not to a. This is the first  problem.

Then you should update your code to query event.currentTarget.

event.currentTarget - identifies the current target for the event, as the event traverses
  the DOM. It always refers to the element to which the event handler
  has been attached, as opposed to event.target which identifies the
  element on which the event occurred.

You should write your event handler like this:

class Hello extends React.Component {

  test(e){
   alert(e.currentTarget.getAttribute('data-href'))
  }

  render() {
    return (
        <div>
          <a onClick={this.test} data-href="foo">
            <img src="https://vignette.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437" />
            <div>clickMe</div>
          </a>
        </div>
    );
  }
}

I would suggest also reading this article about handling events.


问:
Exception: Parameter 'index' must be a int
I'm trying to insert a row in a MySQL database using PDO, and I'm using parameter binding, but I'm getting a stranger error. The important functions are:

```<code>private static function getConnection() : \Pdo
{
    $con = new \PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'myuser', 'mypassword');
    return $con;
}

public static function runBool(string $query, ?array $bind = []) : bool
{
    return self::getConnection()
        ->prepare($query)
        ->execute($bind);
}
</code>```

As you can see, getConnection() is only returning a connection (and it's working fine), the problem is with the function runBool() which is throwing an error on the ->execute($bind); line:

Exception: Parameter 'index' must be a int

For example, my $query is

INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)

And my $bind is

```<code>array(8) {
    ["company_id"]=> int(1)
    ["name"]=> string(3) "John Doe"
    ["phone"]=> string(11) "123456789"
    ["cpf"]=> string(0) ""
    ["rg"]=> string(0) ""
    ["city_id"]=> int(79)
    ["address"]=> string(0) ""
    ["obs"]=> string(0) ""
}
</code>```

I've already tryed to foreach $bind and to use bindParam() or bindValue() individually, and then run execute but I get the same error on the execute().
I've already included : before each key of the array and removed it (following this comment), but nothing changes.
I've already searched a lot on Google but nobody seems to have the same type of trouble.

Info:

PHP 7.1.12

Ubuntu 16.04.03

MySQL 5.7.20

Vagrant 2.0.0

Every help is appreciated.

---------------- EDIT ----------------

As asked, I've checked my namespaces, but I'm using \Pdo, so I think it's the native PHP PDO class. Here's the var_dump of self::getConnection()->prepare($query):

object(PDOStatement)#90 (1) { ["queryString"]=> string(149) "INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)" }

And here's my table:

```<code>CREATE TABLE `client` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(50) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `city_id` int(10) UNSIGNED NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `cpf` varchar(14) DEFAULT NULL,
  `rg` varchar(15) DEFAULT NULL,
  `obs` varchar(100) DEFAULT NULL,
  `company_id` int(10) UNSIGNED NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `client`
  ADD PRIMARY KEY (`id`),
  ADD KEY `city_id` (`city_id`),
  ADD KEY `company_id` (`company_id`);
ALTER TABLE `client` ADD FULLTEXT KEY `search` (`name`,`phone`,`address`,`cpf`,`rg`,`obs`);
ALTER TABLE `client` ADD FULLTEXT KEY `search_basic` (`name`);

ALTER TABLE `client`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=613;

ALTER TABLE `client`
  ADD CONSTRAINT `client-city_id` FOREIGN KEY (`city_id`) REFERENCES `city` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  ADD CONSTRAINT `client-company_id` FOREIGN KEY (`company_id`) REFERENCES     `company` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
</code>```

答:
First check what PDO are u using, check namespaces, because error that u get it's not a PDO error, it is a Phalcon result set error, here is a git: https://github.com/phalcon/cphalcon/blob/master/ext/phalcon/mvc/model/resultset.zep.c#L366

Phalcon try build a result_set.

Can you provide var_dump of self::getConnection()->prepare($query); before executing.

And provide DDL of your table.

Body:
I'm trying to insert a row in a MySQL database using PDO, and I'm using parameter binding, but I'm getting a stranger error. The important functions are:

private static function getConnection() : \Pdo
{
    $con = new \PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'myuser', 'mypassword');
    return $con;
}

public static function runBool(string $query, ?array $bind = []) : bool
{
    return self::getConnection()
        ->prepare($query)
        ->execute($bind);
}

As you can see, getConnection() is only returning a connection (and it's working fine), the problem is with the function runBool() which is throwing an error on the ->execute($bind); line:

Exception: Parameter 'index' must be a int

For example, my $query is

INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)

And my $bind is

array(8) {
    ["company_id"]=> int(1)
    ["name"]=> string(3) "John Doe"
    ["phone"]=> string(11) "123456789"
    ["cpf"]=> string(0) ""
    ["rg"]=> string(0) ""
    ["city_id"]=> int(79)
    ["address"]=> string(0) ""
    ["obs"]=> string(0) ""
}

I've already tryed to foreach $bind and to use bindParam() or bindValue() individually, and then run execute but I get the same error on the execute().
I've already included : before each key of the array and removed it (following this comment), but nothing changes.
I've already searched a lot on Google but nobody seems to have the same type of trouble.

Info:

PHP 7.1.12

Ubuntu 16.04.03

MySQL 5.7.20

Vagrant 2.0.0

Every help is appreciated.

---------------- EDIT ----------------

As asked, I've checked my namespaces, but I'm using \Pdo, so I think it's the native PHP PDO class. Here's the var_dump of self::getConnection()->prepare($query):

object(PDOStatement)#90 (1) { ["queryString"]=> string(149) "INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)" }

And here's my table:

CREATE TABLE `client` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(50) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `city_id` int(10) UNSIGNED NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `cpf` varchar(14) DEFAULT NULL,
  `rg` varchar(15) DEFAULT NULL,
  `obs` varchar(100) DEFAULT NULL,
  `company_id` int(10) UNSIGNED NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `client`
  ADD PRIMARY KEY (`id`),
  ADD KEY `city_id` (`city_id`),
  ADD KEY `company_id` (`company_id`);
ALTER TABLE `client` ADD FULLTEXT KEY `search` (`name`,`phone`,`address`,`cpf`,`rg`,`obs`);
ALTER TABLE `client` ADD FULLTEXT KEY `search_basic` (`name`);

ALTER TABLE `client`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=613;

ALTER TABLE `client`
  ADD CONSTRAINT `client-city_id` FOREIGN KEY (`city_id`) REFERENCES `city` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  ADD CONSTRAINT `client-company_id` FOREIGN KEY (`company_id`) REFERENCES     `company` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;


问:
Cuda GPU is slower than CPU in simple numpy operation
I am using this code based on this article to see the GPU accelerations, but all I can see is slowdown:

```<code>import numpy as np
from timeit import default_timer as timer
from numba import vectorize
import sys

if len(sys.argv) != 3:
    exit("Usage: " + sys.argv[0] + " [cuda|cpu] N(100000-11500000)")

@vectorize(["float32(float32, float32)"], target=sys.argv[1])
def VectorAdd(a, b):
    return a + b

def main():
    N = int(sys.argv[2])
    A = np.ones(N, dtype=np.float32)
    B = np.ones(N, dtype=np.float32)

    start = timer()
    C = VectorAdd(A, B)
    elapsed_time = timer() - start
    #print("C[:5] = " + str(C[:5]))
    #print("C[-5:] = " + str(C[-5:]))
    print("Time: {}".format(elapsed_time))

main()
</code>```

The results:

```<code>$ python speed.py cpu 100000
Time: 0.0001056949986377731
$ python speed.py cuda 100000
Time: 0.11871792199963238

$ python speed.py cpu 11500000
Time: 0.013704434997634962
$ python speed.py cuda 11500000
Time: 0.47120747699955245
</code>```

I cannot send bigger vector as that will generate a numba.cuda.cudadrv.driver.CudaAPIError: Call to cuLaunchKernel results in CUDA_ERROR_INVALID_VALUE exception.`

The output of nvidia-smi is

```<code>Fri Dec  8 10:36:19 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.98                 Driver Version: 384.98                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Quadro 2000D        Off  | 00000000:01:00.0  On |                  N/A |
| 30%   36C   P12    N/A /  N/A |    184MiB /   959MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0       933      G   /usr/lib/xorg/Xorg                            94MiB |
|    0       985      G   /usr/bin/gnome-shell                          86MiB |
+-----------------------------------------------------------------------------+
</code>```

Details of the CPU

```<code>$ lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              4
On-line CPU(s) list: 0-3
Thread(s) per core:  1
Core(s) per socket:  4
Socket(s):           1
NUMA node(s):        1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               58
Model name:          Intel(R) Core(TM) i5-3550 CPU @ 3.30GHz
Stepping:            9
CPU MHz:             3300.135
CPU max MHz:         3700.0000
CPU min MHz:         1600.0000
BogoMIPS:            6600.27
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            256K
L3 cache:            6144K
NUMA node0 CPU(s):   0-3
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm cpuid_fault epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts
</code>```

The GPU is Nvidia Quadro 2000D with 192 CUDA cores and 1Gb RAM.

More complex operation:

```<code>import numpy as np
from timeit import default_timer as timer
from numba import vectorize
import sys

if len(sys.argv) != 3:
    exit("Usage: " + sys.argv[0] + " [cuda|cpu] N()")

@vectorize(["float32(float32, float32)"], target=sys.argv[1])
def VectorAdd(a, b):
    return a * b

def main():
    N = int(sys.argv[2])
    A = np.zeros((N, N), dtype='f')
    B = np.zeros((N, N), dtype='f')
    A[:] = np.random.randn(*A.shape)
    B[:] = np.random.randn(*B.shape)

    start = timer()
    C = VectorAdd(A, B)
    elapsed_time = timer() - start
    print("Time: {}".format(elapsed_time))

main()
</code>```

Results:

```<code>$ python complex.py cpu 3000
Time: 0.010573603001830634
$ python complex.py cuda 3000
Time: 0.3956961739968392
$ python complex.py cpu 30
Time: 9.693001629784703e-06
$ python complex.py cuda 30
Time: 0.10848476299725007
</code>```

Any idea why?

答:
Probably your array is too small and the operation too simple to offset the cost of data transfer associated to the GPU. Other way to see it, is that you're not being fair in your timing since for the GPU it also is timing the memory transfer time and not only the processing time.

Try some more challenging example, maybe first an element wise big matrix multiplication and then a matrix multiplication.

In the end, the power of the GPU is to perform many operations on the same data so you end up paying only once the data transfer cost.

Body:
I am using this code based on this article to see the GPU accelerations, but all I can see is slowdown:

import numpy as np
from timeit import default_timer as timer
from numba import vectorize
import sys

if len(sys.argv) != 3:
    exit("Usage: " + sys.argv[0] + " [cuda|cpu] N(100000-11500000)")

@vectorize(["float32(float32, float32)"], target=sys.argv[1])
def VectorAdd(a, b):
    return a + b

def main():
    N = int(sys.argv[2])
    A = np.ones(N, dtype=np.float32)
    B = np.ones(N, dtype=np.float32)

    start = timer()
    C = VectorAdd(A, B)
    elapsed_time = timer() - start
    #print("C[:5] = " + str(C[:5]))
    #print("C[-5:] = " + str(C[-5:]))
    print("Time: {}".format(elapsed_time))

main()

The results:

$ python speed.py cpu 100000
Time: 0.0001056949986377731
$ python speed.py cuda 100000
Time: 0.11871792199963238

$ python speed.py cpu 11500000
Time: 0.013704434997634962
$ python speed.py cuda 11500000
Time: 0.47120747699955245

I cannot send bigger vector as that will generate a numba.cuda.cudadrv.driver.CudaAPIError: Call to cuLaunchKernel results in CUDA_ERROR_INVALID_VALUE exception.`

The output of nvidia-smi is

Fri Dec  8 10:36:19 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.98                 Driver Version: 384.98                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Quadro 2000D        Off  | 00000000:01:00.0  On |                  N/A |
| 30%   36C   P12    N/A /  N/A |    184MiB /   959MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0       933      G   /usr/lib/xorg/Xorg                            94MiB |
|    0       985      G   /usr/bin/gnome-shell                          86MiB |
+-----------------------------------------------------------------------------+

Details of the CPU

$ lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              4
On-line CPU(s) list: 0-3
Thread(s) per core:  1
Core(s) per socket:  4
Socket(s):           1
NUMA node(s):        1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               58
Model name:          Intel(R) Core(TM) i5-3550 CPU @ 3.30GHz
Stepping:            9
CPU MHz:             3300.135
CPU max MHz:         3700.0000
CPU min MHz:         1600.0000
BogoMIPS:            6600.27
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            256K
L3 cache:            6144K
NUMA node0 CPU(s):   0-3
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm cpuid_fault epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts

The GPU is Nvidia Quadro 2000D with 192 CUDA cores and 1Gb RAM.

More complex operation:

import numpy as np
from timeit import default_timer as timer
from numba import vectorize
import sys

if len(sys.argv) != 3:
    exit("Usage: " + sys.argv[0] + " [cuda|cpu] N()")

@vectorize(["float32(float32, float32)"], target=sys.argv[1])
def VectorAdd(a, b):
    return a * b

def main():
    N = int(sys.argv[2])
    A = np.zeros((N, N), dtype='f')
    B = np.zeros((N, N), dtype='f')
    A[:] = np.random.randn(*A.shape)
    B[:] = np.random.randn(*B.shape)

    start = timer()
    C = VectorAdd(A, B)
    elapsed_time = timer() - start
    print("Time: {}".format(elapsed_time))

main()

Results:

$ python complex.py cpu 3000
Time: 0.010573603001830634
$ python complex.py cuda 3000
Time: 0.3956961739968392
$ python complex.py cpu 30
Time: 9.693001629784703e-06
$ python complex.py cuda 30
Time: 0.10848476299725007

Any idea why?


答:
Use simple for loop for this with Object.values method, to get values as array

var arr = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
];
var newArr = [];
for(let i in arr){
  for(let j in arr[i]){
    newArr.push(Object.values(arr[i][j]));
  }
}
console.log(newArr);```

Title: Javascript convert objects to array


问:
Error when setting string parameter to native query in hibernate
We are using Hibernate in one of our projects and there we use native queries.
In one of the native queries the sql looks like:
AND LNG_ISO = :searchLang.
Then I set the parameter like:

```<code>query.setParameter("searchLang", "deu");
</code>```

But the result shows, that this parameter was not taken into account.
The query is correct, as replacing
AND LNG_ISO = :searchLang with AND LNG_ISO = 'deu' returns the expected result.

What is wrong with my string parameter?
Maybe I have to wrap the value in single quotation marks, but I did not find a way how to do it.

答:
In general using the generic vanilla query.setParameter is not advised because it is much slower and error prone than its specialized equivalents. Try one of these:

```<code>query.setString("searchLang", "deu");
query.setParameter("searchLang", "deu", StringType.INSTANCE);
</code>```

if you are using Hibernate 5.2 or greater than only the latter options is allowed.

Body:
We are using Hibernate in one of our projects and there we use native queries.
In one of the native queries the sql looks like:
AND LNG_ISO = :searchLang.
Then I set the parameter like:

query.setParameter("searchLang", "deu");

But the result shows, that this parameter was not taken into account.
The query is correct, as replacing
AND LNG_ISO = :searchLang with AND LNG_ISO = 'deu' returns the expected result.

What is wrong with my string parameter?
Maybe I have to wrap the value in single quotation marks, but I did not find a way how to do it.

Body:
In general using the generic vanilla query.setParameter is not advised because it is much slower and error prone than its specialized equivalents. Try one of these:

query.setString("searchLang", "deu");
query.setParameter("searchLang", "deu", StringType.INSTANCE);

if you are using Hibernate 5.2 or greater than only the latter options is allowed.


问:
what is the best way to use a custom json converter to convert a complex object?
I'm using asp.net core to create a webapi project.

When an object is posted to my action, I want to use the custom converter to analyse the json object first.And then create an instance of a child class. For the child, instance I only want to customize one property. So the question is, what if the object gets complex, I want to use the standard conversion to get the whole object, and manually manipulate one property.

What is the best way of achieving this?

答: You can add only the properties you want to your View Model, the rest will be ignored. </p>


问:
Python import coding style
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

```<code>import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)
</code>```

I move all my imports into the function where they're actually used., like this:

```<code>def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)
</code>```

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

答:
From a performance point of view, you can see this: Should Python import statements always be at the top of a module?

In general, I only use local imports in order to break dependency cycles.

OwnerDisplayName: TokenMacGuy

ContentLicense: CC BY-SA 2.5

Title: Python import coding style

Body:
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)

I move all my imports into the function where they're actually used., like this:

def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

OwnerDisplayName: sykora


问:
Empty string as base case in BNF recursion?
I'm writing a small grammar as an exercise for class and my professor didn't really get too specific with what qualifies a legal BNF expression in terms.

The BNF grammar is supposed to recognize strings in this form: AB, AABB, AAABBB, A...B... (general form: AnBn)

So, what I got up to was writing:

```<code><S> --> A<S>B | ""
</code>```

My simple yes/no question is whether or not this is legal in BNF, and if not why?

<...> represents a non-terminal, I have no idea if that's convention or what not

答:
Yes, this is acceptable BNF.  You can see an example of this on the Wikipedia entry in the example about US postal addresses.

Typically, though, I've seen the empty string represented as ε.

Body:
I'm writing a small grammar as an exercise for class and my professor didn't really get too specific with what qualifies a legal BNF expression in terms.

The BNF grammar is supposed to recognize strings in this form: AB, AABB, AAABBB, A...B... (general form: AnBn)

So, what I got up to was writing:

<S> --> A<S>B | ""

My simple yes/no question is whether or not this is legal in BNF, and if not why?

<...> represents a non-terminal, I have no idea if that's convention or what not


问:
Mat-table does not print data in Angular 5
I would use mat-table in my project

In my component file I use observable to catch data from DB and print them in my data table.

I tried to follow the official tutorial but nothing is printed on screen and I don't get error

```<code>export class ListeProjetsComponent implements OnInit {

  constructor(private ajoutProj: AjoutprojService) { }
  nouveauProjet: NouveauProjet[];
  ngOnInit(){
    this.getAllProj();
  }
  displayedColumns = ['name'];
  dataSource = new MatTableDataSource<NouveauProjet>(this.nouveauProjet);

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  getAllProj() {
    this.ajoutProj.getAllProj().subscribe(
      response => {
      this.nouveauProjet = response; console.log(this.nouveauProjet) // data is printed in the browser console. but not on screen
      },
      error => console.log(error)
    );
  }
}
</code>```

Html file

```<code><div class="example-container mat-elevation-z8">
  <div class="example-header">
    <mat-form-field>
      <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>
  </div>

  <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.nomProj}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>
</code>```

答:
This might be happening because you initialize the table with an empty data set:

```<code>dataSource = new MatTableDataSource<NouveauProjet>(this.nouveauProjet);
</code>```

At this point, this.nouveauProjet presumably does not contain any data;

Try re initializing the table data source when you get the data from your service:

```<code>  getAllProj() {
    this.ajoutProj.getAllProj().subscribe(
      response => {
        // set dataSource here
        this.dataSource = new MatTableDataSource<NouveauProjet>(response);
      },
      error => console.log(error)
    );
  }
</code>```

Body:
I would use mat-table in my project

In my component file I use observable to catch data from DB and print them in my data table.

I tried to follow the official tutorial but nothing is printed on screen and I don't get error

export class ListeProjetsComponent implements OnInit {

  constructor(private ajoutProj: AjoutprojService) { }
  nouveauProjet: NouveauProjet[];
  ngOnInit(){
    this.getAllProj();
  }
  displayedColumns = ['name'];
  dataSource = new MatTableDataSource<NouveauProjet>(this.nouveauProjet);

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  getAllProj() {
    this.ajoutProj.getAllProj().subscribe(
      response => {
      this.nouveauProjet = response; console.log(this.nouveauProjet) // data is printed in the browser console. but not on screen
      },
      error => console.log(error)
    );
  }
}

Html file

    <mat-form-field>
      <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>

  <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.nomProj}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>

Body:
This might be happening because you initialize the table with an empty data set:

dataSource = new MatTableDataSource<NouveauProjet>(this.nouveauProjet);

At this point, this.nouveauProjet presumably does not contain any data;

Try re initializing the table data source when you get the data from your service:

  getAllProj() {
    this.ajoutProj.getAllProj().subscribe(
      response => {
        // set dataSource here
        this.dataSource = new MatTableDataSource<NouveauProjet>(response);
      },
      error => console.log(error)
    );
  }


问:
table creation logic
I am looking to take two tables I have a perform a data transformation to create a single table. I have an events table and user table:

```<code>Events: {id, user_id, start_date, end_date, cost...}

Users: {id, name, ...}
</code>```

I am trying to create a table at that shows user spend at a daily level, assuming the user start with a starting cost of zero and it goes up after every event.

The intended output would be:

```<code>{date, userid, beginning_balance, sum(cost), num_of_events}
</code>```

i need some direction on how to tackle this one as I am not very familiar with data transformation within SQL

Title: table creation logic

Body:
I am looking to take two tables I have a perform a data transformation to create a single table. I have an events table and user table:

Events: {id, user_id, start_date, end_date, cost...}

Users: {id, name, ...}

I am trying to create a table at that shows user spend at a daily level, assuming the user start with a starting cost of zero and it goes up after every event.

The intended output would be:

{date, userid, beginning_balance, sum(cost), num_of_events}

i need some direction on how to tackle this one as I am not very familiar with data transformation within SQL

Body:
Your requirement is a bit unclear but you may be after something like this

drop table if exists event;
create table event(id int auto_increment primary key, user_id int,start_date date, end_date date, cost int);
insert into event (user_id,start_date , end_date, cost) values
(1,'2017-01-01','2017-01-01',10),(1,'2017-01-01','2017-01-01',10),
(1,'2017-02-01','2017-01-01',10),
(2,'2017-01-01','2017-01-01',10);

select e.user_id,start_date,
            ifnull(
            (select  sum(cost)
            from event e1
            where e1.user_id = e.user_id and e1.start_date <e.start_date
            ),  0 )beginning_balance,
            sum(cost),count(*)
           as num_of_events
from users u
join event e on e.user_id = u.userid
group by e.user_id,start_date

+---------+------------+-------------------+-----------+---------------+
| user_id | start_date | beginning_balance | sum(cost) | num_of_events |
+---------+------------+-------------------+-----------+---------------+
|       1 | 2017-01-01 |                 0 |        20 |             2 |
|       1 | 2017-02-01 |                20 |        10 |             1 |
|       2 | 2017-01-01 |                 0 |        10 |             1 |
+---------+------------+-------------------+-----------+---------------+
3 rows in set (0.03 sec)


问:
TFS Build release IIS Deployment Virtual path should begin with a / Error
Virtual path should begin with a / Error is coming when I try to build ASP.NET Application.

When I try to deploy following error massage come

2017-12-07T22:14:15.6196402Z ##[section]Starting: Release
2017-12-07T22:14:15.6217147Z Current agent version: 2.126.0
2017-12-07T22:14:16.7467026Z ##[section]Starting: Initialize Job
2017-12-07T22:14:16.7497604Z Prepare release directory.
2017-12-07T22:14:16.7507232Z ReleaseId=2, TeamProjectId=49dcec02-39e8-4590-82a2-ab110a875d7e, ReleaseDefinitionName=New Release Definition
2017-12-07T22:14:16.7547852Z Release folder: C:\vstsagent\A4_work\r1\a
2017-12-07T22:14:16.7709838Z Environment variables available are below.  Note that these environment variables can be referred to in the task (in the ReleaseDefinition) by replacing "_" with "." e.g. AGENT_NAME environment variable can be referenced using Agent.Name in the ReleaseDefinition:

2017-12-07T22:14:17.1451135Z Download all required tasks.
2017-12-07T22:14:17.1837731Z ##[section]Finishing: Initialize Job
2017-12-07T22:14:17.2162154Z ##[section]Starting: Download Artifacts
2017-12-07T22:14:17.2272283Z Creating artifacts directory: C:\vstsagent\A4_work\r1\a
2017-12-07T22:14:17.2611603Z Created artifacts directory: C:\vstsagent\A4_work\r1\a
2017-12-07T22:14:17.2611793Z Downloading artifact
2017-12-07T22:14:17.2630213Z Starting artifacts download...
2017-12-07T22:14:17.2656016Z Downloading linked artifact CIDemo-ASP.NET (PREVIEW)-CI of type Build...
2017-12-07T22:14:17.2692891Z Ensuring artifact folder C:\vstsagent\A4_work\r1\a\CIDemo-ASP.NET (PREVIEW)-CI exists and is clean.
2017-12-07T22:14:17.2763873Z Preparing to get the list of available artifacts from build
2017-12-07T22:14:17.7608040Z Preparing to download artifact: drop
2017-12-07T22:14:17.7677814Z Artifact Type: ServerDrop
2017-12-07T22:14:17.7678100Z Downloading artifact from file container: #/1049368/drop to target: C:\vstsagent\A4_work\r1\a\CIDemo-ASP.NET (PREVIEW)-CI\drop
2017-12-07T22:14:17.7681631Z Parallel download limit: 4
2017-12-07T22:14:17.7681855Z Download buffer size: 8192
2017-12-07T22:14:18.0849933Z Caching items under drop in the file container...
2017-12-07T22:14:18.2018057Z Caching complete. (116 ms)
2017-12-07T22:14:18.2223239Z Downloading file
2017-12-07T22:14:28.2769926Z Download complete.
2017-12-07T22:14:28.2777174Z 126 placed file(s): 126 downloaded, 0 empty
2017-12-07T22:14:28.2778130Z 24 MB downloaded at 2435 KB/sec. Download time: 00:00:10.0528421.
2017-12-07T22:14:28.2778657Z Downloaded linked artifact CIDemo-ASP.NET (PREVIEW)-CI
2017-12-07T22:14:28.2778827Z Finished artifacts download
2017-12-07T22:14:28.2818295Z ##[section]Finishing: Download Artifacts
2017-12-07T22:14:28.2842190Z ##[section]Starting: IIS Web App Manage
2017-12-07T22:14:28.3045728Z ==============================================================================
2017-12-07T22:14:28.3045901Z Task         : IIS Web App Manage
2017-12-07T22:14:28.3046054Z Description  : Create or update a Website, Web App, Virtual Directories, and Application Pool
2017-12-07T22:14:28.3046224Z Version      : 0.5.4
2017-12-07T22:14:28.3046352Z Author       : Microsoft Corporation
2017-12-07T22:14:28.3046498Z Help         : [More Information]
2017-12-07T22:14:28.3046664Z ==============================================================================

2017-12-07T22:14:30.0691429Z ##[error]Virtual path should begin with a /

2017-12-07T22:14:30.0892513Z ##[section]Finishing: IIS Web App Manage
2017-12-07T22:14:30.0966325Z ##[section]Finishing: Release

答:
Please check the settings with the step IIS Web App Manage. Seems you did not set the Virtual path correctly.

Virtual path:

Parameters for IIS Application configuration:

Enter the virtual path in IIS relative to the parent website. The
  parent website must already exist. Example: to create an application
  named Site/Application enter /Application.

Parameters for IIS Virtual Directory configuration：

Enter the virtual path in IIS relative to the parent website. The
  parent website and application must already exist. Example: to create
  a virtual directory named Site/Application/VDir enter
  /Application/Vdir.

See Deploy: IIS Web App Manage for details.


问:
In numpy, why is .var() a method while mean() is a normal function?
As an R programmer learning Python, I've been getting confused by the Python syntax a few times. Many of these behaviors seem arbitrary to me. It would help me to understand the reasons behind why things are the way they are in Python. I'm also new to OOP, so this might be the reason for my confusion.

Specifically, these two points confused me the most while following a tutorial:

To compute an array's mean, you use np.mean(myarray). But to compute the variance, you use myarray.var() (that's a method, right?). This seems arbitrary - was there a reason for choosing to implement things in this way?

Plotting a histogram consists of two subsequent commands, plot.hist(values, 50) followed by plt.show(). Why is the second call necessary? And where does the "result" of the first call get stored? Is this some kind of OOP magic?

答:
You can use these methods both ways:  The reasoning was to make scientific python packages friendly for users not comfortable with OOP, and provide a familiar API to people used to matlab, or R.

As pointed out in the comments by @Mel, the matplotlib package also shares this feature.

```<code>import numpy as np

a = np.array([range(10)])
a.mean(), a.var(), np.mean(a), np.var(a)
</code>```

output:

```<code>(4.5, 8.25, 4.5, 8.25)
</code>```

Body:
You can use these methods both ways:  The reasoning was to make scientific python packages friendly for users not comfortable with OOP, and provide a familiar API to people used to matlab, or R.

As pointed out in the comments by @Mel, the matplotlib package also shares this feature.

import numpy as np

a = np.array([range(10)])
a.mean(), a.var(), np.mean(a), np.var(a)

output:

(4.5, 8.25, 4.5, 8.25)


问:
Storing function pointer in std::function
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

```<code>class DynamicLoader
{
  public:
    DynamicLoader(std::string const& filename);

    template<class Signature>
      std::function<Signature> load(std::string const& functionName);

  private:
    void *itsLibraryHandle;
};

DynamicLoader::DynamicLoader(std::string const& filename)
{
  itsLibraryHandle = dlopen(filename.c_str(), RTLD_LAZY);

  if(!itsLibraryHandle)
  { /* Throw Some Error */ }
}

  template<class Signature>
std::function<Signature> DynamicLoader::load(std::string const& functionName)
{
  return <insert magic here> dlsym(itsHandle, functionName.c_str());
}
</code>```

Is there a way to convert the void* function pointer returned by dlsym into a std::function?

答:
try this:

```<code>static_cast<Signature*>()
</code>```

seems works in VC10

complete test:

```<code>#include <functional>

void test()
{}

template <typename Signature>
std::function<Signature> cast(void* f)
{
    return static_cast<Signature*>(f);
}

int main()
{
    std::function<void()> f = cast<void()>(&test);
    return 0;
}
</code>```

Body:
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

class DynamicLoader
{
  public:
    DynamicLoader(std::string const& filename);

    template<class Signature>
      std::function<Signature> load(std::string const& functionName);

  private:
    void *itsLibraryHandle;
};

DynamicLoader::DynamicLoader(std::string const& filename)
{
  itsLibraryHandle = dlopen(filename.c_str(), RTLD_LAZY);

  if(!itsLibraryHandle)
  { /* Throw Some Error */ }
}

  template<class Signature>
std::function<Signature> DynamicLoader::load(std::string const& functionName)
{
  return <insert magic here> dlsym(itsHandle, functionName.c_str());
}

Is there a way to convert the void* function pointer returned by dlsym into a std::function?

Body:
try this:

static_cast<Signature*>()

seems works in VC10

complete test:

#include <functional>

void test()
{}

template <typename Signature>
std::function<Signature> cast(void* f)
{
    return static_cast<Signature*>(f);
}

int main()
{
    std::function<void()> f = cast<void()>(&test);
    return 0;
}


问:
How to retrieve zendesk comments
I am working with the Zendesk API Client gem and I am having trouble including comments in the reply I can retrieve the ticket but it doesn't include the comments to that ticket my code is below

```<code>ticket = ZendeskAPI::Ticket.find(client, id: 34798)
p ticket
</code>```

and here is the response I am getting, is there something obvious I am missing here?

```<code>{
   "ticket"   =>   {
      "url"      =>"https://baopals.zendesk.com/api/v2/tickets/34798.json",
      "id"      =>34798,
      "external_id"      =>nil,
      "via"      =>      {
         "channel"         =>"api",
         "source"         =>         {
            "from"            =>            {

            },
            "to"            =>            {

            },
            "rel"            =>nil
         }
      },
      "created_at"      =>2017-11-17 09:49:11      UTC,
      "updated_at"      =>2017-11-17 09:49:49      UTC,
      "type"      =>nil,
      "subject"      =>"V2 test ticket",
      "raw_subject"      =>"V2 test ticket",
      "description"      =>"1111111111111111111111111111111111111111111111111111111111111111111111",
      "priority"      =>"normal",
      "status"      =>"open",
      "recipient"      =>nil,
      "requester_id"      =>15534722228,
      "submitter_id"      =>15534722228,
      "assignee_id"      =>nil,
      "organization_id"      =>13463857128,
      "group_id"      =>nil,
      "collaborator_ids"      =>      [

      ],
      "follower_ids"      =>      [

      ],
      "forum_topic_id"      =>nil,
      "problem_id"      =>nil,
      "has_incidents"      =>false,
      "is_public"      =>true,
      "due_at"      =>nil,
      "tags"      =>      [

      ],
      "custom_fields"      =>      [
         {
            "id"            =>114097936533,
            "value"            =>false
         },
         {
            "id"            =>114097989754,
            "value"            =>false
         },
         {
            "id"            =>61510988,
            "value"            =>false
         },
         {
            "id"            =>114097437574,
            "value"            =>false
         },
         {
            "id"            =>58345127,
            "value"            =>nil
         },
         {
            "id"            =>76165848,
            "value"            =>nil
         },
         {
            "id"            =>61403888,
            "value"            =>nil
         },
         {
            "id"            =>60446708,
            "value"            =>nil
         }
      ],
      "satisfaction_rating"      =>nil,
      "sharing_agreement_ids"      =>      [

      ],
      "fields"      =>      [
         {
            "id"            =>114097936533,
            "value"            =>false
         },
         {
            "id"            =>114097989754,
            "value"            =>false
         },
         {
            "id"            =>61510988,
            "value"            =>false
         },
         {
            "id"            =>114097437574,
            "value"            =>false
         },
         {
            "id"            =>58345127,
            "value"            =>nil
         },
         {
            "id"            =>76165848,
            "value"            =>nil
         },
         {
            "id"            =>61403888,
            "value"            =>nil
         },
         {
            "id"            =>60446708,
            "value"            =>nil
         }
      ],
      "brand_id"      =>3123448,
      "allow_channelback"      =>false
   }
}
</code>```

答:
Ticket Comments is actually a separate endpoint documented here - https://developer.zendesk.com/rest_api/docs/core/ticket_comments

Looks like you may be able to use ticket.comments() to get the comments

Title: How to retrieve zendesk comments

Body:
I am working with the Zendesk API Client gem and I am having trouble including comments in the reply I can retrieve the ticket but it doesn't include the comments to that ticket my code is below

ticket = ZendeskAPI::Ticket.find(client, id: 34798)
p ticket

and here is the response I am getting, is there something obvious I am missing here?

{
   "ticket"   =>   {
      "url"      =>"https://baopals.zendesk.com/api/v2/tickets/34798.json",
      "id"      =>34798,
      "external_id"      =>nil,
      "via"      =>      {
         "channel"         =>"api",
         "source"         =>         {
            "from"            =>            {

            },
            "to"            =>            {

            },
            "rel"            =>nil
         }
      },
      "created_at"      =>2017-11-17 09:49:11      UTC,
      "updated_at"      =>2017-11-17 09:49:49      UTC,
      "type"      =>nil,
      "subject"      =>"V2 test ticket",
      "raw_subject"      =>"V2 test ticket",
      "description"      =>"1111111111111111111111111111111111111111111111111111111111111111111111",
      "priority"      =>"normal",
      "status"      =>"open",
      "recipient"      =>nil,
      "requester_id"      =>15534722228,
      "submitter_id"      =>15534722228,
      "assignee_id"      =>nil,
      "organization_id"      =>13463857128,
      "group_id"      =>nil,
      "collaborator_ids"      =>      [

      ],
      "follower_ids"      =>      [

      ],
      "forum_topic_id"      =>nil,
      "problem_id"      =>nil,
      "has_incidents"      =>false,
      "is_public"      =>true,
      "due_at"      =>nil,
      "tags"      =>      [

      ],
      "custom_fields"      =>      [
         {
            "id"            =>114097936533,
            "value"            =>false
         },
         {
            "id"            =>114097989754,
            "value"            =>false
         },
         {
            "id"            =>61510988,
            "value"            =>false
         },
         {
            "id"            =>114097437574,
            "value"            =>false
         },
         {
            "id"            =>58345127,
            "value"            =>nil
         },
         {
            "id"            =>76165848,
            "value"            =>nil
         },
         {
            "id"            =>61403888,
            "value"            =>nil
         },
         {
            "id"            =>60446708,
            "value"            =>nil
         }
      ],
      "satisfaction_rating"      =>nil,
      "sharing_agreement_ids"      =>      [

      ],
      "fields"      =>      [
         {
            "id"            =>114097936533,
            "value"            =>false
         },
         {
            "id"            =>114097989754,
            "value"            =>false
         },
         {
            "id"            =>61510988,
            "value"            =>false
         },
         {
            "id"            =>114097437574,
            "value"            =>false
         },
         {
            "id"            =>58345127,
            "value"            =>nil
         },
         {
            "id"            =>76165848,
            "value"            =>nil
         },
         {
            "id"            =>61403888,
            "value"            =>nil
         },
         {
            "id"            =>60446708,
            "value"            =>nil
         }
      ],
      "brand_id"      =>3123448,
      "allow_channelback"      =>false
   }
}


问:
Vuetify .input-group__details change min-height impossible
I'm not an CSS Expert but until now I've not seen any "problem" like this.

So, I am using Vuetify and I added a  for my search form..

Now that component is creating:

```<code><div input-group input-group--prepend-icon input-group--text-field primary--text>
  <label for="search"></label>
  <div class="input-group__input"></div>
  <div class="input-group__details"></div>
  <div class="input-group__messages"></div>
</div>
</code>```

Now my problem is that class .input-group__messages has a min-height and I want it to have 1px or not show at this case, but I can't manage to edit that from my component... there is the way to go to root style but I don't want to do that I want to learn or to know what's the problem what am I missing.

Looking forward for a reply from someone

答:
You need vue-loader version 12.2+ and use Deep selectors

Using CSS (also works with stylus but your IDE might throw syntax errors):

```<code>>>> .input-group__messages {
    min-height: 1px;
}
</code>```

Or SCSS:

```<code>/deep/ .input-group__messages {
    min-height: 1px;
}
</code>```

See this answer for explanations, and other possible solutions if the above did not work.

Body:
I'm not an CSS Expert but until now I've not seen any "problem" like this.

So, I am using Vuetify and I added a  for my search form..

Now that component is creating:

Now my problem is that class .input-group__messages has a min-height and I want it to have 1px or not show at this case, but I can't manage to edit that from my component... there is the way to go to root style but I don't want to do that I want to learn or to know what's the problem what am I missing.

Looking forward for a reply from someone

Body:
You need vue-loader version 12.2+ and use Deep selectors

Using CSS (also works with stylus but your IDE might throw syntax errors):

>>> .input-group__messages {
    min-height: 1px;
}

Or SCSS:

/deep/ .input-group__messages {
    min-height: 1px;
}

See this answer for explanations, and other possible solutions if the above did not work.

ContentLicense: CC BY-SA 4.0


问:
Is it safe to define my io as global.io
I am new to nodejs and socket. What I would like to know is how I should able to access my io variable in different controllers or files. Is it safe to declare my io variable as:

```<code>global.io = require('socket.io').listen(server);
</code>```

so now my io is accessible in any of my controller?

I got this idea from this link:

https://blog.sylo.space/use-global-variable-for-socket-io/

答:
It can cause crashes if it overlaps with another variable, which could be hard to track/handle if your project is quite big and/or includes a lot of librariers, it also exists for the lifetime of the application thus taking up resources. And it is overall considered bad practice to use global variables.

You can check out a great article about global variables in node.js here - http://stackabuse.com/using-global-variables-in-node-js/

EDIT: Since you mentioned safety, it is safe on theory, just not recommended.

Title: Is it safe to define my io as global.io

Body:
I am new to nodejs and socket. What I would like to know is how I should able to access my io variable in different controllers or files. Is it safe to declare my io variable as:

global.io = require('socket.io').listen(server);

so now my io is accessible in any of my controller?

I got this idea from this link:

https://blog.sylo.space/use-global-variable-for-socket-io/


问:
Why Database Dropcolumn Entity Framework?
I am trying to add an image to my database on my online web shop (I want all the details for the product to be in my database so I can use the data on several places - I am trying to follow the DRY-principle). First I tried with "Add-Migration Image". But it drops the lines with the image. Why is that?

Here is my Product entity:

```<code>public class Product
{
    [Key]
    public int ProductID { get; set; }

    [Required(ErrorMessage = "Please enter an product name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please specify a category")]
    public string Category { get; set; }

    public string SubCategory { get; set; }

    [Required(ErrorMessage = "Please enter a description")]
    public string Description { get; set; }

    [Required
    (ErrorMessage = "Please enter a positive price")]
    public decimal Price { get; set; }

    public byte[] Image { get; set; }

    public string ImageSourceFileName { get; set; }

    public string ImageContentType { get; set; }
}
</code>```

Here it was happen. The database first takes the new lines than it drops them. Why is that? And what shall I do differently?

```<code>public partial class Image2 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<byte[]>(
            name: "Image",
            table: "Products",
            type: "varbinary(max)",
            nullable: true);

        migrationBuilder.AddColumn<string>(
            name: "ImageContentType",
            table: "Products",
            type: "nvarchar(max)",
            nullable: true);

        migrationBuilder.AddColumn<string>(
            name: "ImageSourceFileName",
            table: "Products",
            type: "nvarchar(max)",
            nullable: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "Image",
            table: "Products");

        migrationBuilder.DropColumn(
            name: "ImageContentType",
            table: "Products");

        migrationBuilder.DropColumn(
            name: "ImageSourceFileName",
            table: "Products");
    }
}
</code>```

In the end I want to be able to add an image in the Create-Edit-Delete-Views.

This is my process:

First update the database with the Image-rows.

Change the controller and the views so they can handle the image.

See above.

答:
Your migration contains two parts, up and down.

Up is the part that adds the new changes to your database.

The down part is the part you use to undo those changes. So if you want to roll back your migration, the down method is called. Logically, rolling back means dropping the newly added columns.

As long as you do not roll back to a previous version, the down method is never called.

Body:
I am trying to add an image to my database on my online web shop (I want all the details for the product to be in my database so I can use the data on several places - I am trying to follow the DRY-principle). First I tried with "Add-Migration Image". But it drops the lines with the image. Why is that?

Here is my Product entity:

public class Product
{
    [Key]
    public int ProductID { get; set; }

    [Required(ErrorMessage = "Please enter an product name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please specify a category")]
    public string Category { get; set; }

    public string SubCategory { get; set; }

    [Required(ErrorMessage = "Please enter a description")]
    public string Description { get; set; }

    [Required
    (ErrorMessage = "Please enter a positive price")]
    public decimal Price { get; set; }

    public byte[] Image { get; set; }

    public string ImageSourceFileName { get; set; }

    public string ImageContentType { get; set; }
}

Here it was happen. The database first takes the new lines than it drops them. Why is that? And what shall I do differently?

public partial class Image2 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<byte[]>(
            name: "Image",
            table: "Products",
            type: "varbinary(max)",
            nullable: true);

        migrationBuilder.AddColumn<string>(
            name: "ImageContentType",
            table: "Products",
            type: "nvarchar(max)",
            nullable: true);

        migrationBuilder.AddColumn<string>(
            name: "ImageSourceFileName",
            table: "Products",
            type: "nvarchar(max)",
            nullable: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "Image",
            table: "Products");

        migrationBuilder.DropColumn(
            name: "ImageContentType",
            table: "Products");

        migrationBuilder.DropColumn(
            name: "ImageSourceFileName",
            table: "Products");
    }
}

In the end I want to be able to add an image in the Create-Edit-Delete-Views.

This is my process:

First update the database with the Image-rows.

Change the controller and the views so they can handle the image.

See above.