问:
jQuery Animate not behaving as expected
For some reason when I click the close icon it animated the position down like expected but then automatically comes back up.

FIDDLE: https://jsfiddle.net/fq7na1zr/

If you go to the fiddle and click the orange box, it will animate its position up and also show you a X to close it.

When you click the X it animates the div down again but then it shoots back up.

How do I get the div to stay down?

HTML:

```<code>    <div data-position="down" id="container">
        <div id="close" style="display: none;">X</div>
    lorem ipsum dolor sit amet
    </div>
</code>```

jQuery:

```<code>  $('#container').click(function() {
            var currentState = $(this).data('position');

            if (currentState == "down") {
                $('#container').animate({bottom: "20%"});
                $('#container').attr('data-position','up');
                $('#close').css('display','block');
            }

        });

        $('#close').click(function() {
            $('#container').animate({bottom: "-100%"});
            $('#container').attr('data-position','down');
            $('#close').css('display','none');
        });
</code>```

答: This is happening because while you click on the X, the container click event also gets triggered because the click goes through, so you get whatever happens on the "X" click event first, and then whatever happens in the .container click event, which is, as expected, to go back up. You should make some flag like "isDown" and set it to true or false when relevant, and make an if condition with it inside each event handler in order to avoid both actions to take place.</p>

Title: jQuery Animate not behaving as expected

Body:
For some reason when I click the close icon it animated the position down like expected but then automatically comes back up.

FIDDLE: https://jsfiddle.net/fq7na1zr/

If you go to the fiddle and click the orange box, it will animate its position up and also show you a X to close it.

When you click the X it animates the div down again but then it shoots back up.

How do I get the div to stay down?

HTML:

X

    lorem ipsum dolor sit amet

jQuery:

  $('#container').click(function() {
            var currentState = $(this).data('position');

            if (currentState == "down") {
                $('#container').animate({bottom: "20%"});
                $('#container').attr('data-position','up');
                $('#close').css('display','block');
            }

        });

        $('#close').click(function() {
            $('#container').animate({bottom: "-100%"});
            $('#container').attr('data-position','down');
            $('#close').css('display','none');
        });


来源: stackexchange

问:
how can i use res.render for ejs multiple times?
I'm trying to call res.render twice in my nodeJS application but I keep getting an error, when I do so. does anyone know how I could call res.render twice in my app, without switching the file? or including it in all one res.render or changing the director?

```<code>var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.get("/", function (req, res) {
    res.render("index", {
        data: "Hello, guys",
    });
    res.render("index", {
        name: "Hello, again",
    });
});

app.listen(10022, function () {
    console.log("server is up");
});
</code>```

I know the above code will not work. I would like to know how i can send data, and name at different times during the code.

答: I was seeing the same issue because I had multiple asynchronous http calls happening as part of processing the first json response I got from my server and I had to wait for all of them to complete before rendering the response. The way I addressed this is that I kept a counter on how many http request I had to make and then call res.render after that. Hope this helps. </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to call res.render twice in my nodeJS application but I keep getting an error, when I do so. does anyone know how I could call res.render twice in my app, without switching the file? or including it in all one res.render or changing the director?

var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.get("/", function (req, res) {
    res.render("index", {
        data: "Hello, guys",
    });
    res.render("index", {
        name: "Hello, again",
    });
});

app.listen(10022, function () {
    console.log("server is up");
});

I know the above code will not work. I would like to know how i can send data, and name at different times during the code.


问:
Transposing dataframe column, creating different rows per day
I have a dataframe that has one column and a timestamp index including anywhere from 2 to 7 days:

```<code>                         kWh
Timestamp
2017-07-08 06:00:00     0.00
2017-07-08 07:00:00   752.75
2017-07-08 08:00:00  1390.20
2017-07-08 09:00:00  2027.65
2017-07-08 10:00:00  2447.27
        ....           ....
2017-07-12 20:00:00   167.64
2017-07-12 21:00:00     0.00
2017-07-12 22:00:00     0.00
2017-07-12 23:00:00     0.00
</code>```

I would like to transpose the kWh column so that one day's worth of values (hourly granularity, so 24 values/day) fill up a row.  And the next row is the next day of values and so on (so five days of forecasted data has five rows with 24 elements each).

Because my query of the data comes in the vertical format, and my regression and subsequent analysis already occurs in the vertical format, I don't want to change the process too much and am hoping there is a simpler way.  I have tried giving a multi-index with df.index.hour and then using unstack(), but I get a huge dataframe with NaN values everywhere.

Is there an elegant way to do this?

Body:
I have a dataframe that has one column and a timestamp index including anywhere from 2 to 7 days:

                         kWh
Timestamp
2017-07-08 06:00:00     0.00
2017-07-08 07:00:00   752.75
2017-07-08 08:00:00  1390.20
2017-07-08 09:00:00  2027.65
2017-07-08 10:00:00  2447.27
        ....           ....
2017-07-12 20:00:00   167.64
2017-07-12 21:00:00     0.00
2017-07-12 22:00:00     0.00
2017-07-12 23:00:00     0.00

I would like to transpose the kWh column so that one day's worth of values (hourly granularity, so 24 values/day) fill up a row.  And the next row is the next day of values and so on (so five days of forecasted data has five rows with 24 elements each).

Because my query of the data comes in the vertical format, and my regression and subsequent analysis already occurs in the vertical format, I don't want to change the process too much and am hoping there is a simpler way.  I have tried giving a multi-index with df.index.hour and then using unstack(), but I get a huge dataframe with NaN values everywhere.

Is there an elegant way to do this?

Body:
If we start from a frame like

In [25]: df = pd.DataFrame({"kWh": [1]}, index=pd.date_range("2017-07-08",
             "2017-07-12", freq="1H").rename("Timestamp")).cumsum()

In [26]: df.head()
Out[26]:
                     kWh
Timestamp
2017-07-08 00:00:00    1
2017-07-08 01:00:00    2
2017-07-08 02:00:00    3
2017-07-08 03:00:00    4
2017-07-08 04:00:00    5

we can make date and hour columns and then pivot:

In [27]: df["date"] = df.index.date

In [28]: df["hour"] = df.index.hour

In [29]: df.pivot(index="date", columns="hour", values="kWh")
Out[29]:
hour          0     1     2     3     4     5     6     7     8     9   ...   \
date                                                                    ...
2017-07-08   1.0   2.0   3.0   4.0   5.0   6.0   7.0   8.0   9.0  10.0  ...
2017-07-09  25.0  26.0  27.0  28.0  29.0  30.0  31.0  32.0  33.0  34.0  ...
2017-07-10  49.0  50.0  51.0  52.0  53.0  54.0  55.0  56.0  57.0  58.0  ...
2017-07-11  73.0  74.0  75.0  76.0  77.0  78.0  79.0  80.0  81.0  82.0  ...
2017-07-12  97.0   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  ...

hour          14    15    16    17    18    19    20    21    22    23
date
2017-07-08  15.0  16.0  17.0  18.0  19.0  20.0  21.0  22.0  23.0  24.0
2017-07-09  39.0  40.0  41.0  42.0  43.0  44.0  45.0  46.0  47.0  48.0
2017-07-10  63.0  64.0  65.0  66.0  67.0  68.0  69.0  70.0  71.0  72.0
2017-07-11  87.0  88.0  89.0  90.0  91.0  92.0  93.0  94.0  95.0  96.0
2017-07-12   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN

[5 rows x 24 columns]


问:
Xcode UIView for every link that is clicked
Hi

I want to create an app that displays a web site and to be able to open the link in a new session of the UIView every time a user clicks on a link.

I need it to act like that because i want to create an effect whenever the UIView loads and i don't want to create tons of UIView for all of the pages.

Actually, i already displayed a website with the uiview but i cant control how the uiview appears after a link is selected and i cant change the site code.

Does anyone know how to do it inside a tab bar app on xcode?

Thanks

答: I know if you use UIWebViewDelegate and the methods appropriately to stop the link loading and open the link in a new View.</p>

ContentLicense: CC BY-SA 2.5


答:
No need to over-complicate it with JavaScript. Just toggle CSS classes:

HTML

```<code><div id="container">
  <div id="close">X</div>
  lorem ipsum dolor sit amet
</div>
</code>```

CSS

```<code>#container {
  position: fixed;
  bottom: 0%;
  background-color: #f0ad4e;
  color: #000;
  padding: 10px 0;
  font-size: 20px;
  width: 100%;
  cursor: pointer;
  transition: all 0.5s ease-out;
}

#container.up {
  bottom: 20%;
}

#container.down {
  bottom: -100%;
}

#container.up #close {
  display: block;
}

#close {
  display: none;
}
</code>```

JS

```<code>var $container = $('#container')
var $close = $('#close')

$container.click(() => $container.addClass('up'))
$close.click(() => $container.addClass('down'))
</code>```

JSFiddle demo: https://jsfiddle.net/fq7na1zr/3/

Title: jQuery Animate not behaving as expected

Body:
No need to over-complicate it with JavaScript. Just toggle CSS classes:

HTML

<div id="container">
  <div id="close">X</div>
  lorem ipsum dolor sit amet
</div>

CSS

#container {
  position: fixed;
  bottom: 0%;
  background-color: #f0ad4e;
  color: #000;
  padding: 10px 0;
  font-size: 20px;
  width: 100%;
  cursor: pointer;
  transition: all 0.5s ease-out;
}

#container.up {
  bottom: 20%;
}

#container.down {
  bottom: -100%;
}

#container.up #close {
  display: block;
}

#close {
  display: none;
}

JS

var $container = $('#container')
var $close = $('#close')

$container.click(() => $container.addClass('up'))
$close.click(() => $container.addClass('down'))

JSFiddle demo: https://jsfiddle.net/fq7na1zr/3/


问:
Chatbot for XMPP based UC system
I've developed my own chat application using XMPP protocol, in this application I want to make a bot user for auto reply.So any suggested open source chat bot framework which can be used for it and what should be the best bot based application architecture?</p>

答: For Java, many people use Smack. I'd recommend checking that out.</p>

Title: Chatbot for XMPP based UC system


