问:
How to get the not similar data from a access data base using VBA?
I want to extract data from a access database but just not all data if it's similar example if the db contains (a,b,b,b,c) I want to get only (a,b,c).

Hope it's clear enough!

```<code>Set cn = CreateObject("ADODB.Connection")
        cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & folderPath & "\" & gp

       Set rs = CreateObject("ADODB.Recordset")
        rs.Open "SELECT GaCodeMun FROM ModificationsAttributsParcours WHERE GaCodeMun <> '' ", cn, , , adCmdText

TargetRange.CopyFromRecordset rs
</code>```

答:
Use DISTINCT to retrieve unique values.
Your SELECT statement would look like:

```<code>SELECT DISTINCT GaCodeMun FROM ModificationsAttributsParcours WHERE GaCodeMun <> ''
</code>```

If you want to calculate the total of distinct values, you can use this query:

```<code>SELECT COUNT(GaCodeMun) AS Total
from
(
    SELECT DISTINCT GaCodeMun
    FROM ModificationsAttributsParcours
    WHERE GaCodeMun <> ''
)
</code>```

If you want to wrap it up in one query, you can use below query. Total of distinct values however will be reflected per each unique value.

```<code>SELECT DISTINCT GaCodeMun,
(
SELECT COUNT(GaCodeMun) AS Total
FROM
    (
    SELECT DISTINCT GaCodeMun
    FROM ModificationsAttributsParcours
    WHERE GaCodeMun <> ''
    )
)
FROM ModificationsAttributsParcours
</code>```

Body:
I want to extract data from a access database but just not all data if it's similar example if the db contains (a,b,b,b,c) I want to get only (a,b,c).

Hope it's clear enough!

Set cn = CreateObject("ADODB.Connection")
        cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & folderPath & "\" & gp

       Set rs = CreateObject("ADODB.Recordset")
        rs.Open "SELECT GaCodeMun FROM ModificationsAttributsParcours WHERE GaCodeMun <> '' ", cn, , , adCmdText

TargetRange.CopyFromRecordset rs

Body:
Use DISTINCT to retrieve unique values.
Your SELECT statement would look like:

SELECT DISTINCT GaCodeMun FROM ModificationsAttributsParcours WHERE GaCodeMun <> ''

If you want to calculate the total of distinct values, you can use this query:

SELECT COUNT(GaCodeMun) AS Total
from
(
    SELECT DISTINCT GaCodeMun
    FROM ModificationsAttributsParcours
    WHERE GaCodeMun <> ''
)

If you want to wrap it up in one query, you can use below query. Total of distinct values however will be reflected per each unique value.

SELECT DISTINCT GaCodeMun,
(
SELECT COUNT(GaCodeMun) AS Total
FROM
    (
    SELECT DISTINCT GaCodeMun
    FROM ModificationsAttributsParcours
    WHERE GaCodeMun <> ''
    )
)
FROM ModificationsAttributsParcours


来源: stackexchange

问:
What is the best software to host a ruby on rails application on production?
Is webrick the only good option?
I know there is a way of using apache, but is it better than webrick?</p>

答: Honestly, passenger is really good for Apache, but I would consider an external hosting solution. For small projects, heroku provides free hosting, and for large projects, you can scale as needed with relatively low prices. There are some others out there, but heroku (IMHO) gives you the most flexibility... and its FREE (and reliable)!</p>

ContentLicense: CC BY-SA 2.5


问:
How do I change colour of icon font inside active tab?
I'm trying to get the colour of my icon to stay a certain colour when it's the open active tab, but it's not working. I've been able to use p:active to get the icons to change colour when clicked, but that colour goes away after the click is done. I'd like it to stay when that tab is open.

The button.active is working only for background color and not font color. Can anyone help figure this out? I'm at a loss.

Here is all my coding:

```<code>/* Style the tab */
div.tab {
overflow: hidden;
border: 0px;
background-color: transparent;
text-align: center;
margin-left:auto;
margin-right:auto;
display:block;
}

/* Style the buttons inside the tab */
div.tab button {
background-color:transparent;
float: center;
border: none;
outline: none;
cursor: pointer;
min-width:100px;
transition: 0.3s;
font-size: 16px;
color:white;
text-transform: uppercase;
line-height:1;
margin: 2%;
height:31px;
font-weight:300;
}

/* Change background color of buttons on hover */
div.tab button > p:hover {
color:black;
}

/* Create an active/current tablink class */
div.tab button.active {
background-color:#F7941D;
color:white;
}

/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 0px;
border-top: none;
text-align:center;
}
</code>```

And my HTML:

```<code><div id="USA" class="tabcontent" style="display: block;">
<img class="diagram" src="http://dev.legendpower.com/wp-content/uploads/2017/11/Diagram_usa.png" style="margin-bottom:2%;">
</div>

<div id="Canada" class="tabcontent" style="display: none;">
<img class="diagram" src="http://dev.legendpower.com/wp-content/uploads/2017/11/Diagram_can.png"style="margin-bottom:2%;">
</div>

<div class="tab" style="width:50%; height:50px;">
  <button class="tablinks active" onclick="openToggle(event, 'USA')" id="defaultOpen"><p class="icon-usa-flag-icon" id="defaultOpen"></p></button>
  <button class="tablinks" onclick="openToggle(event, 'Canada')"><p class="icon-canada-flag-icon-1"></p></button>
</div>

</div></div>
</code>```

And the JS I'm using:

```<code>function openToggle(evt, ToggleName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(ToggleName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</code>```

答:
You need to target the p tag with the icon class and change the color, so instead of this :

```<code>div.tab button.active {
    background-color:#F7941D;
    color:white;
}
</code>```

you should do this :

```<code>div.tab button.active {
    background-color:#F7941D;
}

div.tab button.active p[class|="icon"] {
    color:white;
}
</code>```

I used this attribute selector [class|="icon"] to target all your icons since all of them start with the word icon. You can read more about attribute selector

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the colour of my icon to stay a certain colour when it's the open active tab, but it's not working. I've been able to use p:active to get the icons to change colour when clicked, but that colour goes away after the click is done. I'd like it to stay when that tab is open.

The button.active is working only for background color and not font color. Can anyone help figure this out? I'm at a loss.

Here is all my coding:

/* Style the tab */
div.tab {
overflow: hidden;
border: 0px;
background-color: transparent;
text-align: center;
margin-left:auto;
margin-right:auto;
display:block;
}

/* Style the buttons inside the tab */
div.tab button {
background-color:transparent;
float: center;
border: none;
outline: none;
cursor: pointer;
min-width:100px;
transition: 0.3s;
font-size: 16px;
color:white;
text-transform: uppercase;
line-height:1;
margin: 2%;
height:31px;
font-weight:300;
}

/* Change background color of buttons on hover */
div.tab button > p:hover {
color:black;
}

/* Create an active/current tablink class */
div.tab button.active {
background-color:#F7941D;
color:white;
}

/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 0px;
border-top: none;
text-align:center;
}

And my HTML:

  <button class="tablinks active" onclick="openToggle(event, 'USA')" id="defaultOpen">

</button>
  <button class="tablinks" onclick="openToggle(event, 'Canada')">

</button>

And the JS I'm using:

function openToggle(evt, ToggleName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(ToggleName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

Body:
You need to target the p tag with the icon class and change the color, so instead of this :

div.tab button.active {
    background-color:#F7941D;
    color:white;
}

you should do this :

div.tab button.active {
    background-color:#F7941D;
}

div.tab button.active p[class|="icon"] {
    color:white;
}

I used this attribute selector [class|="icon"] to target all your icons since all of them start with the word icon. You can read more about attribute selector


问:
Using a content from a ZeroMQ-stream for a webpage
I have this code in Python.

With this I can output the content of the ZeroMQ-stream to a file. Only writing to a file every 10 seconds does not seem to be really useful and costs a lot of performance.

Now I would like to show the content in a web-page. I've seen PyBottle exist, which in Python creates a web server.

How can I integrate PyBottle in my code, so it can output the latest message of the stream? I thought about the code of PyBottle in the while-loop.

But do not I ( unnecessarily ) create a new web-server instance?

How can I handle this?

Sample of PyBottle:

```<code>from bottle import route, run, template

@route( '/hello/<name>' )
def index( name ):
    return template( '<b>Hello {{name}}</b>!', name = name )

run( host = 'localhost', port = 8080 )
</code>```

My Python code:

```<code>#!/usr/bin/env python2

from gzip       import GzipFile
from cStringIO  import StringIO
from subprocess import call
pass;           import zmq

context = zmq.Context()

subscriber = context.socket( zmq.XSUB )
subscriber.connect( "tcp://pubsub.*******.nl:7664" )
subscriber.send( chr( 0x01 )             # { 0x01: ZMQ_XSUB.subscribe,
               + "/RIG/VehiclePositions" #   0x00: ZMQ_XSUB.unsubscribe
                 )                       #   }
while   True:

        multipart =  subscriber.recv_multipart()
        address   =  multipart[0]
        contents  = ''.join(multipart[1:])
        contents  =  GzipFile( '', 'r', 0, StringIO( contents ) ).read()
        filename  = "tmp/treinpos.txt"
        file      =  open( filename, "w" )
        file.write( contents )
        file.close()

subscriber.close()
context.term()
</code>```

答:
Generating repetitive costs is a sign of a bad design practice:

Right,

rather extend the PyBottle, or whatever other web-serving framework to instantiate rather just once ( may use load-balancing workers later, for further increasing the architecture's performance envelope ), where it also creates its own ZeroMQ Context()-IO-datapump engine. This enables the web-serving methods communicate with the rest of the content-generating agents and pre-construct the actual dynamic content both a-priori, ad-hoc and also on-the-fly.

The rest of your architecture will become smarter and way more light-weight, as all your interactions become signalling/messaging-based, avoiding fileIO-tortures of a filesystem at all.

Additional ZeroMQ performance tricks available

may fine-tune via .setsockopt() the remote-terminal I/O-costs + performance by zmq.CONFLATE, zmq.IMMEDIATE and other ISO/OSI-L3-layer parameters

may harden the web-serving code by connectivity white-listing + size-ceilings

and many further performance trick to squeeze maximum performance even from restricted code-execution environment inside the real-world distributed-computing ecosystem.

Body:
I have this code in Python.

With this I can output the content of the ZeroMQ-stream to a file. Only writing to a file every 10 seconds does not seem to be really useful and costs a lot of performance.

Now I would like to show the content in a web-page. I've seen PyBottle exist, which in Python creates a web server.

How can I integrate PyBottle in my code, so it can output the latest message of the stream? I thought about the code of PyBottle in the while-loop.

But do not I ( unnecessarily ) create a new web-server instance?

How can I handle this?

Sample of PyBottle:

from bottle import route, run, template

@route( '/hello/<name>' )
def index( name ):
    return template( 'Hello {{name}}!', name = name )

run( host = 'localhost', port = 8080 )

My Python code:

#!/usr/bin/env python2

from gzip       import GzipFile
from cStringIO  import StringIO
from subprocess import call
pass;           import zmq

context = zmq.Context()

subscriber = context.socket( zmq.XSUB )
subscriber.connect( "tcp://pubsub.*******.nl:7664" )
subscriber.send( chr( 0x01 )             # { 0x01: ZMQ_XSUB.subscribe,
               + "/RIG/VehiclePositions" #   0x00: ZMQ_XSUB.unsubscribe
                 )                       #   }
while   True:

        multipart =  subscriber.recv_multipart()
        address   =  multipart[0]
        contents  = ''.join(multipart[1:])
        contents  =  GzipFile( '', 'r', 0, StringIO( contents ) ).read()
        filename  = "tmp/treinpos.txt"
        file      =  open( filename, "w" )
        file.write( contents )
        file.close()

subscriber.close()
context.term()


问:
Insert only when occurs a condition
I have the next tables:

Votation

```<code>Id: PK
Title: string
Expiration: DateTime
</code>```

VotationOptions

```<code>Id: PK
Option: string
VotationId: FK
</code>```

Users can insert a VotationOption meanwhile Votation.Expiration has not expired.

I can't check the expiration date and after insert an option because in production it could be that the expiration date has not expired and when the option is really inserted in the database, the expiration date has expired.

My code:

```<code>if (this.context.Votations.First(vot => vot.Id == 1 && vot.Expiration < DateTime.Now == null) return BadRequest();

var option = new VotationOption
{
    Option = "Example",
    VotationId = 1
};

this.context.VotationOptions.Add(option);
this.context.SaveChanges();
</code>```

I want this:

```<code>this.context.VotationOptions.AddWhere(option, vot => vot.Expiration < DateTime.Now);
</code>```

答:
Simply using Entity Framework it can't be done. However, you can still use the underlying db context to execute raw SQL so you can use something like:

```<code>int result = this.context.Database.ExecuteSqlCommand("INSERT INTO VotationOptions (VotationId, Option) SELECT {your literal values} FROM Votation WHERE {check validity on the votation}");
</code>```

Where result would indicate how many rows the database ended up inserting. Keep in mind you'd have to write your validity check such that only 1 result could come back.

However, like @ElementalPete mentions in his comment on your question I'd question the necessity.

Title: Insert only when occurs a condition

Body:
I have the next tables:

Votation

Id: PK
Title: string
Expiration: DateTime

VotationOptions

Id: PK
Option: string
VotationId: FK

Users can insert a VotationOption meanwhile Votation.Expiration has not expired.

I can't check the expiration date and after insert an option because in production it could be that the expiration date has not expired and when the option is really inserted in the database, the expiration date has expired.

My code:

if (this.context.Votations.First(vot => vot.Id == 1 && vot.Expiration < DateTime.Now == null) return BadRequest();

var option = new VotationOption
{
    Option = "Example",
    VotationId = 1
};

this.context.VotationOptions.Add(option);
this.context.SaveChanges();

I want this:

this.context.VotationOptions.AddWhere(option, vot => vot.Expiration < DateTime.Now);

Body:
Simply using Entity Framework it can't be done. However, you can still use the underlying db context to execute raw SQL so you can use something like:

int result = this.context.Database.ExecuteSqlCommand("INSERT INTO VotationOptions (VotationId, Option) SELECT {your literal values} FROM Votation WHERE {check validity on the votation}");

Where result would indicate how many rows the database ended up inserting. Keep in mind you'd have to write your validity check such that only 1 result could come back.

However, like @ElementalPete mentions in his comment on your question I'd question the necessity.


问:
Get the sum of all rows in one table
I've tried to get the sum of all rows from one table with the following code, but sadly my database gives me "NULL" back.

PHP:

```<code>$get_cash=mysqli_query($db, "SELECT SUM(price) FROM products WHERE ID='$F_User_ID'");
$fetch_cash = mysqli_fetch_assoc($get_cash);
$cash = $fetch_cash["cash"];
echo "<p>Money spent already: $cash €</p>";
</code>```

MySQL:

```<code>MariaDB [database]> SELECT SUM(price) FROM products WHERE ID='100001';
+------------+
| SUM(price) |
+------------+
|       NULL |
+------------+
1 row in set (0.00 sec)
</code>```

So I want to get the sum of how much money the Person F_User_ID has already spent in all products he has bought.

答:
We can replace a NULL with a zero, and we can assign an alias to the expression to be used as the column name in the resultset. If this query executes, it will return a single row containing a column named cash.

```<code>SELECT IFNULL(SUM(price),0) AS `cash` FROM products WHERE id = 'someval'
</code>```

Recommended reading:

Exploits of a Mom:  https://xkcd.com/327/  aka Little Bobby Tables

OWASP SQL Injection:  https://www.owasp.org/index.php/SQL_Injection

Title: Get the sum of all rows in one table

Body:
I've tried to get the sum of all rows from one table with the following code, but sadly my database gives me "NULL" back.

PHP:

$get_cash=mysqli_query($db, "SELECT SUM(price) FROM products WHERE ID='$F_User_ID'");
$fetch_cash = mysqli_fetch_assoc($get_cash);
$cash = $fetch_cash["cash"];
echo "
Money spent already: $cash €
";

MySQL:

MariaDB [database]> SELECT SUM(price) FROM products WHERE ID='100001';
+------------+
| SUM(price) |
+------------+
|       NULL |
+------------+
1 row in set (0.00 sec)

So I want to get the sum of how much money the Person F_User_ID has already spent in all products he has bought.

Body:
We can replace a NULL with a zero, and we can assign an alias to the expression to be used as the column name in the resultset. If this query executes, it will return a single row containing a column named cash.

SELECT IFNULL(SUM(price),0) AS `cash` FROM products WHERE id = 'someval'

Recommended reading:

Exploits of a Mom:  https://xkcd.com/327/  aka Little Bobby Tables

OWASP SQL Injection:  https://www.owasp.org/index.php/SQL_Injection


答: Phusion Passenger is the de facto Apache mod, and yes, it's better than WEBRick (which is really only good for tiny sites or testing). </p>

Title: What is the best software to host a ruby on rails application on production?

Body:
Is webrick the only good option?
I know there is a way of using apache, but is it better than webrick?


答:
I think I've struggled with a very similar question before and couldn't find a library-supported way.

PS. Found that post boost::multi_index_container, operations on std::set inside container

It's interesting to compare because it basically does similar interval-consolidating but at the time of query. This has benefits (it retains insertion history so you can query other results that benefit from non-lossy storage). It also trades insertion efficiency for more query cost.

I'd probably write the insertion/combination operation myself.

I've tried to come up with a descriptive name here. Since the operation feels similar to landing "drops" into bigger "pools", I called the operation mix:

```<code>template <typename Map, typename V = typename Map::segment_type>
void mix(Map& m, std::initializer_list<V> drops) {
    typename Map::codomain_combine combine;

    for (auto drop : drops) {
        // combine with all overlapping existing segments
        auto range = m.equal_range(drop.first);

        for (auto it = range.first; it != range.second; ++it) {
            combine(drop.second, it->second);
            drop.first = hull(drop.first, it->first);
        }

        m.set(drop); // logically equivalent to m.add(drop) here
    }
}
</code>```

With this you can articulate your desired behaviour like so:

```<code>int main() {
    using Map      = boost::icl::interval_map<int, Ints>;
    using Interval = Map::interval_type::type;
    Map m;

    std::cout << m << "\n";

    mix(m, { {Interval::closed(1,3), {1}},
             {Interval::closed(2,4), {2}},
             {Interval::closed(5,7), {3}},
             {Interval::closed(6,8), {4}} });

    std::cout << m << "\n";

    mix(m, { {Interval::closed(3,6), {42}} });

    std::cout << m << "\n";
}
</code>```

And the output will be

```<code>{}
{([1,4]->{1,2,})([5,8]->{3,4,})}
{([1,8]->{1,2,3,4,42,})}
</code>```

Full Demo

Live On Coliru

```<code>#include <boost/icl/interval_map.hpp>
#include <set>
#include <iostream>

template <typename Map, typename V = typename Map::segment_type>
void mix(Map& m, std::initializer_list<V> drops) {
    typename Map::codomain_combine combine;

    for (auto drop : drops) {
        // combine with all overlapping existing segments
        auto range = m.equal_range(drop.first);

        for (auto it = range.first; it != range.second; ++it) {
            combine(drop.second, it->second);
            drop.first = hull(drop.first, it->first);
        }

        m.set(drop); // logically equivalent to m.add(drop) here
    }
}

// For debug: an ostreamable std::set<int>
struct Ints : std::set<int> {
    using std::set<int>::set;

    friend std::ostream& operator<<(std::ostream& os, Ints const& s) {
        os << '{';
        for(auto i : s) os << i << ",";
        return os << '}';
    }
};

int main() {
    using Map      = boost::icl::interval_map<int, Ints>;
    using Interval = Map::interval_type::type;
    Map m;

    std::cout << m << "\n";

    mix(m, { {Interval::closed(1,3), {1}},
             {Interval::closed(2,4), {2}},
             {Interval::closed(5,7), {3}},
             {Interval::closed(6,8), {4}} });

    std::cout << m << "\n";

    mix(m, { {Interval::closed(3,6), {42}} });

    std::cout << m << "\n";
}
</code>```

Title: boost::icl::interval_map union on overlap

Body:
Is it possible to make interval_map with following accumulative behavior:

[1..3]->1 +
[2..4]->2 +
[5..7]->3 +
[6..8]->4
=
[1..4]->{1,2}, [5..8]->{3,4}
+
[3..6]->42
=
[1..8]->{1,2,3,4,42}

Body:
I think I've struggled with a very similar question before and couldn't find a library-supported way.

PS. Found that post boost::multi_index_container, operations on std::set inside container

It's interesting to compare because it basically does similar interval-consolidating but at the time of query. This has benefits (it retains insertion history so you can query other results that benefit from non-lossy storage). It also trades insertion efficiency for more query cost.

I'd probably write the insertion/combination operation myself.

I've tried to come up with a descriptive name here. Since the operation feels similar to landing "drops" into bigger "pools", I called the operation mix:

template <typename Map, typename V = typename Map::segment_type>
void mix(Map& m, std::initializer_list<V> drops) {
    typename Map::codomain_combine combine;

    for (auto drop : drops) {
        // combine with all overlapping existing segments
        auto range = m.equal_range(drop.first);

        for (auto it = range.first; it != range.second; ++it) {
            combine(drop.second, it->second);
            drop.first = hull(drop.first, it->first);
        }

        m.set(drop); // logically equivalent to m.add(drop) here
    }
}

With this you can articulate your desired behaviour like so:

int main() {
    using Map      = boost::icl::interval_map<int, Ints>;
    using Interval = Map::interval_type::type;
    Map m;

    std::cout << m << "\n";

    mix(m, { {Interval::closed(1,3), {1}},
             {Interval::closed(2,4), {2}},
             {Interval::closed(5,7), {3}},
             {Interval::closed(6,8), {4}} });

    std::cout << m << "\n";

    mix(m, { {Interval::closed(3,6), {42}} });

    std::cout << m << "\n";
}

And the output will be

{}
{([1,4]->{1,2,})([5,8]->{3,4,})}
{([1,8]->{1,2,3,4,42,})}

Full Demo

Live On Coliru

#include <boost/icl/interval_map.hpp>
#include <set>
#include <iostream>

template <typename Map, typename V = typename Map::segment_type>
void mix(Map& m, std::initializer_list<V> drops) {
    typename Map::codomain_combine combine;

    for (auto drop : drops) {
        // combine with all overlapping existing segments
        auto range = m.equal_range(drop.first);

        for (auto it = range.first; it != range.second; ++it) {
            combine(drop.second, it->second);
            drop.first = hull(drop.first, it->first);
        }

        m.set(drop); // logically equivalent to m.add(drop) here
    }
}

// For debug: an ostreamable std::set<int>
struct Ints : std::set<int> {
    using std::set<int>::set;

    friend std::ostream& operator<<(std::ostream& os, Ints const& s) {
        os << '{';
        for(auto i : s) os << i << ",";
        return os << '}';
    }
};

int main() {
    using Map      = boost::icl::interval_map<int, Ints>;
    using Interval = Map::interval_type::type;
    Map m;

    std::cout << m << "\n";

    mix(m, { {Interval::closed(1,3), {1}},
             {Interval::closed(2,4), {2}},
             {Interval::closed(5,7), {3}},
             {Interval::closed(6,8), {4}} });

    std::cout << m << "\n";

    mix(m, { {Interval::closed(3,6), {42}} });

    std::cout << m << "\n";
}


问:
Docker compose build error - Project file does not exist
I'm trying to create docker compose which run my ASP.NET Core app and mssql, but I'm getting an error during build.

Here's my docker compose file:

```<code># Build Stage
FROM microsoft/aspnetcore-build:latest as build-env
WORKDIR /source
COPY . .
RUN dotnet restore ./Travelingowe.sln
RUN dotnet publish --output ${source:-obj/Docker/publish} --configuration Release

# Publish Stage
FROM microsoft/aspnetcore:latest
COPY --from=build-env ./obj/Docker/publish /app
WORKDIR /app
ENTRYPOINT ["dotnet", "Api.dll"]
</code>```

when I run in CMD -> docker-compose up I'm getting:

```<code>Building api
Step 1/9 : FROM microsoft/aspnetcore-build:latest as build-env
 ---> d6273f7c44d4
Step 2/9 : WORKDIR /source
 ---> Using cache
 ---> 978f1c31e14a
Step 3/9 : COPY . .
 ---> Using cache
 ---> bcc750adcb99
Step 4/9 : RUN dotnet restore ./Travelingowe.sln
 ---> Running in 764199859de4
MSBUILD : error MSB1009: Project file does not exist.
Switch: ./Travelingowe.sln
ERROR: Service 'api' failed to build: The command '/bin/sh -c dotnet restore ./Travelingowe.sln' returned a non-zero code: 1
</code>```

Do you have any ide what is wrong?

Thanks!

UPDATE:
My project files:

答: you have issues with your working directory try using absolute path instead of relative path in your working directory in docker file </p>

Body:
I'm trying to create docker compose which run my ASP.NET Core app and mssql, but I'm getting an error during build.

Here's my docker compose file:

# Build Stage
FROM microsoft/aspnetcore-build:latest as build-env
WORKDIR /source
COPY . .
RUN dotnet restore ./Travelingowe.sln
RUN dotnet publish --output ${source:-obj/Docker/publish} --configuration Release

# Publish Stage
FROM microsoft/aspnetcore:latest
COPY --from=build-env ./obj/Docker/publish /app
WORKDIR /app
ENTRYPOINT ["dotnet", "Api.dll"]

when I run in CMD -> docker-compose up I'm getting:

Building api
Step 1/9 : FROM microsoft/aspnetcore-build:latest as build-env
 ---> d6273f7c44d4
Step 2/9 : WORKDIR /source
 ---> Using cache
 ---> 978f1c31e14a
Step 3/9 : COPY . .
 ---> Using cache
 ---> bcc750adcb99
Step 4/9 : RUN dotnet restore ./Travelingowe.sln
 ---> Running in 764199859de4
MSBUILD : error MSB1009: Project file does not exist.
Switch: ./Travelingowe.sln
ERROR: Service 'api' failed to build: The command '/bin/sh -c dotnet restore ./Travelingowe.sln' returned a non-zero code: 1

Do you have any ide what is wrong?

Thanks!

UPDATE:
My project files:


问:
Adding files to a nested zip python
I have a child.zip inside another zip master.zip
I want to add a file str.txt  to the child.zip

The structure is something like this:

master.zip

child.zip

str.txt

Here is my attempts:

```<code>def writeadapt():
    with zipfile.ZipFile('master.zip','a', zipfile.ZIP_DEFLATED) as zfile:
        for name in zfile.namelist():
            if re.search(r'\.zip$', name ) != None:
                zfiledata = io.BytesIO(zfile.read(name))
                with zipfile.ZipFile(zfiledata , 'a', zipfile.ZIP_DEFLATED) as zfile2:
                    zfile2.writestr('str.txt',"hello")
                    zfile2.close()
</code>```

The code does not add the file str.txt to child.zip.

What is the best way to add a file to a nested zip ?

答:
I have a child.zip inside another zip master.zip I want to add a file str.txt to the child.zip

If at all possible, you need to rethink this design altogether.

Adding a file to a ZIP archive requires the archive to be written to. However, files stored within ZIP archives are not writable -- they can be replaced with new files, but not updated in place -- so it is not possible to directly write a file to a nested ZIP archive.

Your code is not working as expected because updating the ZIP archive in zfiledata does not update the corresponding data in the parent archive. (It is, after all, just a BytesIO object.) You would need to write that data back to the parent archive to persist your changes. However, as I noted previously, this will be a slow and expensive operation -- particularly if the archive is large -- so it should be avoided.

Title: Adding files to a nested zip python

Body:
I have a child.zip inside another zip master.zip
I want to add a file str.txt  to the child.zip

The structure is something like this:

master.zip

child.zip

str.txt

Here is my attempts:

def writeadapt():
    with zipfile.ZipFile('master.zip','a', zipfile.ZIP_DEFLATED) as zfile:
        for name in zfile.namelist():
            if re.search(r'\.zip$', name ) != None:
                zfiledata = io.BytesIO(zfile.read(name))
                with zipfile.ZipFile(zfiledata , 'a', zipfile.ZIP_DEFLATED) as zfile2:
                    zfile2.writestr('str.txt',"hello")
                    zfile2.close()

The code does not add the file str.txt to child.zip.

What is the best way to add a file to a nested zip ?


问:
Python attribute name with a variable in it
I am making a desktop programm with Qt+Python and currently I am facing a problem calling some attributes with variable in their names

```<code>self.checkBox_Answer1.clear()
self.checkBox_Answer2.clear()
self.checkBox_Answer3.clear()
self.checkBox_Answer4.clear()
</code>```

Number is the variable, so I want something like

```<code>self."checkBox_Answer%d" % (A).clear()
</code>```

where "A" is my variable which is counted, but coding this way doesnt work

Also tried

```<code>self.str("checkBox_Answer"+"%d" % (A)).clear()
self.checkBox_Answer+"%d" % (A).clear()
</code>```

and nothing works

I know I can do something like

```<code>if A == 1:
    self.checkBox_Answer1.clear()
if A == 2:
    self.checkBox_Answer2.clear()
if A == 3:
    self.checkBox_Answer3.clear()
if A == 4:
    self.checkBox_Answer4.clear()
</code>```

But isn't there more pythonic way to do this stuff?

答:
I would store these variables in a list:

```<code>self.checkboxAnswers = [checkBox_Answer1,etc...]

self.checkboxAnswers[A].clear()
</code>```

You can access these variables in the list by using A. Note that lists start at index 0, so you'll have to increment A by one.

Body:
I am making a desktop programm with Qt+Python and currently I am facing a problem calling some attributes with variable in their names

self.checkBox_Answer1.clear()
self.checkBox_Answer2.clear()
self.checkBox_Answer3.clear()
self.checkBox_Answer4.clear()

Number is the variable, so I want something like

self."checkBox_Answer%d" % (A).clear()

where "A" is my variable which is counted, but coding this way doesnt work

Also tried

self.str("checkBox_Answer"+"%d" % (A)).clear()
self.checkBox_Answer+"%d" % (A).clear()

and nothing works

I know I can do something like

if A == 1:
    self.checkBox_Answer1.clear()
if A == 2:
    self.checkBox_Answer2.clear()
if A == 3:
    self.checkBox_Answer3.clear()
if A == 4:
    self.checkBox_Answer4.clear()

But isn't there more pythonic way to do this stuff?

Body:
I would store these variables in a list:

self.checkboxAnswers = [checkBox_Answer1,etc...]

self.checkboxAnswers[A].clear()

You can access these variables in the list by using A. Note that lists start at index 0, so you'll have to increment A by one.


问:
How to connect a Zebra TLP 2844-Z label printer to Windows 7 laptop?
The title is the basic info. I made a Python program on my Windows 7 computer that prints out labels, and it works when I connect my own printer to it. However, I tried connecting a label printer that is the one I mentioned in the title, and for some reason it's not working. My device manager categorizes it as unspecified, and trying to print with it won't work. This is an old model that was discontinued, so I tried finding a driver for it. Even that didn't work. Does someone have any suggestions? Thanks.</p>

答: Pull down the driver for a GK420d printer. Basically all Zebra ZPL printers use the same driver. If that driver does not recognize your printer automatically just manually install the GK420d driver and point it at your printer.</p>


问:
tool to auto-correct addresses of manually modified disassembled assembly
I have an .obj and I disassemble it (I do not have the original source file).

I modify the resulting assembly file by inserting my own assembly at certain instructions of interest, taking care to push/pop to the stack registers I use so I do not thrash the original content.

Why? Maybe I want to toggle a pin whenever a certain assembly instruction is executed (in real-time i.e. no debugger/JTAG).

Then, I want to assemble it back to .obj but since I've inserted my own assembly, the relative addresses for branches are incorrect now.

QUESTION

Is there an ARM tool that will auto-correct the relative addresses or do I have to do it manually as I insert my assembly?

This is for ARM Cortex M4 but I don't think it should matter.

答:
Use a disassembler that inserts labels for branch targets.  For x86, Agner Fog's objconv disassembler does this (sample output).

Look for something similar for ARM, so you get asm output that can be re-assembled and linked, with addressing re-calculated.  (IDK if any exist, but maybe you can hack that into one of the existing disassemblers.)

But beware that it's not just branch instructions that can be affected by inserting new code.  Any code with static addresses as immediates will be affected by changes to data layout.  On ARM, constants are often loaded with PC-relative loads from nearby literal pools, so those need to use labels as well.


问:
Working with nested await in javascript
I am implementing cache using MongoDB in-memory and MongoDB database in Nodejs application using mongoose. Here Nodejs 8.9 is used with async/await support.

```<code>let get_func = async(userId) => {

    let is_cached = await cache_user.findOne({ user_id: userId });

    if(!is_cached){
        console.log("NOT CACHIED");
        let is_dbuser = await db_user.find({});
        console.log(is_dbuser);

    } else {
        console.log("CACHED");
    }

    console.log("LEAVING get_func")
};

get_func(100);
</code>```

And here's the output:

```<code>NOT CACHIED
[]
LEAVING get_func
</code>```

However db_user is filled with data and was able to verify using:

```<code>db_user.find({}, function(err, users) {
   if (err) throw err;
   console.log(users);
});
</code>```

Moreover checked with let is_error, is_dbuser = await db_user.find({}); if there's a doubt that function returns error and results in that order.

What's the way I should handle this nested await statement. (However it seems function is waiting for second await as expected).

答:
do this instead

```<code>let get_func = async (userId) => {

    let is_cached = await cache_user.findById(userId);

    if(!is_cached){
        console.log("NOT CACHIED");
        let is_dbuser = await db_user.find({});
        console.log(is_dbuser);

    } else {
        console.log("CACHED");
    }

    console.log("LEAVING get_func")
};

get_func(100);
</code>```

please take note that it makes more sense to use findById unless it doesn't satisfy your query requirements and also async may require space before the parenthesis

Title: Working with nested await in javascript

Body:
I am implementing cache using MongoDB in-memory and MongoDB database in Nodejs application using mongoose. Here Nodejs 8.9 is used with async/await support.

let get_func = async(userId) => {

    let is_cached = await cache_user.findOne({ user_id: userId });

    if(!is_cached){
        console.log("NOT CACHIED");
        let is_dbuser = await db_user.find({});
        console.log(is_dbuser);

    } else {
        console.log("CACHED");
    }

    console.log("LEAVING get_func")
};

get_func(100);

And here's the output:

NOT CACHIED
[]
LEAVING get_func

However db_user is filled with data and was able to verify using:

db_user.find({}, function(err, users) {
   if (err) throw err;
   console.log(users);
});

Moreover checked with let is_error, is_dbuser = await db_user.find({}); if there's a doubt that function returns error and results in that order.

What's the way I should handle this nested await statement. (However it seems function is waiting for second await as expected).

Body:
do this instead

let get_func = async (userId) => {

    let is_cached = await cache_user.findById(userId);

    if(!is_cached){
        console.log("NOT CACHIED");
        let is_dbuser = await db_user.find({});
        console.log(is_dbuser);

    } else {
        console.log("CACHED");
    }

    console.log("LEAVING get_func")
};

get_func(100);

please take note that it makes more sense to use findById unless it doesn't satisfy your query requirements and also async may require space before the parenthesis


问:
Jquery accordion animation stops it working
I have a jquery accordion that works fine without animation:

```<code>jQuery('#countrylist').accordion({
    active: false,
    alwaysOpen: false,
    autoHeight: false,
    animated: false
});
</code>```

But if I try to use animation it no longer works:

```<code>jQuery('#countrylist').accordion({
   active: false,
   alwaysOpen: false,
   autoHeight: false,
   animated: "bounceslide"
});
</code>```

Now clicking on one of the heading links no longer opens that div, it doesn't do anything.

Any ideas why this might happen?

答:
According to the documentation, you need to include UI Effects Core in your page as well:

Choose your favorite animation, or
  disable them (set to false). In
  addition to the default, 'bounceslide'
  and all defined easing methods are
  supported ('bounceslide' requires UI
  Effects Core)

(emphasis mine)

I'm pretty sure this is it since your code works fine for me when I include jQueryUI in its entirety: http://jsfiddle.net/andrewwhitaker/86xGs/1/

Body:
I have a jquery accordion that works fine without animation:

jQuery('#countrylist').accordion({
    active: false,
    alwaysOpen: false,
    autoHeight: false,
    animated: false
});

But if I try to use animation it no longer works:

jQuery('#countrylist').accordion({
   active: false,
   alwaysOpen: false,
   autoHeight: false,
   animated: "bounceslide"
});

Now clicking on one of the heading links no longer opens that div, it doesn't do anything.

Any ideas why this might happen?


问:
How to convert IPython notebooks to PDF and HTML?
I want to convert my ipython-notebooks to print them, or simply send them in html format. I have noticed that there exists a tool to do that already, nbconvert. Although I have downloaded it, I have no idea how to convert the notebook, with nbconvert2.py since nbconvert says that it is deprecated. nbconvert2.py says that I need a profile to convert the notebook, what is it? Does there exist a documentation about this tool?</p>

答:
I've been searching for a way to save notebooks as html, since whenever I try to download as html with my new Jupyter installation, I always get a 500 : Internal Server Error The error was: nbconvert failed: validate() got an unexpected keyword argument 'relax_add_props' error. Oddly enough, I've found that downloading as html is as simple as:

Left click in the notebook

Click 'Save As...' in the dropdown menu

Save accordingly

No print preview, no print, no nbconvert. Using Jupyter Version: 1.0.0. Just a suggestion to try (obviously not all setups are the same).

ContentLicense: CC BY-SA 4.0


问:
Prime number test for numbers 1 - 1000
As a homework I have to write a prime number test, that gives back a "true" or "false" statement. The tricky thing is, I have to write a csv.-file that includes the "true" and "false" statements for the numbers 1 to 1000.
I used this code for the prime number test

```<code>def Primzahl(n):
if n < 2:
    return False
if n == 2:
    return True
if not n & 1:
    return False
for x in range(3, int(n**0.5) + 1, 2):
    if n % x == 0:
        return False
return True
</code>```

and

```<code>for i in range (1,1001):
    Primzahl (i)
    print (i)
</code>```

My for-loop only gives out the numbers 1,1000 but not the true or false statements. Do I have to include if and else in my for loop? Can anyone help?

答: The problem is print(i). That will write i, which is the number from your range call. You will also need to print the value returned by your function, e.g. print(Primzahl(i)).

Title: Prime number test for numbers 1 - 1000

Body:
As a homework I have to write a prime number test, that gives back a "true" or "false" statement. The tricky thing is, I have to write a csv.-file that includes the "true" and "false" statements for the numbers 1 to 1000.
I used this code for the prime number test

def Primzahl(n):
if n < 2:
    return False
if n == 2:
    return True
if not n & 1:
    return False
for x in range(3, int(n**0.5) + 1, 2):
    if n % x == 0:
        return False
return True

and

for i in range (1,1001):
    Primzahl (i)
    print (i)

My for-loop only gives out the numbers 1,1000 but not the true or false statements. Do I have to include if and else in my for loop? Can anyone help?


问:
react component method binding with arrow function (class properties)
I heard that this is the cool way to define function instead of binding them in constructor:

```<code>class Comp extends React.Component {
    delete = id => {

    }

    render() {}
}
</code>```

but when I try to build I get:

Module build failed: SyntaxError: Unexpected token (7:15)

pointing to equal sign after delete

what I am missing?

答:
To define class properties the way you are doing it, you need to activate the experimental babel feature transform-class-properties. This allows you to assign expressions like arrrow functions to class properties:

```<code>class Bork {
    //Property initializer syntax
    instanceProperty = "bork";
    boundFunction = () => {
      return this.instanceProperty;
    }

    //Static class properties
    static staticProperty = "babelIsCool";
    static staticFunction = function() {
      return Bork.staticProperty;
    }
  }
</code>```

Note that this feature is not yet part of the ECMAScript specification and may change in the future.

Body:
I heard that this is the cool way to define function instead of binding them in constructor:

class Comp extends React.Component {
    delete = id => {

    }

    render() {}
}

but when I try to build I get:

Module build failed: SyntaxError: Unexpected token (7:15)

pointing to equal sign after delete

what I am missing?

Body:
To define class properties the way you are doing it, you need to activate the experimental babel feature transform-class-properties. This allows you to assign expressions like arrrow functions to class properties:

class Bork {
    //Property initializer syntax
    instanceProperty = "bork";
    boundFunction = () => {
      return this.instanceProperty;
    }

    //Static class properties
    static staticProperty = "babelIsCool";
    static staticFunction = function() {
      return Bork.staticProperty;
    }
  }

Note that this feature is not yet part of the ECMAScript specification and may change in the future.


问:
How to prevent multiple instances of the Root-Widget in Kivy
OK, I try to make my first App in Kivy and I have a Problem with multiple Instances of my Root Widget.

I need to add widgets to my app while running. (to display a spreadsheet)

But because of the multiple instances of the Root Widget, I can't access the widgets with the kivy ids lookup object.

https://kivy.org/docs/guide/lang.html

I made three Buttons to display the problem in the console
Button -1-, -2-, and -3-

Please explain me why there are multiple instances and how I can prevent it, so the code will work.

Thanks for your help!

File --> Match.py

```<code>    #!python
    from __future__ import print_function
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.properties import ObjectProperty, StringProperty
    from kivy.uix.boxlayout import BoxLayout
    from kivy.app import App
    import gc

    class my_gc():
        def search_g(self):
            for obj in gc.get_objects():
                if isinstance(obj, Root):
                    try:
                        print(obj.ids)
                    except:
                        print('fail')

    #Root Widget
    class Root(BoxLayout):

        sm = ObjectProperty(None)
        sc0 = ObjectProperty(None)
        sc1 = ObjectProperty(None)
        sc2 = ObjectProperty(None)
        sc3 = ObjectProperty(None)

        mylbl0 = StringProperty('screen 0')
        mylbl1 = StringProperty('screen 1')
        mylbl2 = StringProperty('screen 2')
        mylbl3 = StringProperty('screen 3')

        def find_ids(self):
            print(self.ids)

    class Screen_Manager(ScreenManager):
        pass

    class Screen_0(Screen):
        pass

    class Screen_1(Screen):
        pass

    class Screen_2(Screen):
        pass

    class Screen_3(Screen):
        pass

    class Match(App):
        rootwidget = Root()
        sm = Screen_Manager()
        gc = my_gc()

        def build(self):
            pass

    Match().run()
</code>```

File --> Match.kv

```<code>    #Root Widget (BoxLayout)
    Root:
        sm: sm
        sc1: sc0
        sc1: sc1
        sc1: sc2
        sc1: sc3
        BoxLayout:
            spacing: '20dp'
            orientation: 'vertical'
            Screen_Manager:
                id: sm
                Screen_0:
                    id: sc0
                    name: 'sc0'
                    manager: 'sm'
                    BoxLayout:
                        id: box_0-0
                        Label:
                            id: lbl_0
                            text: app.rootwidget.mylbl0
                        Label:
                            id: lbl_0-1
                            text: root.mylbl0
                Screen_1:
                    id: sc1
                    name: 'sc1'
                    manager: 'sm'
                    Label:
                        id: lbl1
                        text: root.mylbl1
                Screen_2:
                    id: sc2
                    name: 'sc2'
                    manager: 'sm'
                    Label:
                        id: lbl2
                        text: root.mylbl2
                Screen_3:
                    id: sc3
                    name: 'sc3'
                    manager: 'sm'
                    Label:
                        id: lbl3
                        text: root.mylbl3

            #Tab-Buttons
            BoxLayout:
                size_hint: 1 , None
                height: '60dp'
                orientation: 'horizontal'
                Button:
                    text: '-0-'
                    on_press: root.sm.current = sc0.name
                Button:
                    text: '-1-'
                    on_press: root.sm.current = sc1.name
                Button:
                    text: '-2-'
                    on_press: root.sm.current = sc2.name
                Button:
                    text: '-3-'
                    on_press: root.sm.current = sc3.name
                Button:
                    text: '<'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: root.sm.current = root.sm.previous()
                Button:
                    text: '>'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: root.sm.current = root.sm.next()
                Button:
                    text: '-b1-'
                    size_hint: None , 1
                    width: '60dp'
                    #on_press: root.search_g()              #<-- doesn't work
                    on_press: app.gc.search_g()             #<-- works
                Button:
                    text: '-b2-'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: root.find_ids()               #<-- doesn't work
                    on_press: app.rootwidget.find_ids()     #<-- works
                Button:
                    text: '-b3-'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: print(root.mylbl1)            #<-- works
                    on_press: print(app.rootwidget.mylbl1)  #<-- works
</code>```

答:
Mutilple Instance - Root Widget

As per your code, you don't have mutiple instances of the root widget. Your root widget is Root: as per the kv file, match.kv.

root.search_g()

It doesn't work because your root which is the class Root(BoxLayout) does not have the search_g() method.

root.find_ids - works

When I commented off app.rootwidget.find_ids, the call to root.find_ids works i.e. it printed the ids. The keyword root is available only in rule definitions and represents the root widget of the rule (the first instance of the rule). When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in self.ids dictionary type property.

app.rootwidget.find_ids

It works but there were no ids because it is referencing to the method find_ids in the initiated object, class Root. The rootwidget is just a variable by name and it is a different object than the one from Root:

From the attached screen shot, you will notice that the object locations for root.find_ids and app.rootwidget.find_ids are different.

Adding Widgets Dynamically

To add widgets dynamically into your app while it is running, you have to do the following. For an example, please refer to my other post at Kivy/python : when i click row then it shows error IndexError: list index out of range

Python Script - match.py

Add an import statement as follow:

from kivy.properties import ObjectProperty

Declare a variable (e.g. container) or ObjectProperty type e.g. in the class Root

class Root(BoxLayout):
    container = ObjectProperty(None)

Remove all widgets added dynamically before adding

Add widgets dynamically.

kv File - match.kv

Define a layout e.g. BoxLayout or GridLayout in your kv file.

Give an id to the layout e.g. container in your kv file.

Hook up the ObjectProperty to the id

Root:
    container: container
...
    # Container for adding widgets dynamically
    BoxLayout:
        id: container

Solution

The solution is to declare an ObjectProperty, rootwidget as follow:

snippet

```<code>class Match(App):
    rootwidget = ObjectProperty(None)
    title = "Solution App"

    gc = my_gc()

    def build(self):
        self.rootwidget = Root()
        return self.rootwidget
</code>```

match.py

```<code>#!python
from __future__ import print_function
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
import gc

class my_gc():
    def search_g(self):
        print("my_gc.search_g called")
        for obj in gc.get_objects():
            if isinstance(obj, Root):
                try:
                    print("obj={0}, ids={1}".format(obj, obj.ids))
                    for key, value in obj.ids.items():
                        print("   key={0}, value={1}".format(key, value))
                except:
                    print('fail')

# Root Widget
class Root(BoxLayout):
    sm = ObjectProperty(None)
    sc0 = ObjectProperty(None)
    sc1 = ObjectProperty(None)
    sc2 = ObjectProperty(None)
    sc3 = ObjectProperty(None)

    mylbl0 = StringProperty('screen 0')
    mylbl1 = StringProperty('screen 1')
    mylbl2 = StringProperty('screen 2')
    mylbl3 = StringProperty('screen 3')

    def find_ids(self):
        print("Root.find_ids called")
        print("self={0}, self.ids={1}".format(self, self.ids))
        for key, value in self.ids.items():
            print("   key={0}, value={1}".format(key, value))

class Screen_Manager(ScreenManager):
    pass

class Screen_0(Screen):
    pass

class Screen_1(Screen):
    pass

class Screen_2(Screen):
    pass

class Screen_3(Screen):
    pass

class Match(App):
    rootwidget = ObjectProperty(None)
    title = "Solution App"

    gc = my_gc()

    def build(self):
        self.rootwidget = Root()
        return self.rootwidget

if __name__ == "__main__":
    Match().run()
</code>```

match.kv

```<code>#Root Widget (BoxLayout)
<Root>:
    sm: sm
    sc1: sc0
    sc1: sc1
    sc1: sc2
    sc1: sc3

    BoxLayout:
        spacing: '20dp'
        orientation: 'vertical'
        Screen_Manager:
            id: sm
            Screen_0:
                id: sc0
                name: 'sc0'
                manager: 'sm'
                BoxLayout:
                    id: box_0-0
                    Label:
                        id: lbl_0
                        text: root.mylbl0
                    Label:
                        id: lbl_0-1
                        text: root.mylbl0
            Screen_1:
                id: sc1
                name: 'sc1'
                manager: 'sm'
                Label:
                    id: lbl1
                    text: root.mylbl1
            Screen_2:
                id: sc2
                name: 'sc2'
                manager: 'sm'
                Label:
                    id: lbl2
                    text: root.mylbl2
            Screen_3:
                id: sc3
                name: 'sc3'
                manager: 'sm'
                Label:
                    id: lbl3
                    text: root.mylbl3

        #Tab-Buttons
        BoxLayout:
            id: secondBoxLayout
            size_hint: 1 , None
            height: '60dp'
            orientation: 'horizontal'
            Button:
                text: '-0-'
                on_press: root.sm.current = sc0.name
            Button:
                text: '-1-'
                on_press: root.sm.current = sc1.name
            Button:
                text: '-2-'
                on_press: root.sm.current = sc2.name
            Button:
                text: '-3-'
                on_press: root.sm.current = sc3.name
            Button:
                text: '<'
                size_hint: None , 1
                width: '60dp'
                on_press: root.sm.current = root.sm.previous()
            Button:
                text: '>'
                size_hint: None , 1
                width: '60dp'
                on_press: root.sm.current = root.sm.next()
            Button:
                text: '-b1-'
                size_hint: None , 1
                width: '60dp'
                on_press:
                    print("\non_press: {}".format(self.text))
                    # root.search_g()              #<-- doesn't work
                    print("    app.gc_search_g()")
                    app.gc.search_g()             #<-- works
            Button:
                text: '-b2-'
                size_hint: None , 1
                width: '60dp'
                on_press:
                    print("\non_press: {}".format(self.text))
                    print("    root.find_ids()")
                    root.find_ids()               #<-- works
                    print("\n    app.root.find_ids()")
                    app.rootwidget.find_ids()     #<-- works
            Button:
                text: '-b3-'
                size_hint: None , 1
                width: '60dp'
                on_press:
                    print("\non_press: {}".format(self.text))
                    print(root.mylbl1)            #<-- works
                    print(app.rootwidget.mylbl1)  #<-- works
</code>```

Output

Body:
OK, I try to make my first App in Kivy and I have a Problem with multiple Instances of my Root Widget.

I need to add widgets to my app while running. (to display a spreadsheet)

But because of the multiple instances of the Root Widget, I can't access the widgets with the kivy ids lookup object.

https://kivy.org/docs/guide/lang.html

I made three Buttons to display the problem in the console
Button -1-, -2-, and -3-

Please explain me why there are multiple instances and how I can prevent it, so the code will work.

Thanks for your help!

File --> Match.py

    #!python
    from __future__ import print_function
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.properties import ObjectProperty, StringProperty
    from kivy.uix.boxlayout import BoxLayout
    from kivy.app import App
    import gc

    class my_gc():
        def search_g(self):
            for obj in gc.get_objects():
                if isinstance(obj, Root):
                    try:
                        print(obj.ids)
                    except:
                        print('fail')

    #Root Widget
    class Root(BoxLayout):

        sm = ObjectProperty(None)
        sc0 = ObjectProperty(None)
        sc1 = ObjectProperty(None)
        sc2 = ObjectProperty(None)
        sc3 = ObjectProperty(None)

        mylbl0 = StringProperty('screen 0')
        mylbl1 = StringProperty('screen 1')
        mylbl2 = StringProperty('screen 2')
        mylbl3 = StringProperty('screen 3')

        def find_ids(self):
            print(self.ids)

    class Screen_Manager(ScreenManager):
        pass

    class Screen_0(Screen):
        pass

    class Screen_1(Screen):
        pass

    class Screen_2(Screen):
        pass

    class Screen_3(Screen):
        pass

    class Match(App):
        rootwidget = Root()
        sm = Screen_Manager()
        gc = my_gc()

        def build(self):
            pass

    Match().run()

File --> Match.kv

    #Root Widget (BoxLayout)
    Root:
        sm: sm
        sc1: sc0
        sc1: sc1
        sc1: sc2
        sc1: sc3
        BoxLayout:
            spacing: '20dp'
            orientation: 'vertical'
            Screen_Manager:
                id: sm
                Screen_0:
                    id: sc0
                    name: 'sc0'
                    manager: 'sm'
                    BoxLayout:
                        id: box_0-0
                        Label:
                            id: lbl_0
                            text: app.rootwidget.mylbl0
                        Label:
                            id: lbl_0-1
                            text: root.mylbl0
                Screen_1:
                    id: sc1
                    name: 'sc1'
                    manager: 'sm'
                    Label:
                        id: lbl1
                        text: root.mylbl1
                Screen_2:
                    id: sc2
                    name: 'sc2'
                    manager: 'sm'
                    Label:
                        id: lbl2
                        text: root.mylbl2
                Screen_3:
                    id: sc3
                    name: 'sc3'
                    manager: 'sm'
                    Label:
                        id: lbl3
                        text: root.mylbl3

            #Tab-Buttons
            BoxLayout:
                size_hint: 1 , None
                height: '60dp'
                orientation: 'horizontal'
                Button:
                    text: '-0-'
                    on_press: root.sm.current = sc0.name
                Button:
                    text: '-1-'
                    on_press: root.sm.current = sc1.name
                Button:
                    text: '-2-'
                    on_press: root.sm.current = sc2.name
                Button:
                    text: '-3-'
                    on_press: root.sm.current = sc3.name
                Button:
                    text: '<'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: root.sm.current = root.sm.previous()
                Button:
                    text: '>'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: root.sm.current = root.sm.next()
                Button:
                    text: '-b1-'
                    size_hint: None , 1
                    width: '60dp'
                    #on_press: root.search_g()              #<-- doesn't work
                    on_press: app.gc.search_g()             #<-- works
                Button:
                    text: '-b2-'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: root.find_ids()               #<-- doesn't work
                    on_press: app.rootwidget.find_ids()     #<-- works
                Button:
                    text: '-b3-'
                    size_hint: None , 1
                    width: '60dp'
                    on_press: print(root.mylbl1)            #<-- works
                    on_press: print(app.rootwidget.mylbl1)  #<-- works

Body:
Mutilple Instance - Root Widget

As per your code, you don't have mutiple instances of the root widget. Your root widget is Root: as per the kv file, match.kv.

root.search_g()

It doesn't work because your root which is the class Root(BoxLayout) does not have the search_g() method.

root.find_ids - works

When I commented off app.rootwidget.find_ids, the call to root.find_ids works i.e. it printed the ids. The keyword root is available only in rule definitions and represents the root widget of the rule (the first instance of the rule). When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in self.ids dictionary type property.

app.rootwidget.find_ids

It works but there were no ids because it is referencing to the method find_ids in the initiated object, class Root. The rootwidget is just a variable by name and it is a different object than the one from Root:

From the attached screen shot, you will notice that the object locations for root.find_ids and app.rootwidget.find_ids are different.

Adding Widgets Dynamically

To add widgets dynamically into your app while it is running, you have to do the following. For an example, please refer to my other post at Kivy/python : when i click row then it shows error IndexError: list index out of range

Python Script - match.py

Add an import statement as follow:

from kivy.properties import ObjectProperty

Declare a variable (e.g. container) or ObjectProperty type e.g. in the class Root

class Root(BoxLayout):
    container = ObjectProperty(None)

Remove all widgets added dynamically before adding

Add widgets dynamically.

kv File - match.kv

Define a layout e.g. BoxLayout or GridLayout in your kv file.

Give an id to the layout e.g. container in your kv file.

Hook up the ObjectProperty to the id

Root:
    container: container
...
    # Container for adding widgets dynamically
    BoxLayout:
        id: container

Solution

The solution is to declare an ObjectProperty, rootwidget as follow:

snippet

class Match(App):
    rootwidget = ObjectProperty(None)
    title = "Solution App"

    gc = my_gc()

    def build(self):
        self.rootwidget = Root()
        return self.rootwidget

match.py

#!python
from __future__ import print_function
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
import gc

class my_gc():
    def search_g(self):
        print("my_gc.search_g called")
        for obj in gc.get_objects():
            if isinstance(obj, Root):
                try:
                    print("obj={0}, ids={1}".format(obj, obj.ids))
                    for key, value in obj.ids.items():
                        print("   key={0}, value={1}".format(key, value))
                except:
                    print('fail')

# Root Widget
class Root(BoxLayout):
    sm = ObjectProperty(None)
    sc0 = ObjectProperty(None)
    sc1 = ObjectProperty(None)
    sc2 = ObjectProperty(None)
    sc3 = ObjectProperty(None)

    mylbl0 = StringProperty('screen 0')
    mylbl1 = StringProperty('screen 1')
    mylbl2 = StringProperty('screen 2')
    mylbl3 = StringProperty('screen 3')

    def find_ids(self):
        print("Root.find_ids called")
        print("self={0}, self.ids={1}".format(self, self.ids))
        for key, value in self.ids.items():
            print("   key={0}, value={1}".format(key, value))

class Screen_Manager(ScreenManager):
    pass

class Screen_0(Screen):
    pass

class Screen_1(Screen):
    pass

class Screen_2(Screen):
    pass

class Screen_3(Screen):
    pass

class Match(App):
    rootwidget = ObjectProperty(None)
    title = "Solution App"

    gc = my_gc()

    def build(self):
        self.rootwidget = Root()
        return self.rootwidget

if __name__ == "__main__":
    Match().run()

match.kv

#Root Widget (BoxLayout)
<Root>:
    sm: sm
    sc1: sc0
    sc1: sc1
    sc1: sc2
    sc1: sc3

    BoxLayout:
        spacing: '20dp'
        orientation: 'vertical'
        Screen_Manager:
            id: sm
            Screen_0:
                id: sc0
                name: 'sc0'
                manager: 'sm'
                BoxLayout:
                    id: box_0-0
                    Label:
                        id: lbl_0
                        text: root.mylbl0
                    Label:
                        id: lbl_0-1
                        text: root.mylbl0
            Screen_1:
                id: sc1
                name: 'sc1'
                manager: 'sm'
                Label:
                    id: lbl1
                    text: root.mylbl1
            Screen_2:
                id: sc2
                name: 'sc2'
                manager: 'sm'
                Label:
                    id: lbl2
                    text: root.mylbl2
            Screen_3:
                id: sc3
                name: 'sc3'
                manager: 'sm'
                Label:
                    id: lbl3
                    text: root.mylbl3

        #Tab-Buttons
        BoxLayout:
            id: secondBoxLayout
            size_hint: 1 , None
            height: '60dp'
            orientation: 'horizontal'
            Button:
                text: '-0-'
                on_press: root.sm.current = sc0.name
            Button:
                text: '-1-'
                on_press: root.sm.current = sc1.name
            Button:
                text: '-2-'
                on_press: root.sm.current = sc2.name
            Button:
                text: '-3-'
                on_press: root.sm.current = sc3.name
            Button:
                text: '<'
                size_hint: None , 1
                width: '60dp'
                on_press: root.sm.current = root.sm.previous()
            Button:
                text: '>'
                size_hint: None , 1
                width: '60dp'
                on_press: root.sm.current = root.sm.next()
            Button:
                text: '-b1-'
                size_hint: None , 1
                width: '60dp'
                on_press:
                    print("\non_press: {}".format(self.text))
                    # root.search_g()              #<-- doesn't work
                    print("    app.gc_search_g()")
                    app.gc.search_g()             #<-- works
            Button:
                text: '-b2-'
                size_hint: None , 1
                width: '60dp'
                on_press:
                    print("\non_press: {}".format(self.text))
                    print("    root.find_ids()")
                    root.find_ids()               #<-- works
                    print("\n    app.root.find_ids()")
                    app.rootwidget.find_ids()     #<-- works
            Button:
                text: '-b3-'
                size_hint: None , 1
                width: '60dp'
                on_press:
                    print("\non_press: {}".format(self.text))
                    print(root.mylbl1)            #<-- works
                    print(app.rootwidget.mylbl1)  #<-- works

Output


问:
Loading DataGrid from XML data file
I have a problem with loading data from an XML file in a WPF application.

XAML:

```<code>                    <DataGrid Name="dataGrid" ItemsSource="{Binding Path=Elements[Person]}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Header="Name" Binding="{Binding Path=Element[name].Value}"  />
                        <DataGridCheckBoxColumn Header="Surname" Binding="{Binding Path=Element[surname].Value}"  />
                        <DataGridCheckBoxColumn Header="Date born" Binding="{Binding Path=Element[dateBorn].Value}" />
                    </DataGrid.Columns>
                </DataGrid>
</code>```

XML File:

```<code><Persons>
<Person>
<name>Test1</name>
<surname>Test11</surname>
<dateBorn>02.12.1990</dateBorn>
</Person>

<Person>
<name>Test2</name>
<surname>Test22</surname>
<dateBorn>10.12.1991</dateBorn>
</Person>

<Person>
<name>Test3</name>
<surname>Test3</surname>
<dateBorn>09.12.1992</dateBorn>
</Person>
</code>```

My code:

```<code>        var peopleList = XElement.Load(dataBaseURL);
        dataGrid1.DataContext = peopleList;
</code>```

I get empty cells and  I load data from <person> </person> tags.

答:
The bindings should be corrected as such:</p>

```<code><DataGrid Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn Header="Name" Binding="{Binding name}"  />
                    <DataGridCheckBoxColumn Header="Surname" Binding="{Binding surname}"  />
                    <DataGridCheckBoxColumn Header="Date born" Binding="{Binding dateBorn}" />
                </DataGrid.Columns>
            </DataGrid>
</code>```

Title: Loading DataGrid from XML data file

Body:
I have a problem with loading data from an XML file in a WPF application.

XAML:

                    <DataGrid Name="dataGrid" ItemsSource="{Binding Path=Elements[Person]}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Header="Name" Binding="{Binding Path=Element[name].Value}"  />
                        <DataGridCheckBoxColumn Header="Surname" Binding="{Binding Path=Element[surname].Value}"  />
                        <DataGridCheckBoxColumn Header="Date born" Binding="{Binding Path=Element[dateBorn].Value}" />
                    </DataGrid.Columns>
                </DataGrid>

XML File:

<Persons>
<Person>
<name>Test1</name>
<surname>Test11</surname>
<dateBorn>02.12.1990</dateBorn>
</Person>

<Person>
<name>Test2</name>
<surname>Test22</surname>
<dateBorn>10.12.1991</dateBorn>
</Person>

<Person>
<name>Test3</name>
<surname>Test3</surname>
<dateBorn>09.12.1992</dateBorn>
</Person>

My code:

        var peopleList = XElement.Load(dataBaseURL);
        dataGrid1.DataContext = peopleList;

I get empty cells and  I load data from <person> </person> tags.

Body:
The bindings should be corrected as such:

<DataGrid Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn Header="Name" Binding="{Binding name}"  />
                    <DataGridCheckBoxColumn Header="Surname" Binding="{Binding surname}"  />
                    <DataGridCheckBoxColumn Header="Date born" Binding="{Binding dateBorn}" />
                </DataGrid.Columns>
            </DataGrid>


问:
Set footer on bottom (adapted to content) with Angular 4 and Bootstrap 4
¿How can i make a footer stay on bottom of a website with the following structure?:

```<code><html>
    <head>
    </head>

    <body>
        <app-root></app-root>
    </body>

</html>
</code>```

So, the app-root is the main component in angular, inside this component i have the following structure:

```<code><app-navbar></app-navbar>
<div class="container">
    <div class="row">

        <div class="col-12 p-0">
            <app-information *ngIf="title == 'information'"></app-information>
            <app-form *ngIf="title == 'form'"></app-form>
            <app-proyects *ngIf="title == 'proyects'"></app-proyects>
            <app-blog *ngIf="title == 'blog'"></app-blog>
            <app-courses *ngIf="title == 'coursess'"></cursos>
        </div>

    </div>
</div>
<app-footer></app-footer>
</code>```

So, just for understanding, the divs inside the col-12 div are shown depending on a variable called title setted up by pressing buttons on the navbar.
The case is that not all of those divs have content that exceedes the screen size, and the footer goes upwards.

Inside my footer i have this structure:

```<code><footer class="bg-inf-blue" >
    <div class="container p-0">
        <div class="row text-white py-3">
            <div class="col-6 h6 p-0">Contact</div>
            <div class="col-6 h6">Social Media</div>
            <div class="col-2 p-0">
                <ul class="list-unstyled">
                    <li class="h6">Place 1</li>
                    <li>Place 1 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-2">
                <ul class="list-unstyled">
                    <li class="h6">Place 2</li>
                    <li>Place 2 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-2">
                <ul class="list-unstyled">
                    <li class="h6">Place 3</li>
                    <li>Place 3 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-6 align-items-center">
                <a href="https://www.facebook.com/address/" target="blank"><img src="../assets/facebook-logo-button.png" height="40px"></a>
                <a href="https://twitter.com/address" target="blank"><img src="../assets/twitter-logo-button.png" height="40px"></a>
            </div>
            <div class="col-12 p-0">
                <small>Lorem ipsum dolor sit amet consectetur</small>
            </div>
        </div>
    </div>
</footer>
</code>```

what i need is that the footer to stay on the bottom of the screen when the content between the  and  is too short to fill the screen.

If there's a solution with CSS, i'm working with Twitter Bootstrap 4, if there's a solution with typescript, i'm working with Angular 4.

答:
You can apply a sticky footer as described on the Twitter v4 example (https://v4-alpha.getbootstrap.com/examples/sticky-footer/).

Here is a short example:

HTML

```<code><footer class="footer">
 ...
</footer>
</code>```

CSS

```<code>html {
    position: relative;
    min-height: 100%;
}

body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  line-height: 60px;
}
</code>```

Body:
¿How can i make a footer stay on bottom of a website with the following structure?:

        <app-root></app-root>

So, the app-root is the main component in angular, inside this component i have the following structure:

<app-navbar></app-navbar>

            <app-information *ngIf="title == 'information'"></app-information>
            <app-form *ngIf="title == 'form'"></app-form>
            <app-proyects *ngIf="title == 'proyects'"></app-proyects>
            <app-blog *ngIf="title == 'blog'"></app-blog>
            <app-courses *ngIf="title == 'coursess'"></cursos>

<app-footer></app-footer>

So, just for understanding, the divs inside the col-12 div are shown depending on a variable called title setted up by pressing buttons on the navbar.
The case is that not all of those divs have content that exceedes the screen size, and the footer goes upwards.

Inside my footer i have this structure:

Contact

Social Media

Place 1

Place 1 address

XXX XXX-XXXX

Place 2

Place 2 address

XXX XXX-XXXX

Place 3

Place 3 address

XXX XXX-XXXX

                Lorem ipsum dolor sit amet consectetur

what i need is that the footer to stay on the bottom of the screen when the content between the  and  is too short to fill the screen.

If there's a solution with CSS, i'm working with Twitter Bootstrap 4, if there's a solution with typescript, i'm working with Angular 4.

Body:
You can apply a sticky footer as described on the Twitter v4 example (https://v4-alpha.getbootstrap.com/examples/sticky-footer/).

Here is a short example:

HTML

<footer class="footer">
 ...
</footer>

CSS

html {
    position: relative;
    min-height: 100%;
}

body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  line-height: 60px;
}


问:
Getting state of a text input when pressing enter key in React
I'm taking my first steps with React and I struggle with setting and getting states of an input element.

The application shall render a simple input element without a submit button.

When pressing Enter the current value of the text field shall be written to the console.

So far I've added two event handlers for onKeyUp (checking if Enter was pressed) and another for onChange to output the text field's value.

This is my current code:

```<code>import React, { Component } from "react";
import ReactDOM from "react-dom";

class Terminal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ""};
    this.handleChange = this.handleChange.bind(this);
  }

  handleKey(e) {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    return (
      <div>
        <span>My Prompt: > </span>
        <input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />
      </div>
    );
  }
}

ReactDOM.render(
  <Terminal />,
  document.getElementById("root")
);
</code>```

Pressing Enter is recognized but logging to the console gives me:

```<code>Uncaught TypeError: Cannot read property 'state' of undefined
    at handleKey (index.js:24)
</code>```

What am I missing here?

答:
just change thease:

```<code> onChange={this.handleChange}
 onKeyUp={this.handleKey}
</code>```

to

```<code> onChange={this.handleChange = this.handleChange.bind(this)}
 onKeyUp={this.handleKey = this.handleKey.bind(this)}`
</code>```

Body:
I'm taking my first steps with React and I struggle with setting and getting states of an input element.

The application shall render a simple input element without a submit button.

When pressing Enter the current value of the text field shall be written to the console.

So far I've added two event handlers for onKeyUp (checking if Enter was pressed) and another for onChange to output the text field's value.

This is my current code:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class Terminal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ""};
    this.handleChange = this.handleChange.bind(this);
  }

  handleKey(e) {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    return (

        My Prompt: >
        <input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />

    );
  }
}

ReactDOM.render(
  <Terminal />,
  document.getElementById("root")
);

Pressing Enter is recognized but logging to the console gives me:

Uncaught TypeError: Cannot read property 'state' of undefined
    at handleKey (index.js:24)

What am I missing here?

Body:
just change thease:

 onChange={this.handleChange}
 onKeyUp={this.handleKey}

to

 onChange={this.handleChange = this.handleChange.bind(this)}
 onKeyUp={this.handleKey = this.handleKey.bind(this)}`


问:
using the hardware rng from python
Are there any ready made libraries so that the intel hardware prng (rdrand) can be used by numpy programs to fill buffers of random numbers?

Failing this can someone point me in the right direction for some C code that I could adapt or use (I use CPython and Cython with numpy so the bare minimum wrapper shd be enough).

The random generators I want are uniform random numbers between [0,1).

答:
There is a paper available here (http://iopscience.iop.org/article/10.3847/1538-4357/aa7ede/meta;jsessionid=A9DA9DDB925E6522D058F3CEEC7D0B21.ip-10-40-2-120) and (non-paywalled version) here (https://arxiv.org/abs/1707.02212) that describes how to use Intel Secure Key, which is a cryptographically secure random number generator implemented on-chip.  It can be accessed via RdRand and RdSeed instructions.

But the author seems to say you should go for implementing it in C/C++ instead of Python.  The rdrand python module runs about 100x slower than the Python default random number generator, and about 1000x slower than the one in Numpy (paper section 5.2).

Title: using the hardware rng from python


问:
Turning back from update on SQL Server
There is any code from backing from update on SQL Server. I mean without triggers and logs.

KR,

Çağın

答: If you happen to have change data capture or audit logging, you can easily recover from a bad change. Or as suggested you can restore yesterday's backup to another instance and then copy the data as much as possible. If you don't have any of these things, perhaps you need to them set up for future problems. Or maybe even hire a database professional so you don't get caught like this again. And of course,  take all update, delete and insert rights away from application ddevelopers on production. Sometimes the best thing you can do is at least learn from your mistakes and make the system better for the next time. </p>

Title: Turning back from update on SQL Server


问:
Counting the number of records of an angularfire2.5 Observable list and drop it in a Colspan
I'm having some problems trying to drop the number of records (members) of an observable list with angularfire2.5 RTDB, in a td colspan.

I manage calculate the number with the following code

```<code>{{ (members | async)?.length }}
</code>```

But I don't know how to drop the number in a td colspan :

```<code><td colspan="{{ (members | async)?.length }}">
</code>```

Do I have to get the number from the controller and if so how can I do this.

I'm getting my list with the following code:

```<code>    this.members = db.list('members').snapshotChanges().map(arr => {
  return arr.map(snap => Object.assign(snap.payload.val(), { key: snap.key }) )
})
</code>```

答:
try this</p>

```<code><td [colSpan]="(members | async)?.length">
</code>```

Body:
I'm having some problems trying to drop the number of records (members) of an observable list with angularfire2.5 RTDB, in a td colspan.

I manage calculate the number with the following code

{{ (members | async)?.length }}

But I don't know how to drop the number in a td colspan :

Do I have to get the number from the controller and if so how can I do this.

I'm getting my list with the following code:

    this.members = db.list('members').snapshotChanges().map(arr => {
  return arr.map(snap => Object.assign(snap.payload.val(), { key: snap.key }) )
})

Body:
try this

<td [colSpan]="(members | async)?.length">


问:
NodeJS async library will not send requests asynchronsly
Question about asynchronsousity

I've wrote 2 node express servers both running on localhost.

Server1 has a simple express REST API that receives GET requests from browser, this API will trigger a GET request to Server2, while the request (sent from Server1) is wrapped within a NodeJS async library call.
Server2 will respond for each request after 10 seconds (using the good old node's setTimeout).

My thinking was that - If 2 requests sent from Server1 to Server2 (one second after the other) what would happend is:

Server1 will send the first request to Server2 and will not wait for response, making the event loop available to listen to more incoming requests.

After 1 second 2nd request comes in and Server1 will shoot out this one as well to Server2.

Server2 will count 10 seconds for each incoming request, which eventually will respond also with ~1 second delay between the responses to Server1.

Server1 will respond eventually to both request after ~11 seconds (responses to browser).

BUT NOT !!!

What I get is:

The response to browser for the 1st request is received after 10 seconds.

The response to browser for the 2nd request is received after another 10 seconds counted from the first response (making it ~20 seconds in total) as if no async mechanism is working at all.

(And by the way I tried to wrap the request that Server1 sends with async.asyncify(...), async.series(...), async.parallel(...) - 2nd request always comes back after ~20 seconds).

Why?

My severs code:

Server 1: gets both requests to localhost:9999/work1

```<code>/* ############################################
                SERVER 1
############################################ */
const express = require('express');
const app = express();
const async = require('async');
const request = require('request');

var reqId = 1;

function requestWork(cb) {
    console.log("Starting request: " + reqId);
    request.get('http://localhost:8888/work2').on('response', cb);
    console.log("After request: " + reqId);
}

app.get('/work1', (req, res) => {

    reqId++;
    async.setImmediate(requestWork, function() {
        console.log("Request done!");
        res.send('Easy request done: ' + reqId);
    });
});

var port = 9999;
app.listen(port, () => console.log('Server 1, listening on port ' + port));
</code>```

Server 2:

```<code>/* ############################################
                SERVER 2
############################################ */
const express = require('express');
const app = express();
const async = require('async');

var reqId = 100;

app.get('/work2', (req, res) => {

    console.log("Got work to do: " + reqId);
    setTimeout(() => {
        reqId++;
        res.send('Big work done: ' + reqId) ;
    }, 10000);
});

var port = 8888;
app.listen(port, () => console.log('Server 2, listening on port '+ port));
</code>```

答:
it's not express or async problem. It's browser problem.

If you try same code but run parallel requests in different browsers you will get what you expect.

For google chrome more details can be found here.

Chrome stalls when making multiple requests to same resource?

Hope this helps.

Body:
Question about asynchronsousity

I've wrote 2 node express servers both running on localhost.

Server1 has a simple express REST API that receives GET requests from browser, this API will trigger a GET request to Server2, while the request (sent from Server1) is wrapped within a NodeJS async library call.
Server2 will respond for each request after 10 seconds (using the good old node's setTimeout).

My thinking was that - If 2 requests sent from Server1 to Server2 (one second after the other) what would happend is:

Server1 will send the first request to Server2 and will not wait for response, making the event loop available to listen to more incoming requests.

After 1 second 2nd request comes in and Server1 will shoot out this one as well to Server2.

Server2 will count 10 seconds for each incoming request, which eventually will respond also with ~1 second delay between the responses to Server1.

Server1 will respond eventually to both request after ~11 seconds (responses to browser).

BUT NOT !!!

What I get is:

The response to browser for the 1st request is received after 10 seconds.

The response to browser for the 2nd request is received after another 10 seconds counted from the first response (making it ~20 seconds in total) as if no async mechanism is working at all.

(And by the way I tried to wrap the request that Server1 sends with async.asyncify(...), async.series(...), async.parallel(...) - 2nd request always comes back after ~20 seconds).

Why?

My severs code:

Server 1: gets both requests to localhost:9999/work1

/* ############################################
                SERVER 1
############################################ */
const express = require('express');
const app = express();
const async = require('async');
const request = require('request');

var reqId = 1;

function requestWork(cb) {
    console.log("Starting request: " + reqId);
    request.get('http://localhost:8888/work2').on('response', cb);
    console.log("After request: " + reqId);
}

app.get('/work1', (req, res) => {

    reqId++;
    async.setImmediate(requestWork, function() {
        console.log("Request done!");
        res.send('Easy request done: ' + reqId);
    });
});

var port = 9999;
app.listen(port, () => console.log('Server 1, listening on port ' + port));

Server 2:

/* ############################################
                SERVER 2
############################################ */
const express = require('express');
const app = express();
const async = require('async');

var reqId = 100;

app.get('/work2', (req, res) => {

    console.log("Got work to do: " + reqId);
    setTimeout(() => {
        reqId++;
        res.send('Big work done: ' + reqId) ;
    }, 10000);
});

var port = 8888;
app.listen(port, () => console.log('Server 2, listening on port '+ port));


问:
SQL Sub-query Error
I think there is issue with the A2 set where I am only including Restart_case = Y, but I am not sure please help. I am getting this error: An unexpected token "WHERE" was found following "_ID) AS Max_DateBegin".  Expected tokens may include...
Thank you</p>

```<code>SELECT A2.* FROM
(SELECT A1.*, min(BeginDate) OVER (PARTITION BY Per_ID) AS Min_BeginDate,
MAX(BeginDate) OVER (PARTITION BY Per_ID) AS Max_BeginDate
WHERE RestartCase = 'Y'
From) A2
(SELECT distinct C.Per_ID, P.DOB, C.BeginDate, C.EndDate, C.RestartCase, P.per_type
FROM CaseSum C LEFT JOIN PERSON p on C.ID_PRSN = P.ID_PRSN)  A1
WHERE per_Type = 1 AND BeginDate <= '9/30/2017' AND (EndDate >= '10/01/2017' OR EndDate IS NULL)
ORDER BY A1.Per_ID
</code>```

答:
Consider a conditional CASE inline aggregate in your window functions to combine both attempted resultsets:

```<code>SELECT DISTINCT C.Per_ID, P.DOB, C.BeginDate, C.EndDate, C.RestartCase, P.per_type,
                MIN(CASE WHEN C.RestartCase = 'Y' THEN C.BeginDate END)
                              OVER (PARTITION BY C.Per_ID) AS Min_BeginDate,
                MAX(CASE WHEN C.RestartCase = 'Y' THEN C.BeginDate END)
                              OVER (PARTITION BY C.Per_ID) AS Max_BeginDate
FROM CaseSum C
LEFT JOIN PERSON P on C.ID_PRSN = P.ID_PRSN
WHERE P.per_Type = 1 AND C.BeginDate <= '9/30/2017'
  AND (C.EndDate >= '10/01/2017' OR C.EndDate IS NULL)
ORDER BY C.Per_ID
</code>```

Title: SQL Sub-query Error

Body:
I think there is issue with the A2 set where I am only including Restart_case = Y, but I am not sure please help. I am getting this error: An unexpected token "WHERE" was found following "_ID) AS Max_DateBegin".  Expected tokens may include...
Thank you

SELECT A2.* FROM
(SELECT A1.*, min(BeginDate) OVER (PARTITION BY Per_ID) AS Min_BeginDate,
MAX(BeginDate) OVER (PARTITION BY Per_ID) AS Max_BeginDate
WHERE RestartCase = 'Y'
From) A2
(SELECT distinct C.Per_ID, P.DOB, C.BeginDate, C.EndDate, C.RestartCase, P.per_type
FROM CaseSum C LEFT JOIN PERSON p on C.ID_PRSN = P.ID_PRSN)  A1
WHERE per_Type = 1 AND BeginDate <= '9/30/2017' AND (EndDate >= '10/01/2017' OR EndDate IS NULL)
ORDER BY A1.Per_ID

Body:
Consider a conditional CASE inline aggregate in your window functions to combine both attempted resultsets:

SELECT DISTINCT C.Per_ID, P.DOB, C.BeginDate, C.EndDate, C.RestartCase, P.per_type,
                MIN(CASE WHEN C.RestartCase = 'Y' THEN C.BeginDate END)
                              OVER (PARTITION BY C.Per_ID) AS Min_BeginDate,
                MAX(CASE WHEN C.RestartCase = 'Y' THEN C.BeginDate END)
                              OVER (PARTITION BY C.Per_ID) AS Max_BeginDate
FROM CaseSum C
LEFT JOIN PERSON P on C.ID_PRSN = P.ID_PRSN
WHERE P.per_Type = 1 AND C.BeginDate <= '9/30/2017'
  AND (C.EndDate >= '10/01/2017' OR C.EndDate IS NULL)
ORDER BY C.Per_ID


问:
$store properties are not reactive when using computed property (Vuex)
I have a Vuex store, which I'm injecting into my instance:

import store from '../store';

const mainNav = new Vue({
  el: '#main-nav',
  store,
  components: { NavComponent }
});
```
<p>And I'm creating a computed property from that store in the component:</p>
<pre class="lang-js prettyprint-override"><code>computed: {
  isWide() {
    return this.$store.state.nav.type === 'wide';
  }
}
</code>```

This does create the this.isWide property for the template on component initialization, but when the store value is updated, the component doesn't register this - the old value is still on the template.

What am I doing wrong here?

答:
you should not manipulate store objects directly from component methods, you should commit mutations on store object. Mutations are functions that have listeners and when called changed variables are tracked and changes are propagated. If you need to do something async like submit data to the server you have to go even one step further define actions on the store, do async call and then commit mutations from there to update state object. I know this sounds so annoying but once you use to it it is pretty straight forward.

const store = new Vuex.Store({
  state: {
    nav: {
      type: 'not wide by default'
    }
  },
  mutations: {
    changeType: (state, type) => {
      state.nav.type = type;
    }
  }
})

Vue.component('NavComponent', {
  template: '
isWide?: {{isWide}}
',
  computed: {
    isWide () {
      return this.$store.state.nav.type === 'wide'
    }
  }
})

new Vue({
  el: '#app',
  store,
  methods: {
    changeType (type) {
      this.$store.commit('changeType', type);
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.0/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.js"></script>
<div id="app">
  <nav-component></nav-component>
  <button @click="changeType('wide')">
    Change to Wide
  </button>
  <button @click="changeType('narrow')">
    Change to Narrow
  </button>
</div></code>```

https://codepen.io/zoransa/pen/KyqvWd?editors=1010

it also works directly at stat.nav without type
https://codepen.io/zoransa/pen/xPrLyW?editors=1010

Body:
I have a Vuex store, which I'm injecting into my instance:

import store from '../store';

const mainNav = new Vue({
  el: '#main-nav',
  store,
  components: { NavComponent }
});

And I'm creating a computed property from that store in the component:

computed: {
  isWide() {
    return this.$store.state.nav.type === 'wide';
  }
}

This does create the this.isWide property for the template on component initialization, but when the store value is updated, the component doesn't register this - the old value is still on the template.

What am I doing wrong here?

Body:
you should not manipulate store objects directly from component methods, you should commit mutations on store object. Mutations are functions that have listeners and when called changed variables are tracked and changes are propagated. If you need to do something async like submit data to the server you have to go even one step further define actions on the store, do async call and then commit mutations from there to update state object. I know this sounds so annoying but once you use to it it is pretty straight forward.

const store = new Vuex.Store({
  state: {
    nav: {
      type: 'not wide by default'
    }
  },
  mutations: {
    changeType: (state, type) => {
      state.nav.type = type;
    }
  }
})

Vue.component('NavComponent', {
  template: '<div>isWide?: {{isWide}}</div>',
  computed: {
    isWide () {
      return this.$store.state.nav.type === 'wide'
    }
  }
})

new Vue({
  el: '#app',
  store,
  methods: {
    changeType (type) {
      this.$store.commit('changeType', type);
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.0/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.js"></script>
<div id="app">
  <nav-component></nav-component>
  <button @click="changeType('wide')">
    Change to Wide
  </button>
  <button @click="changeType('narrow')">
    Change to Narrow
  </button>
</div>

https://codepen.io/zoransa/pen/KyqvWd?editors=1010

it also works directly at stat.nav without type
https://codepen.io/zoransa/pen/xPrLyW?editors=1010