问:
Is it possible to have php and .htaccess authentication through one form?
I am using both PHP and .htaccess login systems on my website.Both authentications are handled seperately(i.e php by quering database and .htaccess by including password file in root directories). PHP login directs user to the specific page and .htaccess login directs user to a specific directory that includes subdirectories and various files. As per current situation if a user wants to access directories he is required to login twice. First login directs him to a page where he finds a link and clicking on the link again prompts him to enter username and password and directs him to the directory.

Is there a way that would simplify the two authentication problem and make it one. I mean the login system should work in such a way whereif user A logs in he will be directed to the page, and if user B logs through the same login he should be directed to the directories?

Any help would be highly appreciated.

答:
You can try to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string basic username:password, but with the username:password portion encoded via base64_encode. Source

However, this seems like a bad design imo. Are both scripts on the same server, if yes, then they can access the same resources from the backend.

Another option you can do is switch the protection to use php: http://php.net/manual/en/features.http-auth.php


问:
I'm creating a table in in which the data is being gotten from a JSON file. this is the code
```<code>var myObj, i, t = document.querySelector("#data_table");

myObj = {
name: "John",
age: 30,
cars: [
{name: "Ford", models: ["Fiesta", "Focus", "Mustang"]},
{name: "BMW", models: ["320", "X3", "X5"]},
{name: "Fiat", models: ["500", "Panda"]}
]

};

for (i in myObj.cars) {
var _row = t.insertRow(-1);

var c = _row.insertCell(-1);
c.innerHTML = myObj.cars[i].name;
c.style.fontWeight = "bolder";

for (var j = 0; j < myObj.cars[i].models.length; j++) {
var _c = _row.insertCell(-1);
_c.innerHTML = myObj.cars[i].models[j];
}
}
</code>```

my problem now is the name of the cars are appear on in a single column instead of a row (e.g they should be the table header for each column). but i havent been able to figure it out. your help would be appreciated.

This is the html

```<code><table width='100%' id='data_table' class="table table-condensed table-hover">
<caption> VEHICLE DATA </caption>

</table>
</code>```

A link of what it looks like now
enter image description here

But this is what i want it to look like
enter image description here

答:
Hi try this it would work.

```<code>var myObj, i, t = document.querySelector("#data_table");

myObj = {
    name: "John",
    age: 30,
    cars: [{
            name: "Ford",
            models: ["Fiesta", "Focus", "Mustang"]
        },
        {
            name: "BMW",
            models: ["320", "X3", "X5"]
        },
        {
            name: "Fiat",
            models: ["500", "Panda"]
        }
    ]

};

//Determine the max rows to draw (except the header) in the table
var rowCount = 0;
for (i in myObj.cars) {
    if (myObj.cars[i].models.length > rowCount) {
        rowCount = myObj.cars[i].models.length;
    }
}
//Add header row
var headerRow = t.insertRow(-1);
for (i in myObj.cars) {
    var c = headerRow.insertCell(-1);
    c.innerHTML = myObj.cars[i].name;
    c.style.fontWeight = "bolder";
}

//Add details rows and cells
for (var j = 0; j < rowCount; j++) {
    var _row = t.insertRow(-1);

    //Add cells for each row
    for (i in myObj.cars) {
        var _c = _row.insertCell(i);
        if (myObj.cars[i].models[j]) {
            _c.innerHTML = myObj.cars[i].models[j];
        }

    }

}
</code>```

Body:
var myObj, i, t = document.querySelector("#data_table");

myObj = {
name: "John",
age: 30,
cars: [
{name: "Ford", models: ["Fiesta", "Focus", "Mustang"]},
{name: "BMW", models: ["320", "X3", "X5"]},
{name: "Fiat", models: ["500", "Panda"]}
]

};

for (i in myObj.cars) {
var _row = t.insertRow(-1);

var c = _row.insertCell(-1);
c.innerHTML = myObj.cars[i].name;
c.style.fontWeight = "bolder";

for (var j = 0; j < myObj.cars[i].models.length; j++) {
var _c = _row.insertCell(-1);
_c.innerHTML = myObj.cars[i].models[j];
}
}

my problem now is the name of the cars are appear on in a single column instead of a row (e.g they should be the table header for each column). but i havent been able to figure it out. your help would be appreciated.

This is the html

 VEHICLE DATA

A link of what it looks like now
enter image description here

But this is what i want it to look like
enter image description here

Body:
Hi try this it would work.

var myObj, i, t = document.querySelector("#data_table");

myObj = {
    name: "John",
    age: 30,
    cars: [{
            name: "Ford",
            models: ["Fiesta", "Focus", "Mustang"]
        },
        {
            name: "BMW",
            models: ["320", "X3", "X5"]
        },
        {
            name: "Fiat",
            models: ["500", "Panda"]
        }
    ]

};

//Determine the max rows to draw (except the header) in the table
var rowCount = 0;
for (i in myObj.cars) {
    if (myObj.cars[i].models.length > rowCount) {
        rowCount = myObj.cars[i].models.length;
    }
}
//Add header row
var headerRow = t.insertRow(-1);
for (i in myObj.cars) {
    var c = headerRow.insertCell(-1);
    c.innerHTML = myObj.cars[i].name;
    c.style.fontWeight = "bolder";
}

//Add details rows and cells
for (var j = 0; j < rowCount; j++) {
    var _row = t.insertRow(-1);

    //Add cells for each row
    for (i in myObj.cars) {
        var _c = _row.insertCell(i);
        if (myObj.cars[i].models[j]) {
            _c.innerHTML = myObj.cars[i].models[j];
        }

    }

}


问:
Receipt printer?
I am developing a software which require to print receipts.

What is the most common type of receipt printer?

Are there any industry standards for receipt printer API?

Are there any .net library for that? Tried to find but didn't find anything.

答:
UnifiedPOS is the most common API today for communicating with Point-Of-Sale peripherals including receipt printers: http://www.nrf-arts.org/UnifiedPOS/default.htm.

Microsoft have an implementation for .NET: http://msdn.microsoft.com/en-us/library/ms828083.aspx.

UnifiedPOS evolved from OPOS (OLE for Retail POS), so google for OPOS for more info.  You will find more peripheral manufacturers support OPOS than other flavors of UnifiedPOS.  Microsoft's POS for .NET will work with OPOS V1.8 Service objects.

OwnerDisplayName: mamu

Title: Receipt printer?

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Joe

LastEditorDisplayName: Joe


问:
replace line in a file C++
I'm trying to find a way to replace a line, containing a string, in a file with a new line.

If the string is not present in the file, then append it to the file.

Can someone give a sample code?

EDIT : is there anyway if the line that i need to replace is at the end of the file?

答:
If you want to change the length of (or delete) a line in the middle of a file, you will have to re-write all the subsequent lines.

There's no way of simply deleting or inserting characters into an existing file.

Title: replace line in a file C++


问:
Docker Connecting PHP container to MySQL
I have two containers, a apache-php container, and a mysql db container.
I am trying to get my php script to query my sql database.
I am however receiving the following errors;

```<code>Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known
</code>```

AND

```<code>Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory
</code>```

when toggling the host address, i think i am missing something fundamental to docker and this is driving my crazy.

My docker compose looks like;

```<code>version: '2'

services:

    applications:
      image: tianon/true
      volumes:
        - /var/www/test:/var/www/html

    mysql_store:
      image: tianon/true
      volumes:
        - /var/www/test/mysql:/var/lib/mysql

    apache2:
      build:
        context: ./apache2
      volumes_from:
        - applications
      ports:
        - "80:80"
      depends_on:
       - mysql
      links:
        - mysql
    mysql:
      build:
        context: ./mysql
        volumes_from:
          - mysql_store
      environment:
        - MYSQL_DATABASE=testapp
        - MYSQL_USER=johnm
        - MYSQL_PASSWORD=johnm
        - MYSQL_ROOT_PASSWORD=secret
      volumes:
        - ./mysql/save:/var/lib/mysql
      ports:
        - "3306:3306"
</code>```

my mysql dockerfile looks like

```<code>FROM mysql:8

MAINTAINER Mahmoud Zalt <mahmoud@zalt.me>

#####################################
# Set Timezone
#####################################

ARG TZ=UTC
ENV TZ ${TZ}
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

RUN chown -R mysql:root /var/lib/mysql/

ADD my.cnf /etc/mysql/conf.d/my.cnf

CMD ["mysqld"]

EXPOSE 3306
</code>```

my apache dockerfile looks like;

```<code>FROM php:7.0-apache
#COPY ./src/ /var/www/html/i
#RUN apt-get update && add-apt-repository ppa:ondrej/php && apt-get update && apt-get install php7.0-mysql
RUN apt-get update && apt-get install -y \
    && docker-php-ext-install pdo pdo_mysql \
    && docker-php-ext-enable pdo pdo_mysql
</code>```

and finally my index.php looks like

```<code><?php
    $db = new PDO('mysql:host=localhost;port=3306;dbname=testapp', 'root', 'secret');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    var_dump($db->query('SELECT * from users'));
</code>```

For my database host i have tried "db", "localhost" and "127.0.0.1".

Any help on this will be greatly appreciated!

答:
What you need to use as DNS name is the service name: mysql:

```<code> $db = new PDO('mysql:host=mysql;port=3306;dbname=testapp', 'root', 'secret');
</code>```

Because you named as so the MySQL compose service:

```<code>    mysql:
      build:
        context: ./mysql
...
</code>```

Body:
I have two containers, a apache-php container, and a mysql db container.
I am trying to get my php script to query my sql database.
I am however receiving the following errors;

Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known

AND

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory

when toggling the host address, i think i am missing something fundamental to docker and this is driving my crazy.

My docker compose looks like;

version: '2'

services:

    applications:
      image: tianon/true
      volumes:
        - /var/www/test:/var/www/html

    mysql_store:
      image: tianon/true
      volumes:
        - /var/www/test/mysql:/var/lib/mysql

    apache2:
      build:
        context: ./apache2
      volumes_from:
        - applications
      ports:
        - "80:80"
      depends_on:
       - mysql
      links:
        - mysql
    mysql:
      build:
        context: ./mysql
        volumes_from:
          - mysql_store
      environment:
        - MYSQL_DATABASE=testapp
        - MYSQL_USER=johnm
        - MYSQL_PASSWORD=johnm
        - MYSQL_ROOT_PASSWORD=secret
      volumes:
        - ./mysql/save:/var/lib/mysql
      ports:
        - "3306:3306"

my mysql dockerfile looks like

FROM mysql:8

MAINTAINER Mahmoud Zalt <mahmoud@zalt.me>

#####################################
# Set Timezone
#####################################

ARG TZ=UTC
ENV TZ ${TZ}
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

RUN chown -R mysql:root /var/lib/mysql/

ADD my.cnf /etc/mysql/conf.d/my.cnf

CMD ["mysqld"]

EXPOSE 3306

my apache dockerfile looks like;

FROM php:7.0-apache
#COPY ./src/ /var/www/html/i
#RUN apt-get update && add-apt-repository ppa:ondrej/php && apt-get update && apt-get install php7.0-mysql
RUN apt-get update && apt-get install -y \
    && docker-php-ext-install pdo pdo_mysql \
    && docker-php-ext-enable pdo pdo_mysql

and finally my index.php looks like

<?php
    $db = new PDO('mysql:host=localhost;port=3306;dbname=testapp', 'root', 'secret');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    var_dump($db->query('SELECT * from users'));

For my database host i have tried "db", "localhost" and "127.0.0.1".

Any help on this will be greatly appreciated!

Body:
What you need to use as DNS name is the service name: mysql:

 $db = new PDO('mysql:host=mysql;port=3306;dbname=testapp', 'root', 'secret');

Because you named as so the MySQL compose service:

    mysql:
      build:
        context: ./mysql
...


问:
How correctly give vector from function (type_traits)
How can I return std::vector from this operator+()?

```<code>#include <iostream>
#include <vector>
#include <type_traits>
#include <algorithm>
#include <utility>

template<typename> struct is_std_vector :  std::false_type {};
template<typename T, typename A> struct is_std_vector<std::vector<T, A>> :  std::true_type {};
template <typename T>
std::enable_if_t<is_std_vector<std::decay_t<T>>::value>
operator+(T&& vec1, T&& vec2)
{
    for (int i = 0; i < vec2.size(); ++i)
        vec1.emplace_back(std::forward<int>(vec2.at(i)));
    return vec1;
}

int main()
{
    std::vector<int> vec1{ 1,2,3,4,5 };
    std::vector<int> vec2{ 2,3,4,5,6 };
    std::vector<int> vecResult;
    vecResult = std::move(vec1) + std::move(vec2);
    for (const auto& itr : vecResult)
        std::cout << itr << std::endl;
    return 0;
}
</code>```

now function return void, but i don't know why, i want give std::vector as forward reference to operator+(T&& vec1, T&& vec2) and return std::vector. I think that is good, but compiler know better. Some suggestions?

error compiler

C2679 binary '=': no operator found which takes a right-hand operand
  of type 'void' (or there is no acceptable conversion)

答:
The problem is that the default type for std::enable_if_t, when the condition is true, is void.

So, instead of returning void

```<code>std::enable_if_t<is_std_vector<std::decay_t<T>>::value>
   operator+(T&& vec1, T&& vec2)
</code>```

I suppose you should returning T or something similar

```<code>std::enable_if_t<is_std_vector<std::decay_t<T>>::value, T>
   operator+(T&& vec1, T&& vec2)
</code>```

Body:
How can I return std::vector from this operator+()?

#include <iostream>
#include <vector>
#include <type_traits>
#include <algorithm>
#include <utility>

template<typename> struct is_std_vector :  std::false_type {};
template<typename T, typename A> struct is_std_vector<std::vector<T, A>> :  std::true_type {};
template <typename T>
std::enable_if_t<is_std_vector<std::decay_t<T>>::value>
operator+(T&& vec1, T&& vec2)
{
    for (int i = 0; i < vec2.size(); ++i)
        vec1.emplace_back(std::forward<int>(vec2.at(i)));
    return vec1;
}

int main()
{
    std::vector<int> vec1{ 1,2,3,4,5 };
    std::vector<int> vec2{ 2,3,4,5,6 };
    std::vector<int> vecResult;
    vecResult = std::move(vec1) + std::move(vec2);
    for (const auto& itr : vecResult)
        std::cout << itr << std::endl;
    return 0;
}

now function return void, but i don't know why, i want give std::vector as forward reference to operator+(T&& vec1, T&& vec2) and return std::vector. I think that is good, but compiler know better. Some suggestions?

error compiler

C2679 binary '=': no operator found which takes a right-hand operand
  of type 'void' (or there is no acceptable conversion)

Body:
The problem is that the default type for std::enable_if_t, when the condition is true, is void.

So, instead of returning void

std::enable_if_t<is_std_vector<std::decay_t<T>>::value>
   operator+(T&& vec1, T&& vec2)

I suppose you should returning T or something similar

std::enable_if_t<is_std_vector<std::decay_t<T>>::value, T>
   operator+(T&& vec1, T&& vec2)


问:
How to get values from this JSON using Alamofire swift 3
I'm trying to get values from this JSON. This is part of the JSON because the real JSON data is too long.

```<code>"hits" : [ {
"recipe" : {
  "uri" : "http://www.edamam.com/ontologies/edamam.owl#recipe_bd8def1d09d8c308f659e6945f366271",
  "label" : "Pinchos de carne",
  "image" : "http://img.recetascomidas.com/recetas/640_480/pinchos-de-carne.jpg",
  "source" : "Recetal Comidas",
  "url" : "http://pinchos-de-carne.recetascomidas.com/",
  "shareAs" : "http://www.edamam.com/recipe/pinchos-de-carne-bd8def1d09d8c308f659e6945f366271/carne",
  "yield" : 6.0,
  "dietLabels" : [ "Low-Carb" ],
  "healthLabels" : [ "Dairy-Free", "Gluten-Free", "Egg-Free", "Peanut-Free", "Tree-Nut-Free", "Soy-Free", "Fish-Free", "Shellfish-Free" ],
  "cautions" : [ ],
  "ingredientLines" : [ "600 gr. de carne magra de cerdo", "2 cucharadas de pimentón dulce", "1 cucharada de pimentón picante", "1 cucharada de cúrcuma", "1 cucharada de sazonador especial para carnes", "3 cucharadas de perejil fresco bien picadito", "1/2 cucharada de comino", "Aceite de oliva", "3 patatas", "1 diente de ajo", "Pimienta negra", "Sal" ],
  "ingredients" : [ {
    "text" : "600 gr. de carne magra de cerdo",
    "quantity" : 600.0,
    "measure" : null,
    "food" : "carne magra cerdo",
    "weight" : 600.0
  }, {
    "text" : "2 cucharadas de pimentón dulce",
    "quantity" : 2.0,
    "measure" : "tbsp",
    "food" : "pimenton dulce",
    "weight" : 13.6
  }, {
    "text" : "1 cucharada de pimentón picante",
    "quantity" : 1.0,
    "measure" : "tbsp",
    "food" : "pimenton picante",
    "weight" : 6.8
  }, {
    "text" : "1 cucharada de cúrcuma",
    "quantity" : 1.0,
    "measure" : "tbsp",
    "food" : "curcuma",
    "weight" : 6.8
  }, {
    "text" : "1 cucharada de sazonador especial para carnes",
    "quantity" : 1.0,
    "measure" : "tbsp",
    "food" : "sazonador",
    "weight" : 2.7
  }, {
    "text" : "3 cucharadas de perejil fresco bien picadito",
    "quantity" : 3.0,
    "measure" : "tbsp",
    "food" : "perejil fresco",
    "weight" : 11.4
  }, {
    "text" : "1/2 cucharada de comino",
    "quantity" : 0.5,
    "measure" : "tbsp",
    "food" : "comino",
    "weight" : 3.0
  }, {
    "text" : "Aceite de oliva",
    "quantity" : 2.0,
    "measure" : "tbsp",
    "food" : "aceite oliva",
    "weight" : 27.0
  }, {
    "text" : "3 patatas",
    "quantity" : 3.0,
    "measure" : null,
    "food" : "patatas",
    "weight" : 195.0
  }, {
    "text" : "1 diente de ajo",
    "quantity" : 1.0,
    "measure" : null,
    "food" : "ajo",
    "weight" : 3.0
  }, {
    "text" : "Pimienta negra",
    "quantity" : 1.0,
    "measure" : "peppercorn",
    "food" : "pimienta negra",
    "weight" : 0.3
  }, {
    "text" : "Sal",
    "quantity" : 0.0,
    "measure" : null,
    "food" : "sal",
    "weight" : 3.3346887
  } ]
</code>```

For example, I want to get label values that is inside "recipe". I successfully print in console all the JSON, but I don't know how to get recipe values.

I hope you can help me.

This is the code I have now.

```<code>let url: String = "https://test-es.edamam.com/search?q=pollo"
var arregloHits: NSMutableArray = []

override func viewDidLoad() {
    super.viewDidLoad()

    pruebaJson()
}

func pruebaJson(){
    if ControladorService.conexionInternet(){
        ControladorService.sharedInstance.callUrlWithCompletion(url: url, params: nil, completion: { (finished, response) in
            if finished{
                let result = NSMutableArray(array: response["hits"] as! NSArray)

                self.arregloHits = result
                print(self.arregloHits)
            }else{
                print("Connection failed")
            }
        }, method: .get)
    }else{
        print("No Internet")
    }
}
</code>```

答:
Your top level json structure is a dictionary. So you need to parse it into [String: Any]. Then your hints level is a JSON array, so you need to parse it into [Any]

Here is an example. Don't forget to handle unwrap

```<code>do{
    let json = try JSONSerialization.jsonObject(with: yourJSONData, options: []) as? [String: Any]

    let hits = json?["hits"] as? [Any]
    dump(hits)
}catch let error{

}
</code>```

Body:
I'm trying to get values from this JSON. This is part of the JSON because the real JSON data is too long.

"hits" : [ {
"recipe" : {
  "uri" : "http://www.edamam.com/ontologies/edamam.owl#recipe_bd8def1d09d8c308f659e6945f366271",
  "label" : "Pinchos de carne",
  "image" : "http://img.recetascomidas.com/recetas/640_480/pinchos-de-carne.jpg",
  "source" : "Recetal Comidas",
  "url" : "http://pinchos-de-carne.recetascomidas.com/",
  "shareAs" : "http://www.edamam.com/recipe/pinchos-de-carne-bd8def1d09d8c308f659e6945f366271/carne",
  "yield" : 6.0,
  "dietLabels" : [ "Low-Carb" ],
  "healthLabels" : [ "Dairy-Free", "Gluten-Free", "Egg-Free", "Peanut-Free", "Tree-Nut-Free", "Soy-Free", "Fish-Free", "Shellfish-Free" ],
  "cautions" : [ ],
  "ingredientLines" : [ "600 gr. de carne magra de cerdo", "2 cucharadas de pimentón dulce", "1 cucharada de pimentón picante", "1 cucharada de cúrcuma", "1 cucharada de sazonador especial para carnes", "3 cucharadas de perejil fresco bien picadito", "1/2 cucharada de comino", "Aceite de oliva", "3 patatas", "1 diente de ajo", "Pimienta negra", "Sal" ],
  "ingredients" : [ {
    "text" : "600 gr. de carne magra de cerdo",
    "quantity" : 600.0,
    "measure" : null,
    "food" : "carne magra cerdo",
    "weight" : 600.0
  }, {
    "text" : "2 cucharadas de pimentón dulce",
    "quantity" : 2.0,
    "measure" : "tbsp",
    "food" : "pimenton dulce",
    "weight" : 13.6
  }, {
    "text" : "1 cucharada de pimentón picante",
    "quantity" : 1.0,
    "measure" : "tbsp",
    "food" : "pimenton picante",
    "weight" : 6.8
  }, {
    "text" : "1 cucharada de cúrcuma",
    "quantity" : 1.0,
    "measure" : "tbsp",
    "food" : "curcuma",
    "weight" : 6.8
  }, {
    "text" : "1 cucharada de sazonador especial para carnes",
    "quantity" : 1.0,
    "measure" : "tbsp",
    "food" : "sazonador",
    "weight" : 2.7
  }, {
    "text" : "3 cucharadas de perejil fresco bien picadito",
    "quantity" : 3.0,
    "measure" : "tbsp",
    "food" : "perejil fresco",
    "weight" : 11.4
  }, {
    "text" : "1/2 cucharada de comino",
    "quantity" : 0.5,
    "measure" : "tbsp",
    "food" : "comino",
    "weight" : 3.0
  }, {
    "text" : "Aceite de oliva",
    "quantity" : 2.0,
    "measure" : "tbsp",
    "food" : "aceite oliva",
    "weight" : 27.0
  }, {
    "text" : "3 patatas",
    "quantity" : 3.0,
    "measure" : null,
    "food" : "patatas",
    "weight" : 195.0
  }, {
    "text" : "1 diente de ajo",
    "quantity" : 1.0,
    "measure" : null,
    "food" : "ajo",
    "weight" : 3.0
  }, {
    "text" : "Pimienta negra",
    "quantity" : 1.0,
    "measure" : "peppercorn",
    "food" : "pimienta negra",
    "weight" : 0.3
  }, {
    "text" : "Sal",
    "quantity" : 0.0,
    "measure" : null,
    "food" : "sal",
    "weight" : 3.3346887
  } ]

For example, I want to get label values that is inside "recipe". I successfully print in console all the JSON, but I don't know how to get recipe values.

I hope you can help me.

This is the code I have now.

let url: String = "https://test-es.edamam.com/search?q=pollo"
var arregloHits: NSMutableArray = []

override func viewDidLoad() {
    super.viewDidLoad()

    pruebaJson()
}

func pruebaJson(){
    if ControladorService.conexionInternet(){
        ControladorService.sharedInstance.callUrlWithCompletion(url: url, params: nil, completion: { (finished, response) in
            if finished{
                let result = NSMutableArray(array: response["hits"] as! NSArray)

                self.arregloHits = result
                print(self.arregloHits)
            }else{
                print("Connection failed")
            }
        }, method: .get)
    }else{
        print("No Internet")
    }
}

Body:
Your top level json structure is a dictionary. So you need to parse it into [String: Any]. Then your hints level is a JSON array, so you need to parse it into [Any]

Here is an example. Don't forget to handle unwrap

do{
    let json = try JSONSerialization.jsonObject(with: yourJSONData, options: []) as? [String: Any]

    let hits = json?["hits"] as? [Any]
    dump(hits)
}catch let error{

}


答:
```<code> event.stopPropagation();
</code>```

will solve your problem. Because you click on the #close div and the #container div too. With event.stopPropagation(); you prevent calling the event listener for the #container div.

Title: jQuery Animate not behaving as expected

Body:
 event.stopPropagation();

will solve your problem. Because you click on the #close div and the #container div too. With event.stopPropagation(); you prevent calling the event listener for the #container div.


问:
Client side vs server side logic
I am trying to develop a website but I am confused about where to put my logic.
Scenario: I want to update the list of items based on the filters selected by user. Example: https://www.zillow.com . When user selects price range or home type etc, the list of houses gets updated.

So my question is should I make a network call everytime user selects a filter or pull all the items in the list and filter on the client side.
I am using Angular 4 for web development.

My concerns are:

what if we have slower networks so the server side would not be that efficient.

for mobile devices I don't think we should pull all the data in the device memory.

The items in the list would be in 1000s and item would be an object of 4 strings and 1 image.

答: 1000+ items are way too much for a single request, and the performance sure would be a problem for mobile devices. Do the filtering logic on the server and return only a small portion of the results (pagination). You would have more requests, but a slow network sure would have more problems with a gigantic initial request than one or more small ones.</p>

Title: Client side vs server side logic


Title: Transposing dataframe column, creating different rows per day

Body:
Not sure why your MultiIndex code doesn't work.
I'm assuming your MultiIndex code is something along the lines, which gives the same output as the pivot:

In []
df = pd.DataFrame({"kWh": [1]}, index=pd.date_range("2017-07-08",
                   "2017-07-12", freq="1H").rename("Timestamp")).cumsum()
df.index = pd.MultiIndex.from_arrays([df.index.date, df.index.hour], names=['Date','Hour'])
df.unstack()

Out[]:
             kWh                                                        ...   \
Hour          0     1     2     3     4     5     6     7     8     9   ...
Date                                                                    ...
2017-07-08   1.0   2.0   3.0   4.0   5.0   6.0   7.0   8.0   9.0  10.0  ...
2017-07-09  25.0  26.0  27.0  28.0  29.0  30.0  31.0  32.0  33.0  34.0  ...
2017-07-10  49.0  50.0  51.0  52.0  53.0  54.0  55.0  56.0  57.0  58.0  ...
2017-07-11  73.0  74.0  75.0  76.0  77.0  78.0  79.0  80.0  81.0  82.0  ...
2017-07-12  97.0   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN  ...

Hour          14    15    16    17    18    19    20    21    22    23
Date
2017-07-08  15.0  16.0  17.0  18.0  19.0  20.0  21.0  22.0  23.0  24.0
2017-07-09  39.0  40.0  41.0  42.0  43.0  44.0  45.0  46.0  47.0  48.0
2017-07-10  63.0  64.0  65.0  66.0  67.0  68.0  69.0  70.0  71.0  72.0
2017-07-11  87.0  88.0  89.0  90.0  91.0  92.0  93.0  94.0  95.0  96.0
2017-07-12   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN

[5 rows x 24 columns]


问:
Saving all Inputs entered for display on cout - C++
I have looked in the forum but can't seem to find anything specific to what I need.

I am writing a program that asks the user to input a number of students. Depending on the number of students they enter they will then have to enter the students name and a series of 10 grades, or pressing 999 to cancel. The program will later have to display all students entered with their average grade. What I have now just overrides the previous inputs and displays the last one entered.

This is what I have so far:

```<code>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

int main() {

std::string teacherName = "";
std::string classDesignation ="";
int numStudents = 0;
std::string studentName = "";
double grade[10];
double  averageGrade = 0.00;
char letterGrade;

std::cout << "Enter the teacher's name: ";
getline(std::cin, teacherName);

std::cout << "Enter the class designation: ";
getline(std::cin, classDesignation);

std::cout << "Enter the number of students ( 1 or more ): ";
std::cin >> numStudents;
std::cin.ignore();

for (int x = 0; x <= numStudents - 1; x++) {
    std::cout << "Enter the student's name: ";
    getline(std::cin, studentName);

    for (int i = 0; i <= 9; i++) {
        std::cout << "Enter grade from 0 - 100 or 999 to stop: ";
        std::cin >> grade[i];

        if (grade[i] == 999){
            break;
    }
        averageGrade += grade[i];

        if (averageGrade <= 59){
            letterGrade = 'F';
        }
        if (averageGrade >= 60 || averageGrade <= 69){
            letterGrade = 'D';
        }
        if (averageGrade >= 70 || averageGrade <= 79){
            letterGrade = 'C';
        }
        if (averageGrade >= 80 || averageGrade <= 89){
            letterGrade = 'B';
        }
        if (averageGrade > 90){
            letterGrade = 'A';
        }
    }
}

std::cout << "Teacher: " << teacherName << std::endl;
std::cout << "Class: " << classDesignation << std::endl;
std::cout << "Student Name: " << studentName;
std::cout << std::setw(19) << "Average: " << averageGrade;
std::cout << " Grade: " << letterGrade << std::endl;
std::cout << "Student count: " << numStudents << std::endl;
std::cout << "Student average: " << std::endl;
std::cout << "A's: " << std::endl;
std::cout << "B's: " << std::endl;
std::cout << "C's: " << std::endl;
std::cout << "D's: " << std::endl;
std::cout << "F's: " << std::endl;

return 0;
}
</code>```

Any tips?

Thank you!

答:
@Hansel, here's what I think will work.  We'll change this line to get what we want:

```<code>averageGrade += grade[i];
</code>```

To:

```<code>//to declarations:
double  averageGradeSum = 0.00;
//then change the line mentioned before to:
averageGradeSum += grade[i];
</code>```

Then:

```<code>//if for some reason you're indexing starts at 1
averageGrade = averageGradeSum/i;
//if indexing starts at 0 like usual C++ use:
averageGrade = averageGradeSum/(i+1);
</code>```

I'm not going to test this.  It should make sense and if I screwed up the syntax it should be an easy google adventure to fix.  Enjoy :)

Body:
I have looked in the forum but can't seem to find anything specific to what I need.

I am writing a program that asks the user to input a number of students. Depending on the number of students they enter they will then have to enter the students name and a series of 10 grades, or pressing 999 to cancel. The program will later have to display all students entered with their average grade. What I have now just overrides the previous inputs and displays the last one entered.

This is what I have so far:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

int main() {

std::string teacherName = "";
std::string classDesignation ="";
int numStudents = 0;
std::string studentName = "";
double grade[10];
double  averageGrade = 0.00;
char letterGrade;

std::cout << "Enter the teacher's name: ";
getline(std::cin, teacherName);

std::cout << "Enter the class designation: ";
getline(std::cin, classDesignation);

std::cout << "Enter the number of students ( 1 or more ): ";
std::cin >> numStudents;
std::cin.ignore();

for (int x = 0; x <= numStudents - 1; x++) {
    std::cout << "Enter the student's name: ";
    getline(std::cin, studentName);

    for (int i = 0; i <= 9; i++) {
        std::cout << "Enter grade from 0 - 100 or 999 to stop: ";
        std::cin >> grade[i];

        if (grade[i] == 999){
            break;
    }
        averageGrade += grade[i];

        if (averageGrade <= 59){
            letterGrade = 'F';
        }
        if (averageGrade >= 60 || averageGrade <= 69){
            letterGrade = 'D';
        }
        if (averageGrade >= 70 || averageGrade <= 79){
            letterGrade = 'C';
        }
        if (averageGrade >= 80 || averageGrade <= 89){
            letterGrade = 'B';
        }
        if (averageGrade > 90){
            letterGrade = 'A';
        }
    }
}

std::cout << "Teacher: " << teacherName << std::endl;
std::cout << "Class: " << classDesignation << std::endl;
std::cout << "Student Name: " << studentName;
std::cout << std::setw(19) << "Average: " << averageGrade;
std::cout << " Grade: " << letterGrade << std::endl;
std::cout << "Student count: " << numStudents << std::endl;
std::cout << "Student average: " << std::endl;
std::cout << "A's: " << std::endl;
std::cout << "B's: " << std::endl;
std::cout << "C's: " << std::endl;
std::cout << "D's: " << std::endl;
std::cout << "F's: " << std::endl;

return 0;
}

Any tips?

Thank you!

Body:
@Hansel, here's what I think will work.  We'll change this line to get what we want:

averageGrade += grade[i];

To:

//to declarations:
double  averageGradeSum = 0.00;
//then change the line mentioned before to:
averageGradeSum += grade[i];

Then:

//if for some reason you're indexing starts at 1
averageGrade = averageGradeSum/i;
//if indexing starts at 0 like usual C++ use:
averageGrade = averageGradeSum/(i+1);

I'm not going to test this.  It should make sense and if I screwed up the syntax it should be an easy google adventure to fix.  Enjoy :)


问:
Python XPath returns empty list?
I am trying to scrape information from this webpage.

Here is a screenshot should the webpage not work.

I am trying to print the text in the first  element.

I copied the XPath as provided by the Inspect Element view in Google Chrome (see screenshot above), and

//*[@id="main"]/div[1]/div/div/div[2]/p[1]/span[1]/text() was copied to my clipboard.

This is the code I tried:

```<code>from lxml import html
import requests

# get alert info
page = requests.get( 'https://www.msn.com/en-us/weather/weatheralerts/Beverly%20Hills,California,Unite%20d%20States/we-city?weadegreetype=F&day=1&ocid=ansmsnweather')
tree = html.fromstring(page.content)

alertInfo = tree.xpath( '//*[@id="main"]/div[1]/div/div/div[2]/p[1]/span[1]/text()')

print alertInfo
</code>```

However, all I got as an output was []. I am sure that the URL string is correct. Why did this occur?

I also tried alertInfo = tree.xpath( '//span/text()') to see if I could just pick out the element in the list, but even that returned an empty list.

Thanks.

答:
the problem is not with your xpath but rather with the way naughty msn replies to script requests. you may try to trick it as if you're a rel browser hence

if all you're looking is weather reports, I strongly advise getting away from parsing html pages (which is highly vulnerable to page structure changes) some services have great API for example accuweather or yahoo! weather

Title: Python XPath returns empty list?

Body:
I am trying to scrape information from this webpage.

Here is a screenshot should the webpage not work.

I am trying to print the text in the first  element.

I copied the XPath as provided by the Inspect Element view in Google Chrome (see screenshot above), and

//*[@id="main"]/div[1]/div/div/div[2]/p[1]/span[1]/text() was copied to my clipboard.

This is the code I tried:

from lxml import html
import requests

# get alert info
page = requests.get( 'https://www.msn.com/en-us/weather/weatheralerts/Beverly%20Hills,California,Unite%20d%20States/we-city?weadegreetype=F&day=1&ocid=ansmsnweather')
tree = html.fromstring(page.content)

alertInfo = tree.xpath( '//*[@id="main"]/div[1]/div/div/div[2]/p[1]/span[1]/text()')

print alertInfo

However, all I got as an output was []. I am sure that the URL string is correct. Why did this occur?

I also tried alertInfo = tree.xpath( '//span/text()') to see if I could just pick out the element in the list, but even that returned an empty list.

Thanks.


问:
How to get text from unmanaged application to a c# application?
I have a 3rd party application, which creates several windows of which each has a textbox with text I want. I then want to use that information within my application, so I just need to obtain that information (possible trigger some commands back to it later on by pressing buttons)

The 3rd party application is un-managed C++.
My application is C# (.NET 4.0).

I have seen that you can do 'hooks' into other application but I'll be honest I am completely lost of which route to take and how to go about it.

Some advice would be great.

答: The easiest interop with an unmanaged C++ is via C++/CLI. If there's already a simple C wrapper then P/Invoke will be sufficient.</p>


问:
Error while running python scripts/diff_drive.py --remote http://10.100.82.30 --config=diff_vehicle
Code snippet after running the $python scripts/diff_drive.py --remote http://10.100.82.30 --config=diff_vehicle

```<code>Detected running on rasberrypi. Only importing select modules.

Using TensorFlow backend.

Usage:

    drive.py [--remote=<name>] [--config=<name>]

Options:
  --remote=<name>   recording session name

  --config=<name>   vehicle configuration file name (without extension)

[default: diff_vehicle]
</code>```

I'm trying to build a differential Donkey Car. Using a Raspberry Pi3, Picam, and an ADAFRUIT Motor HAT for DC and Stepper motors.

答:
You are missing "=" in one of the argument. python getopt accepts values in name=value form

Try
$python scripts/diff_drive.py --remote=http://10.100.82.30 --config=diff_vehicle

Body:
Code snippet after running the $python scripts/diff_drive.py --remote http://10.100.82.30 --config=diff_vehicle

Detected running on rasberrypi. Only importing select modules.

Using TensorFlow backend.

Usage:

    drive.py [--remote=<name>] [--config=<name>]

Options:
  --remote=<name>   recording session name

  --config=<name>   vehicle configuration file name (without extension)

[default: diff_vehicle]

I'm trying to build a differential Donkey Car. Using a Raspberry Pi3, Picam, and an ADAFRUIT Motor HAT for DC and Stepper motors.


问:
Angular 2 Material Design Autocomplete search box
I got some issues on autocomplete on Angular2 Material Design which these are the things happened:

*When I type a character that is associated with the one I search it won't display on the autocomplete the specific character that I entered on the search textbox as shown in the picture below:

When before typing on the search box.

When after typing on the search box

The second one is that when I select a specific list on the list of users it seems that it will display the [object Object] thingy and I don't know why it happens. See the picture below:

When before selecting a employee on the list

When after selecting a employee on the list

Here is my code below see if there's something that I missed or what.

Angular Code: new-useraccount-components.ts

import { Component } from '@angular/core';
import { WebServiceComponents } from '../WebService/web.service';
import { FormControl } from '@angular/forms';

import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';

@Component({
    selector: 'new-user-account',
    template: `
              <md-card class="card-margin">
                <md-card-content>
                    <md-input-container>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [formControl]="UserAccountCtrl" />

                    </md-input-container>
                    <md-autocomplete #auto="mdAutocomplete">
                        <md-option *ngFor="let userAccount of filterUserAccount | async" [value]="userAccount">
                            {{userAccount.username}}
                        </md-option>
                    </md-autocomplete>
                    <md-input-container>
                        <input mdInput placeholder="Username" />

                    </md-input-container>
                </md-card-content>
              </md-card>
              `
})

export class NewUserAccountComponent{
    UserAccountCtrl: FormControl;
    filterUserAccount: any;

     async ngOnInit(){
        var response = await this.webService.getUserAccounts();
        this.userAccounts = response.json();
    }

    userAccounts = [];

    constructor(private webService : WebServiceComponents){
    this.UserAccountCtrl = new FormControl();
    this.filterUserAccount = this.UserAccountCtrl.valueChanges
        .startWith(null)
        .map(name => this.filteredUserAccount(name));
    }

    filteredUserAccount(val: string) {
    return val ? this.userAccounts.filter(s => new RegExp(`^${val}`, 'gi').test(s))
               : this.userAccounts;
  }
}```
</div>
</div>
</p>

<p><strong>AppModule:</strong> <em>app.module.ts</em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MaterialModule } from '@angular/material';
import { AppComponent }  from './app.component';
import { WebServiceComponents } from './WebService/web.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { UserAccountComponent } from './UserAccount/useraccount-components';
import { NewUserAccountComponent } from './UserAccount/new-useraccount-component';

@NgModule({
  imports:      [ BrowserModule, MaterialModule, ReactiveFormsModule, FormsModule ],
  declarations: [ AppComponent, UserAccountComponent, NewUserAccountComponent ],
  bootstrap:    [ AppComponent ],
  providers: [ WebServiceComponents ]
})
export class AppModule { }</code>```

Sorry I'm just a newbie trying to play with this new framework.  Hopefully someone will guide me on how to fix this issue.  Thank you and Have a wonderful day ahead!

答:
The docs are quite clear if you read them closely enough:

https://material.angular.io/components/autocomplete/overview

You'll be especially interested in what it has to say under the title "Setting separate control and display values". It is not displaying your search result because you want to display something different than the [value] you've specified.

The other problem you are having is that when selecting an item in the list the actual value of that item is inserted into the search box. Since this is a userAccount and not the username, [object Object] is displayed.

Simply changing to [value]="userAccount.username" could solve both your problems. If this does not give you the desired effect, you'll have to use the [displayWith] attribute as explained in the docs.

Body:
I got some issues on autocomplete on Angular2 Material Design which these are the things happened:

*When I type a character that is associated with the one I search it won't display on the autocomplete the specific character that I entered on the search textbox as shown in the picture below:

When before typing on the search box.

When after typing on the search box

The second one is that when I select a specific list on the list of users it seems that it will display the [object Object] thingy and I don't know why it happens. See the picture below:

When before selecting a employee on the list

When after selecting a employee on the list

Here is my code below see if there's something that I missed or what.

Angular Code: new-useraccount-components.ts

import { Component } from '@angular/core';
import { WebServiceComponents } from '../WebService/web.service';
import { FormControl } from '@angular/forms';

import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';

@Component({
    selector: 'new-user-account',
    template: `
              <md-card class="card-margin">
                <md-card-content>
                    <md-input-container>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [formControl]="UserAccountCtrl" />

                    </md-input-container>
                    <md-autocomplete #auto="mdAutocomplete">
                        <md-option *ngFor="let userAccount of filterUserAccount | async" [value]="userAccount">
                            {{userAccount.username}}
                        </md-option>
                    </md-autocomplete>
                    <md-input-container>
                        <input mdInput placeholder="Username" />

                    </md-input-container>
                </md-card-content>
              </md-card>
              `
})

export class NewUserAccountComponent{
    UserAccountCtrl: FormControl;
    filterUserAccount: any;

     async ngOnInit(){
        var response = await this.webService.getUserAccounts();
        this.userAccounts = response.json();
    }

    userAccounts = [];

    constructor(private webService : WebServiceComponents){
    this.UserAccountCtrl = new FormControl();
    this.filterUserAccount = this.UserAccountCtrl.valueChanges
        .startWith(null)
        .map(name => this.filteredUserAccount(name));
    }

    filteredUserAccount(val: string) {
    return val ? this.userAccounts.filter(s => new RegExp(`^${val}`, 'gi').test(s))
               : this.userAccounts;
  }
}

AppModule: app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MaterialModule } from '@angular/material';
import { AppComponent }  from './app.component';
import { WebServiceComponents } from './WebService/web.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { UserAccountComponent } from './UserAccount/useraccount-components';
import { NewUserAccountComponent } from './UserAccount/new-useraccount-component';

@NgModule({
  imports:      [ BrowserModule, MaterialModule, ReactiveFormsModule, FormsModule ],
  declarations: [ AppComponent, UserAccountComponent, NewUserAccountComponent ],
  bootstrap:    [ AppComponent ],
  providers: [ WebServiceComponents ]
})
export class AppModule { }

Sorry I'm just a newbie trying to play with this new framework.  Hopefully someone will guide me on how to fix this issue.  Thank you and Have a wonderful day ahead!


问:
var not accessible/visible within $.getJSON
First off, know that I am very new noob. The code below works except for the "if" portion of the "if-else" portion. The "searchTerm" that is alerted is the last value that a user enters into an input field with multiple values. So if user enters "a, b, c, d", and "a" (or any other value) meet the ===0 criteria, "d" is what is alerted.

I have researched here in stackoverflow and googled other areas and learning about callbacks and promises and that .getJSON is asynchronous and visibility outside of JSON and such but I have to admit I'm obviously not getting it and I'm sure I'm missing something simple. Any insight/help will be greatly appreciated.

```<code>for (var l = 0; l < searchTermArray.length; l++) {
    searchTerm = searchTermArray[l];
    searchURL = buildURL(searchTerm);
    getResults(searchURL, searchTerm);
    function getResults() {
        $.getJSON(searchURL, function (responses) {
            presentResults(responses, searchTerm);
        });
    }
    function presentResults(responses, searchTerm) {
        response = responses.search;
        if (responses.search.return.count === 0) {
            alert(searchTerm + " Not Found");
        } else {
            alert("Results found");
            ****Do other stuff with the results****
        }
     }
  }
</code>```

答:
I went ahead and separated the functions away from the for loop and then wrapped the .getJSON in a function of its own and passed the searchURL and searchTerm parameters which allowed me to works with the searchTerm for which the criteria was met.</p>

```<code>function getResults(searchURL, searchTerm) {
   responses = '';
   $.getJSON(searchURL, function (responses) {
       presentResults(responses, searchTerm);
   }); // close JSON
}
</code>```

Body:
First off, know that I am very new noob. The code below works except for the "if" portion of the "if-else" portion. The "searchTerm" that is alerted is the last value that a user enters into an input field with multiple values. So if user enters "a, b, c, d", and "a" (or any other value) meet the ===0 criteria, "d" is what is alerted.

I have researched here in stackoverflow and googled other areas and learning about callbacks and promises and that .getJSON is asynchronous and visibility outside of JSON and such but I have to admit I'm obviously not getting it and I'm sure I'm missing something simple. Any insight/help will be greatly appreciated.

for (var l = 0; l < searchTermArray.length; l++) {
    searchTerm = searchTermArray[l];
    searchURL = buildURL(searchTerm);
    getResults(searchURL, searchTerm);
    function getResults() {
        $.getJSON(searchURL, function (responses) {
            presentResults(responses, searchTerm);
        });
    }
    function presentResults(responses, searchTerm) {
        response = responses.search;
        if (responses.search.return.count === 0) {
            alert(searchTerm + " Not Found");
        } else {
            alert("Results found");
            ****Do other stuff with the results****
        }
     }
  }

Body:
I went ahead and separated the functions away from the for loop and then wrapped the .getJSON in a function of its own and passed the searchURL and searchTerm parameters which allowed me to works with the searchTerm for which the criteria was met.

function getResults(searchURL, searchTerm) {
   responses = '';
   $.getJSON(searchURL, function (responses) {
       presentResults(responses, searchTerm);
   }); // close JSON
}


问:
What is routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
What is routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

I cannot find any .axd file in my project, can I remove this route rule?

答:
Some Background

If you open up this file:

```<code>%WINDIR%\Microsoft.NET\Framework\version\Config\Web.config
</code>```

you will find this within the file:

```<code><add path="WebResource.axd"
     verb="GET"
     type="System.Web.Handlers.AssemblyResourceLoader"
     validate="True" />
</code>```

That is basically telling the Asp.NET runtime: "Hey asp.net dude, if a request comes for WebResource.axd then use AssemblyResourceLoader to process the request."

Please do note that WebResource.axd is NOT a file but simply a map (if I may say) to AssemblyResourceLoader. It is the name under which the handler is registered. On my machine, I found the following .axd handlers:

```<code><add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
<add verb="*" path="*_AppService.axd"
</code>```

Ok, so what does that handler do?

The AssemblyResourceLoader knows how to look for embedded files within an assembly so it can serve it (send it to the client i.e. a browser). For example, in asp.net web forms, if you use the validation controls, they depend on some javascript to show the errors on the web page. However, that javascript is embedded in an assembly. The browser needs the javascript so you will see this in the html of the page:

```<code><script src="/YourSite/WebResource.axd?d=fs7zUa...&t=6342..." type="text/javascript"></script>
</code>```

The AssemblyResourceLoader will find the assembly where the javascript is embedded using the information in the querystring and return the javascript.

Back to the Question

So to answer the question, what is:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

That is telling the routing engine that we will not be processing those requests that match that route pattern. In other words, we will not process .axd requests. Why? Because MVC itself is an HttpHandler similar to .axd and .aspx and many other handlers that are in the web.config file. The MVC handler does not know how to process the request such as looking for embedded resources in an assembly-the AssemblyResourceLoader knows how to do that. MVC knows how to do, well everything it does which is beyond the scope of this question and answer.

Body:
Some Background

If you open up this file:

%WINDIR%\Microsoft.NET\Framework\version\Config\Web.config

you will find this within the file:

<add path="WebResource.axd"
     verb="GET"
     type="System.Web.Handlers.AssemblyResourceLoader"
     validate="True" />

That is basically telling the Asp.NET runtime: "Hey asp.net dude, if a request comes for WebResource.axd then use AssemblyResourceLoader to process the request."

Please do note that WebResource.axd is NOT a file but simply a map (if I may say) to AssemblyResourceLoader. It is the name under which the handler is registered. On my machine, I found the following .axd handlers:

<add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
<add verb="*" path="*_AppService.axd"

Ok, so what does that handler do?

The AssemblyResourceLoader knows how to look for embedded files within an assembly so it can serve it (send it to the client i.e. a browser). For example, in asp.net web forms, if you use the validation controls, they depend on some javascript to show the errors on the web page. However, that javascript is embedded in an assembly. The browser needs the javascript so you will see this in the html of the page:

<script src="/YourSite/WebResource.axd?d=fs7zUa...&amp;t=6342..." type="text/javascript"></script>

The AssemblyResourceLoader will find the assembly where the javascript is embedded using the information in the querystring and return the javascript.

Back to the Question

So to answer the question, what is:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

That is telling the routing engine that we will not be processing those requests that match that route pattern. In other words, we will not process .axd requests. Why? Because MVC itself is an HttpHandler similar to .axd and .aspx and many other handlers that are in the web.config file. The MVC handler does not know how to process the request such as looking for embedded resources in an assembly-the AssemblyResourceLoader knows how to do that. MVC knows how to do, well everything it does which is beyond the scope of this question and answer.

ContentLicense: CC BY-SA 4.0


问:
mysql performance question
Is a search through numbers (INT) faster than characters in an mySQL database?
Regards,
Thijs</p>

答:
In practice the difference will be small - it will increase depending on the relative length of the 2 fields. The question pre-supposes that 2 are interchangeable - which is a very bad assumption given that MySQL natively supports an ENUM data-type.

If it's that important to you, why not measure it?

Title: mysql performance question


问:
How to stop AWS SES Spamming my gmail email?
Gmail gets flooded with spam emails from AWS Ses

After my spam email folder gets full the gmail is not getting any more emails. How can I report to AWS Ses not to send me an email from a specific AWS Ses Account.

Here is the details. I have contacted the company who is sending the emails. They are unable to solve the issue. ( In 3 years cant cope with change ).

I was once a permitted receiver but not anymore. Help would be appreciated.

Delivered-To: rifaterdemsahin@gmail.com Received: by 10.100.151.140
  with SMTP id q12csp736984pja;
          Thu, 22 Jun 2017 18:55:26 -0700 (PDT) X-Received: by 10.200.47.87 with SMTP id k23mr6662116qta.11.1498182926606;
          Thu, 22 Jun 2017 18:55:26 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1498182926; cv=none;
          d=google.com; s=arc-20160816;
          b=VjPlf2DSOO/X+jFewPovx0GPtS81NriE988G1yhFs0sWUAULrnp31pIDjiI3v/MC2h
           VOJDD6IkKpp+gsU4gYLo8BRoS71ZiHtB6O7Yk1z5Nc7QKxk+FjBuGK75Y8qM3dObxCKU
           FpZ3vwZrmwHbL8etRznU/DwfcN5f60GP45eINzKe7QYS+HOquiISKfFI6Kjac5/GvHqu
           fRL2zdFHu5E2aIXGUMUK4EdVsFjMQUsJUqBJC0OSoqLesyLdoyqV4oTAunH8BwYKWEY4
           /JTNP2zR6+6wucgfEVVPUQ5W6ocKVWPlJnHDw+vP1y6JkKMNaNj9mYl0LORMKHU71ptN
           f8Ig== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
          h=feedback-id:date:message-id:content-transfer-encoding:mime-version
           :subject:to:from:dkim-signature:arc-authentication-results;
          bh=Y7pVjQ5emAE4pdcubLwi7473vY3OWUVV5NusExrVNc8=;
          b=DlgSuorHXVeVtWhKM/csFcSeADLzJCLSuzCwZEsHVT7XLtmwSQERCwlIDHyabl8Ffa
           NNXx8CCYYfrAu0mbg3vGnAvG8SmusEwfBe0cAaa7D1bGf2fM/hGJzsQX21e3rbyQzvnu
           GSTZjwpW48sFkWzN863wLai5Z2Ne+eR/7lyzfEO/mIIJL0f3uvVmV32kFYMWHxYz0x8/
           r8GpiLqfD6nxMqvpxn04a/KYgo97/TxyB9AFaKEN08ih1d7+qLE5isq+BJI2NjCJLHnW
           vqlM1ideeygoN20cgTaz6ZQpYOQAsO0SIZQkoOtkT/6eb0DNCEa1RO45AmMgC9ZJ4rkc
           PYKQ== ARC-Authentication-Results: i=1; mx.google.com;
         dkim=pass header.i=@amazonses.com header.b=WNeDQXRK;
         spf=pass (google.com: domain of 0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  designates 54.240.9.109 as permitted sender)
  smtp.mailfrom=0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  Return-Path:
  <0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com>
  Received: from a9-109.smtp-out.amazonses.com
  (a9-109.smtp-out.amazonses.com. [54.240.9.109])
          by mx.google.com with ESMTPS id h186si1190862qkc.200.2017.06.22.18.55.26
          for
          (version=TLS1 cipher=ECDHE-RSA-AES128-SHA bits=128/128);
          Thu, 22 Jun 2017 18:55:26 -0700 (PDT) Received-SPF: pass (google.com: domain of
  0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  designates 54.240.9.109 as permitted sender) client-ip=54.240.9.109;
  Authentication-Results: mx.google.com;
         dkim=pass header.i=@amazonses.com header.b=WNeDQXRK;
         spf=pass (google.com: domain of 0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  designates 54.240.9.109 as permitted sender)
  smtp.mailfrom=0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/simple;
  s=224i4yxa5dv7c2xz3womw6peuasteono; d=amazonses.com; t=1498182926;
  h=From:To:Subject:MIME-Version:Content-Type:Content-Transfer-Encoding:Message-ID:Date:Feedback-ID;
  bh=VCZKg8hFUb63lOKDitSw+wHccKQ7iJdOqT+3v5T9kMM=;
  b=WNeDQXRKVjREfsyiCHuwazQD7AXWRfZc3UcrwH1AghtaCnavxJ6CBSLTUsIqc5GF
  m6/uRCDItr6crWjplYgl14Dq2mbGHMFtB+vZHh0PPNmO4n3+/8PevleQbEYInRWmlec
  ZbFX57QHhrNXtEyUc4qaM3ZtjpcwjaPzOXe2liB8= From: No-Reply
   To: rifaterdemsahin@gmail.com Subject:
  Performance Warning(3x) IP: 192.168.30.40 Method:
  Broadage.Common.Tools.Email MIME-Version: 1.0 Content-Type: text/html;
  charset=UTF-8 Content-Transfer-Encoding: quoted-printable Message-ID:
  <0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@email.amazonses.com>
  Date: Fri, 23 Jun 2017 01:55:26 +0000 X-SES-Outgoing:
  2017.06.23-54.240.9.109 Feedback-ID: 1.us-east-1.SIJlVA2xTbAVdBXctlUaxBDeEU1mquOgueuof7Nldbc=:AmazonSES

Performans Uyar=C4=B1s=C4=B1
Mak= ine Ip =3D>  192.168.30.40
Uygulama Ad=C4=B1 =3D>
Method Name =3D>  Broadage.Common= .Tools.Email
=C4=B0stenilen Performans S=C3=BCresi =3D>
  250 ms elapsed time

Harcanan S=C3=BCre=
  =3D> 786.708 ms elapsed time

答:
1) As pointed by Jordan Stewart, configure your filter to delete messages, but don't mark them as spam.

2) As complaint directly to the company did not work, I suggest complaining to AWS. See here https://aws.amazon.com/premiumsupport/knowledge-center/report-aws-abuse/
They seem to take abuse (or misuse) of their platform quite seriously. So, I would expect the company will be forced to either fix the issue or be disconnected from SES service.


问:
Equivalence of static methods in Go
Let's say in Java, I have class CryptoFormat, which has a static method named getLegacyFormat(). When I want to use the method, I just need to call CryptoFormat.getLegacyFormat(). This is clear because I know where the method comes from.

In Go, there is no static method. I don't really want to just make a file called crypto_format.go and define the method there. The reason is that whenever I need the method, I just call GetLegacyFormat(), which doesn't contain the context where the method comes from.

I could think of two ways to solve the problem:

Make a separate package named cryptoformat, and define the method as a global function in the package. This way, I need to make a new package for just few methods. Also, whenever I need static methods like this, I have to define new packages.

Define a struct named cryptoFormat containing method GetLegacyFormat(). Also, define a <s>global</s> public variable named CryptoFormat, which points to an instance of struct cryptoFormat. This way, I can call CryptoFormat.GetLegacyFormat() when I need the method.

I am not sure which one is better, or whether there is better way.

答:
I would say option 1 you mention is the more idiomatic way to define such functions, if they don't need any state that would warrant to tie them to an underlying struct.

If there is some state you'd like to have as context for the function, then option 2 would be the way to go.

Note that in Go, functions are "first class citizens", so you don't have Java's constraints of needing to define a class for static methods.

And yes, if you want a separate namespace you'd need to define separate packages (just as in Java you'd need to define separate classes and/or packages).

If you want your implementation to be idiomatic, I'd suggest you take a look at Go's standard libraries (pick a few packages and explore how they implement their functions) to get a better feeling of the usual ways to structure this.

Title: Equivalence of static methods in Go


问:
One line solution for editing a numpy array of counts? (python)
I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])
</code>```

I want to get back an array like so:

```<code>[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]
</code>```

Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 occurs once in the third position, 1 occurs once in the fourth position, etc. Later, I'll have more input arrays of the same dimensions, and I would like to add on the totals of the values to this array of counts.

The code I have right now is:

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1
</code>```

This does give me the output I want. However, I would like to condense the for loops into one line, using a line similar to this:

```<code>cumulative[:, :, a[:, :]-1] +=1
</code>```

This line doesn't work, and I can't find anything online on how to perform this operation. Any suggestions?

Body:
I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

I want to get back an array like so:

[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]

Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 occurs once in the third position, 1 occurs once in the fourth position, etc. Later, I'll have more input arrays of the same dimensions, and I would like to add on the totals of the values to this array of counts.

The code I have right now is:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1

This does give me the output I want. However, I would like to condense the for loops into one line, using a line similar to this:

cumulative[:, :, a[:, :]-1] +=1

This line doesn't work, and I can't find anything online on how to perform this operation. Any suggestions?

Body: np.concatenate((a==1,a==2,a==3),axis=1).reshape((4,3,3)).transpose(0,2,1) + 0


问:
iOS swift 3 how can I change types in a switch statement
I have 2 TableViewCells that upload images and the code is essentially identical . What I want to do is get that code and get it into 1 function so that I can reduce duplication  . I am however having trouble casting things properly . The 2 tableview Cells are called HomeTVC and ProfileTVC and they both have an UiImageView which is named profile_Image .

Here is how I call that function

```<code>  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTVC", for: indexPath) as! HomeTVC

 homeProfile.sharedGetImage(cellType: cell,streamsModel: streamsModel, row: indexPath.row)

}
</code>```

Obviously the code above belongs to the HomeTVC tableView, now here is the function

```<code>   func sharedGetImage (cellType: UITableViewCell?,streamsModel: streamModel, row: Int) {

        var cell = HomeTVC()

        switch cellType {

        case is HomeTVC :
         cell =  HomeTVC()
         break

        case  is ProfileTVC :
        cell = cell as! ProfileTVC

        default : break

        }

        if streamsModel.profile_image_string[row] != "" {

            if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage {
                cell.profile_image.image = image
            }

          }
     }
</code>```

I'm getting an error inside the switch statement on cell = cell as! ProfileTVC the error is cast from HomeTVC to ProfileTVC fails unrelated type . Which I understand, how can I get around that issue ? What I want to do is detect what type the UITableViewCell is then get a variable and change it to that type so that I can access the profile_image property .

答:
In your sharedGetImage function, you are passing a reference to the table view cell, so use that instead of creating a new cell.

```<code>func sharedGetImage(cellType: UITableViewCell?, streamsModel: streamModel, row: Int) {

    if let cell = cellType as? HomeTVC {
        if streamsModel.profile_image_string[row] != "" {
            if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage {
                cell.profile_image.image = image
            }
        }
    }

    if let cell = cellType as? ProfileTVC {
        if streamsModel.profile_image_string[row] != "" {
            if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage {
                cell.profile_image.image = image
            }
        }
    }

}
</code>```

Alternatively, when you have two classes that have the same property, this is a great chance to use a protocol. You could create a protocol to specify that an object has a UIImageView for a profile image.

```<code>protocol ProfileImageDisplaying {
    var profileImageView: UIImageView
}
</code>```

You could make both cells adopt this protocol, and then you would only need to do one check (to see if the cell is ProfileImageDisplaying) instead of two.

Body:
I have 2 TableViewCells that upload images and the code is essentially identical . What I want to do is get that code and get it into 1 function so that I can reduce duplication  . I am however having trouble casting things properly . The 2 tableview Cells are called HomeTVC and ProfileTVC and they both have an UiImageView which is named profile_Image .

Here is how I call that function

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTVC", for: indexPath) as! HomeTVC

 homeProfile.sharedGetImage(cellType: cell,streamsModel: streamsModel, row: indexPath.row)

}

Obviously the code above belongs to the HomeTVC tableView, now here is the function

   func sharedGetImage (cellType: UITableViewCell?,streamsModel: streamModel, row: Int) {

        var cell = HomeTVC()

        switch cellType {

        case is HomeTVC :
         cell =  HomeTVC()
         break

        case  is ProfileTVC :
        cell = cell as! ProfileTVC

        default : break

        }

        if streamsModel.profile_image_string[row] != "" {

            if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage {
                cell.profile_image.image = image
            }

          }
     }

I'm getting an error inside the switch statement on cell = cell as! ProfileTVC the error is cast from HomeTVC to ProfileTVC fails unrelated type . Which I understand, how can I get around that issue ? What I want to do is detect what type the UITableViewCell is then get a variable and change it to that type so that I can access the profile_image property .

Body:
In your sharedGetImage function, you are passing a reference to the table view cell, so use that instead of creating a new cell.

func sharedGetImage(cellType: UITableViewCell?, streamsModel: streamModel, row: Int) {

    if let cell = cellType as? HomeTVC {
        if streamsModel.profile_image_string[row] != "" {
            if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage {
                cell.profile_image.image = image
            }
        }
    }

    if let cell = cellType as? ProfileTVC {
        if streamsModel.profile_image_string[row] != "" {
            if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage {
                cell.profile_image.image = image
            }
        }
    }

}

Alternatively, when you have two classes that have the same property, this is a great chance to use a protocol. You could create a protocol to specify that an object has a UIImageView for a profile image.

protocol ProfileImageDisplaying {
    var profileImageView: UIImageView
}

You could make both cells adopt this protocol, and then you would only need to do one check (to see if the cell is ProfileImageDisplaying) instead of two.


问:
How can I check one value against another value in my Google Sheet and then query properties of the cell with the matching value?
I want to check values from a JSON URL against values within a defined range in my Google Sheet.

Should there be a match, I would like to query the properties of the cell containing the matching value (its row, its column, etc.)

How can I do this within Google Apps Script?

答: Everything you need to know about Spreadsheet operations in Apps Script can be found in Overview and SpreadsheetApp. You can start from there. For example, the methods to query properties like row and col are getRow and getColumn</p>


问:
hibernate 5 maven and mysql No suitable driver found for jdbc:mysql://127.0.0.1:3306/projeto
i'm getting this error: "No suitable driver found for jdbc:mysql://127.0.0.1:3306/project", i'm using eclipse, maven, hibernate 5, and i've already instaled the mysql connector, but still not working, any ideis?

the prompt error.

```<code>GRAVE: Servlet.service() for servlet [Spring MVC Dispatcher Servlet] in
context with path [/projeto] threw exception [Handler dispatch failed; nested
exception is java.lang.ExceptionInInitializerError] with root
causejava.sql.SQLException: No suitable driver found for
jdbc:mysql://127.0.0.1:3306/projeto
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionCreator.makeConnection(DriverManagerConnectionCreator.java:34)
</code>```

the hiberate and mysql dependencies in my pom file.

```<code><hibernate-core.version>5.0.1.Final</hibernate-core.version>
    <hibernate-commons-annotations.version>5.0.1.Final</hibernate-commons-annotations.version>
    <mysql-connector-java.version>6.0.6</mysql-connector-java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>${hibernate-commons-annotations.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate-core.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>
</code>```

jars on maven

and the code where the error came from. *the code stops in the comented line.

```<code>public class HibernateUtil {

private static final SessionFactory sessionFactory;
static {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
            .build();
//Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();

    sessionFactory = metaData.getSessionFactoryBuilder().build();
}

public static SessionFactory getSessionFactory() {

    return sessionFactory;

    }
}
</code>```

答:
I've found the solution for my problem, but first of all, thanks to Zeromus for answering me. The problem, in my case, is occurring when I'm trying to instantiate this object:

```<code>public class HibernateUtil {

private static final SessionFactory sessionFactory;
static {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
</code>```

The method .configure("hibernate.cfg.xml").build(); was not finding the hibernate xml file. I just refreshed the project and the problem was solved, I hope it can help someone. It was so simple, but took a long time to find it.

Body:
i'm getting this error: "No suitable driver found for jdbc:mysql://127.0.0.1:3306/project", i'm using eclipse, maven, hibernate 5, and i've already instaled the mysql connector, but still not working, any ideis?

the prompt error.

GRAVE: Servlet.service() for servlet [Spring MVC Dispatcher Servlet] in
context with path [/projeto] threw exception [Handler dispatch failed; nested
exception is java.lang.ExceptionInInitializerError] with root
causejava.sql.SQLException: No suitable driver found for
jdbc:mysql://127.0.0.1:3306/projeto
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionCreator.makeConnection(DriverManagerConnectionCreator.java:34)

the hiberate and mysql dependencies in my pom file.

<hibernate-core.version>5.0.1.Final</hibernate-core.version>
    <hibernate-commons-annotations.version>5.0.1.Final</hibernate-commons-annotations.version>
    <mysql-connector-java.version>6.0.6</mysql-connector-java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>${hibernate-commons-annotations.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate-core.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

jars on maven

and the code where the error came from. *the code stops in the comented line.

public class HibernateUtil {

private static final SessionFactory sessionFactory;
static {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
            .build();
//Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();

    sessionFactory = metaData.getSessionFactoryBuilder().build();
}

public static SessionFactory getSessionFactory() {

    return sessionFactory;

    }
}

Body:
I've found the solution for my problem, but first of all, thanks to Zeromus for answering me. The problem, in my case, is occurring when I'm trying to instantiate this object:

public class HibernateUtil {

private static final SessionFactory sessionFactory;
static {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

The method .configure("hibernate.cfg.xml").build(); was not finding the hibernate xml file. I just refreshed the project and the problem was solved, I hope it can help someone. It was so simple, but took a long time to find it.


问:
Eclipse for Robot Framework (java version) project: how to run specific tags?
My project uses Maven to reference all needed libraries, so I don't even need to manually install robot framework (I just included markusbernhardt's Selenium2Library as a dependency in pom.xml):

```<code>  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.markusbernhardt</groupId>
      <artifactId>robotframework-selenium2library-java</artifactId>
      <version>1.4.0.8</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</code>```

I can run my tests as Maven Install or using a Run Configuration for Maven:

However, I don't know how to tell robot framework that I want to run tests tagged with certain tags. I don't run robot framework from a command line as I don't have robot framework installed in my machine, I'm only using it as a maven dependency, so I can't run python -m robot.run --include tag.

I tried adding --include tag as a Parameter in the Run Configuration but it's being ignored.

Is there a way to send this tag parameter to robot within Eclipse?

答:
Just found out how! Leaving info here in case it helps someone else:

It's all in pom.xml:

Add a <properties />first-level element (within <project />) with a property name of your choosing and the tag you want to run, like this:

```<code><properties>
  <robot-tag>mytag</robot-tag>
</properties>
</code>```

Then, in the plugins section, within the robotframework-maven-plugin plugin
element, add this:

```<code><configuration>
  <includes>
    <include>${robot-tag}</include>
  </includes>
</configuration>
</code>```

That's it. The Run Configuration doesn't need to be changed. And the project can also be ran as Maven Install.

This is what my pom.xml looks like now (stripping out the  element and project-specific info like groupID, artifactID, etc):

```<code>  <properties>
    <robot-tag>debug</robot-tag>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.markusbernhardt</groupId>
      <artifactId>robotframework-selenium2library-java</artifactId>
      <version>1.4.0.8</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <includes>
            <include>${robot-tag}</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>
</code>```

Body:
My project uses Maven to reference all needed libraries, so I don't even need to manually install robot framework (I just included markusbernhardt's Selenium2Library as a dependency in pom.xml):

  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.markusbernhardt</groupId>
      <artifactId>robotframework-selenium2library-java</artifactId>
      <version>1.4.0.8</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

I can run my tests as Maven Install or using a Run Configuration for Maven:

However, I don't know how to tell robot framework that I want to run tests tagged with certain tags. I don't run robot framework from a command line as I don't have robot framework installed in my machine, I'm only using it as a maven dependency, so I can't run python -m robot.run --include tag.

I tried adding --include tag as a Parameter in the Run Configuration but it's being ignored.

Is there a way to send this tag parameter to robot within Eclipse?

Body:
Just found out how! Leaving info here in case it helps someone else:

It's all in pom.xml:

Add a <properties />first-level element (within <project />) with a property name of your choosing and the tag you want to run, like this:

<properties>
  <robot-tag>mytag</robot-tag>
</properties>

Then, in the plugins section, within the robotframework-maven-plugin plugin
element, add this:

<configuration>
  <includes>
    <include>${robot-tag}</include>
  </includes>
</configuration>

That's it. The Run Configuration doesn't need to be changed. And the project can also be ran as Maven Install.

This is what my pom.xml looks like now (stripping out the  element and project-specific info like groupID, artifactID, etc):

  <properties>
    <robot-tag>debug</robot-tag>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.markusbernhardt</groupId>
      <artifactId>robotframework-selenium2library-java</artifactId>
      <version>1.4.0.8</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <includes>
            <include>${robot-tag}</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>