问:
Simple JS menu toggle
I am pretty new to JavaScript and decided to code a menu that opens/expands when you click a button and closes when you click the button again.

I got everything to work but I cannot seem to find why the menu isn't closing.

Here is my code:

Any help or guidance is much appreciated!
I have included my HTML, CSS and JS files.

let toggleNavStatus = false;

let toggleNav = function (){
    let getSideBar = document.querySelector(".nav-sidebar");
    let getSideBarUl = document.querySelector(".nav-sidebar ul");
    let getSideBarUTitle = document.querySelector(".nav-sidebar span");
    let getSideBarLinks = document.querySelectorAll(".nav-sidebar a");

    if(toggleNavStatus === false){
        getSideBarUl.style.visibility = "visible";
        getSideBar.style.width = "295px";
        getSideBarTitle.style.opacity = "0.5";

        let arrayLenght = getSideBarLinks.length;
        for(let i = 0; i < arrayLenght; i++){
            getSideBarLinks[i].style.opacity = "1";
        }
        toggleNavStatus = true;
  } else if(toggleNavStatus === true){
    getSideBarUl.style.visibility = "hidden";
    getSideBar.style.width = "50px";
    getSideBarTitle.style.opacity = "0";

    let arrayLenght = getSideBarLinks.length;
    for(let i = 0; i < arrayLenght; i++){
        getSideBarLinks[i].style.opacity = "0";
    }
    toggleNavStatus = false;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 100%;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 50px;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;
 }

 .nav-sidebar ul{
    padding-top: 15px;
    overflow: hidden;
    visibility: hidden;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">

  Home

  Portfolio

  About Us

  Gallery

  Contact

 Projects

  Making a Website

  SEAO Optimizing Video

  Walking Through The Park

  Just Another Day

```

答:
I have solved that for you but it is just a basic show hide with JavaScript.You can extend it anytime to get a proper transition.

Note: JavaScript script is at the bottom of HTML not is the JS section.

Solution:

body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 60px;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;

 }

 .nav-sidebar ul{
    padding-top: 15px;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">
</head>
<body>

    <nav class="nav-main">

        <button class="btn-toggle-nav" onclick="toggleNav()">nav</button>

        <ul>
            <li>  Home </li>
            <li>  Portfolio </li>
            <li>  About Us </li>
            <li>  Gallery </li>
            <li>  Contact </li>
        </ul>

    </nav>

    <aside class="nav-sidebar" id="nav-sidebar"
    style="display:none">
        <ul>
            <li> <span>Projects</span></li>
            <li>  Making a Website  </li>
            <li>  SEAO Optimizing Video  </li>
            <li>  Walking Through The Park  </li>
            <li>  Just Another Day </li>
        </ul>

    </aside>

</body>
<script>
function toggleNav(){
 console.log("Hello");
  var x = document.getElementById("nav-sidebar");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
</html></code>```

Title: Simple JS menu toggle

Body:
I am pretty new to JavaScript and decided to code a menu that opens/expands when you click a button and closes when you click the button again.

I got everything to work but I cannot seem to find why the menu isn't closing.

Here is my code:

Any help or guidance is much appreciated!
I have included my HTML, CSS and JS files.

let toggleNavStatus = false;

let toggleNav = function (){
    let getSideBar = document.querySelector(".nav-sidebar");
    let getSideBarUl = document.querySelector(".nav-sidebar ul");
    let getSideBarUTitle = document.querySelector(".nav-sidebar span");
    let getSideBarLinks = document.querySelectorAll(".nav-sidebar a");

    if(toggleNavStatus === false){
        getSideBarUl.style.visibility = "visible";
        getSideBar.style.width = "295px";
        getSideBarTitle.style.opacity = "0.5";

        let arrayLenght = getSideBarLinks.length;
        for(let i = 0; i < arrayLenght; i++){
            getSideBarLinks[i].style.opacity = "1";
        }
        toggleNavStatus = true;
  } else if(toggleNavStatus === true){
    getSideBarUl.style.visibility = "hidden";
    getSideBar.style.width = "50px";
    getSideBarTitle.style.opacity = "0";

    let arrayLenght = getSideBarLinks.length;
    for(let i = 0; i < arrayLenght; i++){
        getSideBarLinks[i].style.opacity = "0";
    }
    toggleNavStatus = false;
    }
}

body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 100%;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 50px;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;
 }

 .nav-sidebar ul{
    padding-top: 15px;
    overflow: hidden;
    visibility: hidden;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">

  Home

  Portfolio

  About Us

  Gallery

  Contact

 Projects

  Making a Website

  SEAO Optimizing Video

  Walking Through The Park

  Just Another Day

Body:
I have solved that for you but it is just a basic show hide with JavaScript.You can extend it anytime to get a proper transition.

Note: JavaScript script is at the bottom of HTML not is the JS section.

Solution:

body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 60px;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;

 }

 .nav-sidebar ul{
    padding-top: 15px;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">
</head>
<body>

    <nav class="nav-main">

        <button class="btn-toggle-nav" onclick="toggleNav()">nav</button>

        <ul>
            <li> <a href="#"> Home</a> </li>
            <li> <a href="#"> Portfolio</a> </li>
            <li> <a href="#"> About Us</a> </li>
            <li> <a href="#"> Gallery</a> </li>
            <li> <a href="#"> Contact</a> </li>
        </ul>

    </nav>

    <aside class="nav-sidebar" id="nav-sidebar"
    style="display:none">
        <ul>
            <li> <span>Projects</span></li>
            <li> <a href="#"> Making a Website </a> </li>
            <li> <a href="#"> SEAO Optimizing Video </a> </li>
            <li> <a href="#"> Walking Through The Park </a> </li>
            <li> <a href="#"> Just Another Day</a> </li>
        </ul>

    </aside>

</body>
<script>
function toggleNav(){
 console.log("Hello");
  var x = document.getElementById("nav-sidebar");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
</html>


来源: stackexchange

问:
Implementing saved python regression model to react expo application
I have a python regression model that predicts one's level of happiness based on user-input data, i have trained and tested it using Python.
But I'm using React Native to create my mobile application. </p>

<p>My mobile application will take in the user-input data needed and will output a prediction on their level of happiness. Anyone has an idea on how to implement this? Any advice would be appreciated! I lack the experience, but have an interest in this area, Im still learning so please help me out :) </p>

答: You need to create python API and call it from the mobile application by passing the input features. Python API will return you the forecasted value. This API will load the regression model and make a forecast on given input features. I hope It will help. </p>

ContentLicense: CC BY-SA 4.0

Body:
I have a python regression model that predicts one's level of happiness based on user-input data, i have trained and tested it using Python.
But I'm using React Native to create my mobile application.

My mobile application will take in the user-input data needed and will output a prediction on their level of happiness. Anyone has an idea on how to implement this? Any advice would be appreciated! I lack the experience, but have an interest in this area, Im still learning so please help me out :)


问:
Reading a pickle file (PANDAS Python Data Frame) in R
Is there an easy way to read pickle files (.pkl) from Pandas Dataframe into R?

One possibility is to export to CSV and have R read the CSV but that seems really cumbersome for me because my dataframes are rather large. Is there an easier way to do so?

Thanks!

答:
To add to the answer above:  you might need to point to a different conda env to get to pandas:</p>

```<code>use_condaenv("name_of_conda_env", conda = "<<result_of `which conda`>>")
pd <- import('pandas')

df <- pd$read_pickle(paste0(outdir, "df.pkl"))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To add to the answer above:  you might need to point to a different conda env to get to pandas:

use_condaenv("name_of_conda_env", conda = "<<result_of `which conda`>>")
pd <- import('pandas')

df <- pd$read_pickle(paste0(outdir, "df.pkl"))


问:
Why does the length of array shows zero when we define a set of array properties using character value instead of numeric?
I was practicing JavaScript arrays, and I came across this situation. When I am declaring array properties using numeric values and I try to get the length of the array, then it shows the length. But when I set the properties of the array using character values, I get the length of the array as zero. Why is this happening?

var array_1 = [];
var array_2 = [];

array_1[0] = "Hello World 1";
array_1[1] = "Hello World 2";
array_1[2] = "Hello World 3";
array_2['abc'] = "Hello World";
array_2['def'] = "Hello World 1";
array_2['ghi'] = "Hello World 2";
console.log(array_1.length);
console.log(array_2.length);```

答:
As you can check in here:

the length property as well as array methods are only applied to the elements with numeric indexes. Therefore, elements added using string indexes can only be regarded as properties of the array object and not true array elements.

Arrays are objects in javascript. So, you can think as adding string key elements to an array, as adding a new property to an object. This is why length will only work for array elements added with a numeric index.

Basically you can think the array object is an extension of a javascript object but with properties like push, remove or length that are exclusive to collection objects alike.

Check out the following example to understand better the usage in different scenarios:

var array = [];

array[0] = 1;
// Length = 1
console.log(array.length);

array["five"] = 5;
// Length still = 1
console.log(array.length);

array[1] = 1;
// Length now is = 2
console.log(array.length);

array[4] = 1;
// Length now is = 5, because you are adding an element to the position 4
console.log(array.length);
console.log(array);```


问:
How to get all the class name of an element in jquery?
I have some li's

```<code> li class="views-row views-row-2 views-row-even"
 li class="views-row views-row-3 views-row-odd"
 li class="views-row views-row-4 views-row-even"
 li class="views-row views-row-5 views-row-odd"
</code>```

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have

li class="views-row views-row-2 views-row-even selected". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help

答:
Several options, but this is a good one:</p>

```<code>views_row = $("li.selected").attr("class").match(/(views\-row\-[0-9]+)/)[0];
</code>```

Body:
I have some li's

 li class="views-row views-row-2 views-row-even"
 li class="views-row views-row-3 views-row-odd"
 li class="views-row views-row-4 views-row-even"
 li class="views-row views-row-5 views-row-odd"

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have

li class="views-row views-row-2 views-row-even selected". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help

Body:
Several options, but this is a good one:

views_row = $("li.selected").attr("class").match(/(views\-row\-[0-9]+)/)[0];


问:
Vector dot product in Microsoft SEAL with CKKS
I am currently trying to implement matrix multiplication methods using the Microsoft SEAL library. I have created a vector<vector<double>> as input matrix and encoded it with CKKSEncoder. However the encoder packs an entire vector into a single Plaintext so I just have a vector<Plaintext> which makes me lose the 2D structure (and then of course I'll have a vector<Ciphertext> after encryption). Having a 1D vector allows me to access only the rows entirely but not the columns.

I managed to transpose the matrices before encoding. This allowed me to multiply component-wise the rows of the first matrix and columns (rows in transposed form) of the second matrix but I am unable to sum the elements of the resulting vector together since it's packed into a single Ciphertext. I just need to figure out how to make the vector dot product work in SEAL to perform matrix multiplication. Am I missing something or is my method wrong?

答:
It has been suggested by KyoohyungHan in the issue: https://github.com/microsoft/SEAL/issues/138 that it is possible to solve the problem with rotations by rotating the output vector and summing it up repeatedly.

For example:

// my_output_vector is the Ciphertext output

vector<Ciphertext> rotations_output(my_output_vector.size());

for(int steps = 0; steps < my_output_vector.size(); steps++)
{
    evaluator.rotate_vector(my_output_vector, steps, galois_keys, rotations_output[steps]);
}

Ciphertext sum_output;
evaluator.add_many(rotations_output, sum_output);
```


问:
How find shortest path in transport connection by using Cypher query (neo4j) over GTFS data?
I am new in neo4j, I created a graph following this steps, based on a data model from GTFS. I would like to find all the shortest indirect routes in the graph (with transfers).
Data model of graph database contains 4 entities: Route, Trip, Stop, Stoptime. Here is a screenshot of db.scheme().

Based on query which wrote Bruggen, I modified it for my use:

```<code>MATCH
(from:Stop {code:'VBR'})--(st_from:Stoptime),
(to:Stop {code:'VIR'})--(st_to:Stoptime),
p1=((st_from)-[:PRECEDES*]->(st_midway_arr:Stoptime)),
(st_midway_arr)--(midway:Stop),
(midway)--(st_midway_dep:Stoptime),
p2=((st_midway_dep)-[:PRECEDES*]->(st_to))
WHERE
st_from.departure_time > '00:00'
AND st_from.departure_time < '23:00'
AND st_midway_arr.arrival_time > st_from.departure_time
AND st_midway_dep.departure_time > st_midway_arr.arrival_time
AND st_to.arrival_time > st_midway_dep.departure_time
RETURN
from,st_from,to,st_to,p1,p2,midway
order by (st_to.arrival_time_int-st_from.departure_time_int) ASC
limit 1;
</code>```

This query is not using the shortest path, and it takes in average 30s to find a path, but the output of the query is good.

So I tried to write another query, with method allshortestpaths, it really fast (0,3s). But it returns me also trips which run in a different direction (VIR -> VBR)... another problem is the timing od that connection.

Could you help me, how to access to the transfer node (Station) when I am using allshortestpath method? I want to write a condition for timing and stop_sequence to be sure that's the right direction.

```<code>match (from:Stop {code:'VBR'}),(to:Stop {code:'VIR'})
with from,to
match p = allshortestpaths((from)-[*]-(to))
where NONE (x in relationships(p) where type(x)="OPERATES")
return p
limit 10;
</code>```

答:
```<code>match (from:Stop {code:'VBR'}),(to:Stop {code:'VIR'})
with from,to
match p = allshortestpaths((from)-[*]->(to)) // here you needed you give the direction to make sure paths are from 'VBR' to 'VIR'
where NONE (x in relationships(p) where type(x)="OPERATES")
return p
limit 10;
</code>```

Next , if you want to see the nodes in the path , then you can use the nodes(p)

```<code>match (from:Stop {code:'VBR'}),(to:Stop {code:'VIR'})
with from,to
match p = allshortestpaths((from)-[*]->(to))
where NONE (x in relationships(p) where type(x)="OPERATES")
AND ALL(node in nodes WHERE node = from OR node = to OR YOUR CONDTION ON TRANSFER NODE)
limit 10
</code>```

Body:
I am new in neo4j, I created a graph following this steps, based on a data model from GTFS. I would like to find all the shortest indirect routes in the graph (with transfers).
Data model of graph database contains 4 entities: Route, Trip, Stop, Stoptime. Here is a screenshot of db.scheme().

Based on query which wrote Bruggen, I modified it for my use:

MATCH
(from:Stop {code:'VBR'})--(st_from:Stoptime),
(to:Stop {code:'VIR'})--(st_to:Stoptime),
p1=((st_from)-[:PRECEDES*]->(st_midway_arr:Stoptime)),
(st_midway_arr)--(midway:Stop),
(midway)--(st_midway_dep:Stoptime),
p2=((st_midway_dep)-[:PRECEDES*]->(st_to))
WHERE
st_from.departure_time > '00:00'
AND st_from.departure_time < '23:00'
AND st_midway_arr.arrival_time > st_from.departure_time
AND st_midway_dep.departure_time > st_midway_arr.arrival_time
AND st_to.arrival_time > st_midway_dep.departure_time
RETURN
from,st_from,to,st_to,p1,p2,midway
order by (st_to.arrival_time_int-st_from.departure_time_int) ASC
limit 1;

This query is not using the shortest path, and it takes in average 30s to find a path, but the output of the query is good.

So I tried to write another query, with method allshortestpaths, it really fast (0,3s). But it returns me also trips which run in a different direction (VIR -> VBR)... another problem is the timing od that connection.

Could you help me, how to access to the transfer node (Station) when I am using allshortestpath method? I want to write a condition for timing and stop_sequence to be sure that's the right direction.

match (from:Stop {code:'VBR'}),(to:Stop {code:'VIR'})
with from,to
match p = allshortestpaths((from)-[*]-(to))
where NONE (x in relationships(p) where type(x)="OPERATES")
return p
limit 10;

Body:
match (from:Stop {code:'VBR'}),(to:Stop {code:'VIR'})
with from,to
match p = allshortestpaths((from)-[*]->(to)) // here you needed you give the direction to make sure paths are from 'VBR' to 'VIR'
where NONE (x in relationships(p) where type(x)="OPERATES")
return p
limit 10;

Next , if you want to see the nodes in the path , then you can use the nodes(p)

match (from:Stop {code:'VBR'}),(to:Stop {code:'VIR'})
with from,to
match p = allshortestpaths((from)-[*]->(to))
where NONE (x in relationships(p) where type(x)="OPERATES")
AND ALL(node in nodes WHERE node = from OR node = to OR YOUR CONDTION ON TRANSFER NODE)
limit 10


问:
How to concatenate list to int in Python?
When using a list, I saw that I cannot add or subtract the sample I took from the list. For example:

```<code>import random

x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
print(x + 1)
</code>```

Why I can’t add into the list I created and how can I get around that issue?

答:
If you want to increase the value of every item in a list, you can do like:

```<code>import random
x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=3 )
print(x)
for index in range(len(x)):
      x[index] = x[index] +1
print(x)
</code>```

In your case, if k is always 1, you can simply like:

```<code>import random
x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
print(x)
x[0] = x[0] + 1
print(x)
</code>```

Body:
When using a list, I saw that I cannot add or subtract the sample I took from the list. For example:

import random

x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
print(x + 1)

Why I can’t add into the list I created and how can I get around that issue?

Body:
If you want to increase the value of every item in a list, you can do like:

import random
x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=3 )
print(x)
for index in range(len(x)):
      x[index] = x[index] +1
print(x)

In your case, if k is always 1, you can simply like:

import random
x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
print(x)
x[0] = x[0] + 1
print(x)


问:
unable to detect Internet in android
I have a fragment that has a WebView, everything works fine but I need to add a feature where if there is no Internet the fragment should display an error message with a try again button, for some reason my try again button is not working.

here's my code:

```<code>NewsFragment.java
public final class NewsFragment extends Fragment {

    private WebView mWebView;
    private ImageView img;
    private Button btnTryAgain;
    private LinearLayout mLinearLayout;
    private ConnectivityManager conMgr;
    private NetworkInfo networkInfo;
    .
    .
    .

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news,container,false);
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

        //Initialization of the above declared variables
        mWebView = getView().findViewById(R.id.webView);
        img = getView().findViewById(R.id.img404);
        btnTryAgain = getView().findViewById(R.id.btnTryAgain);
        mLinearLayout = getView().findViewById(R.id.linearLayout404);

        //Checking if user is connected to the internet or not.
        conMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo = conMgr.getActiveNetworkInfo();

        //this is will work everytime the fragment is called or in onResume()
        //if INTERNET connected
        if (isConnected()) {
            mWebView.setWebViewClient(new WebViewClient());
            mWebView.loadUrl("https://news.google.com/");
        } else { //if INTERNET not connected
            mLinearLayout.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
        }

        //TryAgain Button Event handling
        btnTryAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isConnected()) {
                    mLinearLayout.setVisibility(View.GONE);
                    mWebView.setVisibility(View.VISIBLE);
                    mWebView.setWebViewClient(new WebViewClient());
                    mWebView.loadUrl("https://news.google.com/");
                    Toast.makeText(getContext(), "Connected!", Toast.LENGTH_SHORT).show();
                } else { //if INTERNET not connected
                    Toast.makeText(getContext(), "No Internet :(", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    }
    public boolean isConnected(){
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
}
</code>```

Please help me I'm new to android

答:
Use this permission:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

And use this Method:

```<code>ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
        connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
    return true;
} else {
    return false;
}
</code>```

Title: unable to detect Internet in android

Body:
I have a fragment that has a WebView, everything works fine but I need to add a feature where if there is no Internet the fragment should display an error message with a try again button, for some reason my try again button is not working.

here's my code:

NewsFragment.java
public final class NewsFragment extends Fragment {

    private WebView mWebView;
    private ImageView img;
    private Button btnTryAgain;
    private LinearLayout mLinearLayout;
    private ConnectivityManager conMgr;
    private NetworkInfo networkInfo;
    .
    .
    .

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news,container,false);
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

        //Initialization of the above declared variables
        mWebView = getView().findViewById(R.id.webView);
        img = getView().findViewById(R.id.img404);
        btnTryAgain = getView().findViewById(R.id.btnTryAgain);
        mLinearLayout = getView().findViewById(R.id.linearLayout404);

        //Checking if user is connected to the internet or not.
        conMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo = conMgr.getActiveNetworkInfo();

        //this is will work everytime the fragment is called or in onResume()
        //if INTERNET connected
        if (isConnected()) {
            mWebView.setWebViewClient(new WebViewClient());
            mWebView.loadUrl("https://news.google.com/");
        } else { //if INTERNET not connected
            mLinearLayout.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
        }

        //TryAgain Button Event handling
        btnTryAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isConnected()) {
                    mLinearLayout.setVisibility(View.GONE);
                    mWebView.setVisibility(View.VISIBLE);
                    mWebView.setWebViewClient(new WebViewClient());
                    mWebView.loadUrl("https://news.google.com/");
                    Toast.makeText(getContext(), "Connected!", Toast.LENGTH_SHORT).show();
                } else { //if INTERNET not connected
                    Toast.makeText(getContext(), "No Internet :(", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    }
    public boolean isConnected(){
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
}

Please help me I'm new to android

Body:
Use this permission:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And use this Method:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
        connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
    return true;
} else {
    return false;
}


问:
Thread freezing the application
I'm designing an application which reads DICOM data sets and visualizes them with volume rendering techniques by using VTK library. Anyway, the problem I'm dealing is volume rendering is really CPU-bounded process. If I handle the volume rendering in a single threaded process, application (GUI) freezes and passes to "not responding" state. I have written another thread for volume rendering process. However GUI still freezes, here are the codes.

```<code>private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e) {

             volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &Form1::volumeRender));
             volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
             volumeRenderThread->Start();
         }

private: void volumeRender()
         {
             threeDPictureBox->Invoke(gcnew volumeDelegate(this, &Form1::volumeDelegateMethod));

             /*
             if ( threeDPictureBox->InvokeRequired )
             {
                threeDPictureBox->Invoke(gcnew System::Action(this, &Form1::volumeRender));
             }
             else
             {
                 dicom->VolumeRender(threeDPictureBox, vrSettings);
             }
             */
         }
private: delegate void volumeDelegate();

private: void volumeDelegateMethod()
         {
             dicom->VolumeRender(threeDPictureBox, vrSettings);
         }

void Dicom::VolumeRender( Windows::Forms::PictureBox ^pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId((HWND)((pictureBox->Handle).ToPointer()));
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor

}
</code>```

threeDPictureBox is a PictureBox component that I'm sending it to volumeRender method of dicom object. vrSettings is a struct for volume Rendering parameters.

When the volume Render button is clicked and click event handler fired, volumeRenderThread starts and freezes the application even I have set its priority Lowest! I have also tried the lines which is commented. None of them works. What's the point I'm missing?? Thanks for answers from now!!

答:
Can you try the following and let me know if it works. My C++ is quite rusty, but the idea is the following. I'm guessing that VTK only needs HWND to do the its job, so you need to retrieve HWND in your UI thread and then pass this to VTK.

Change you code like this (make sure to change my C#isms if any to proper C++):

```<code>private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e)
{
    volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ParameterizedThreadStart(this, &Form1::volumeRender));
    volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
    volumeRenderThread->Start(pictureBox->Handle);
}

private: void volumeRender(System::Object^  pictureBox)
{
    dicom->VolumeRender((HWND)((System::IntPtr)pictureBox).ToPointer()), vrSettings);
}

void Dicom::VolumeRender( HWND pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId(pictureBox);
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor
}
</code>```

Title: Thread freezing the application

Body:
I'm designing an application which reads DICOM data sets and visualizes them with volume rendering techniques by using VTK library. Anyway, the problem I'm dealing is volume rendering is really CPU-bounded process. If I handle the volume rendering in a single threaded process, application (GUI) freezes and passes to "not responding" state. I have written another thread for volume rendering process. However GUI still freezes, here are the codes.

private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e) {

             volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &Form1::volumeRender));
             volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
             volumeRenderThread->Start();
         }

private: void volumeRender()
         {
             threeDPictureBox->Invoke(gcnew volumeDelegate(this, &Form1::volumeDelegateMethod));

             /*
             if ( threeDPictureBox->InvokeRequired )
             {
                threeDPictureBox->Invoke(gcnew System::Action(this, &Form1::volumeRender));
             }
             else
             {
                 dicom->VolumeRender(threeDPictureBox, vrSettings);
             }
             */
         }
private: delegate void volumeDelegate();

private: void volumeDelegateMethod()
         {
             dicom->VolumeRender(threeDPictureBox, vrSettings);
         }

void Dicom::VolumeRender( Windows::Forms::PictureBox ^pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId((HWND)((pictureBox->Handle).ToPointer()));
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor

}

threeDPictureBox is a PictureBox component that I'm sending it to volumeRender method of dicom object. vrSettings is a struct for volume Rendering parameters.

When the volume Render button is clicked and click event handler fired, volumeRenderThread starts and freezes the application even I have set its priority Lowest! I have also tried the lines which is commented. None of them works. What's the point I'm missing?? Thanks for answers from now!!

Body:
Can you try the following and let me know if it works. My C++ is quite rusty, but the idea is the following. I'm guessing that VTK only needs HWND to do the its job, so you need to retrieve HWND in your UI thread and then pass this to VTK.

Change you code like this (make sure to change my C#isms if any to proper C++):

private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e)
{
    volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ParameterizedThreadStart(this, &Form1::volumeRender));
    volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
    volumeRenderThread->Start(pictureBox->Handle);
}

private: void volumeRender(System::Object^  pictureBox)
{
    dicom->VolumeRender((HWND)((System::IntPtr)pictureBox).ToPointer()), vrSettings);
}

void Dicom::VolumeRender( HWND pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId(pictureBox);
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor
}


问:
Using pyopengltk and add another common tkinter function
I currently try to create opengl simulation in tkinter, so i found this. The example code provided there :

```<code>import time
import tkinter
from OpenGL import GL
from pyopengltk import OpenGLFrame

class AppOgl(OpenGLFrame):

    def initgl(self):
        """Initalize gl states when the frame is created"""
        GL.glViewport(0, 0, self.width, self.height)
        GL.glClearColor(0.0, 1.0, 0.0, 0.0)
        self.start = time.time()
        self.nframes = 0

    def redraw(self):
        """Render a single frame"""
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        tm = time.time() - self.start
        self.nframes += 1
        print("fps",self.nframes / tm, end="\r" )

if __name__ == '__main__':
    root = tkinter.Tk()
    app = AppOgl(root, width=320, height=200)
    app.pack(fill=tkinter.BOTH, expand=tkinter.YES)
    app.animate = 1
    app.after(100, app.printContext)
    app.mainloop()
</code>```

I can run it fine but i sligthly confused because i usually use tkinter with this format :

```<code>class frontpage(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent=parent

        '''Creating'''
        #Window 1
        label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
        frame1 = tk.Frame(self)

        ''' Some code '''

        label1.pack(fill='x')
        frame1.pack()

    def func1(self):
        #some function

if __name__ == '__main__':
    frontapp = frontpage(None)
    frontapp.title('App v0.1')
    frontapp.mainloop()
</code>```

Given that, is there anyway i could insert normal tkinter item such as frame, button, etc using pyopengltk?

答:
Based on solution suggested by @stovfl, we just need to insert our opengl class into our tkinter class __init__. Then it become :

```<code>from __future__ import print_function

import sys, math, time
import tkinter as tk
from OpenGL import GL, GLU
from pyopengltk import OpenGLFrame

class AppOgl(OpenGLFrame):

    def initgl(self):
        """Initalize gl states when the frame is created"""
        GL.glViewport(0, 0, self.width, self.height)
        GL.glClearColor(0.0, 1.0, 0.0, 0.0)
        self.start = time.time()
        self.nframes = 0

    def redraw(self):
        """Render a single frame"""
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        tm = time.time() - self.start
        self.nframes += 1
        print("fps",self.nframes / tm, end="\r" )

class frontpage(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent=parent

        open_gl_frame = AppOgl(self, width=320, height=200)
        '''Creating'''
        #Window 1
        label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
        frame1 = tk.Frame(self)

        ''' Some code '''

        open_gl_frame.animate=1 #dont forget this, or your simulation would not animated
        open_gl_frame.pack()
        label1.pack(fill='x')
        frame1.pack()

    def func1(self):
        pass

if __name__ == '__main__':
        frontapp = frontpage(None)
        frontapp.title('App v0.1')
        frontapp.mainloop()
</code>```

Body:
I currently try to create opengl simulation in tkinter, so i found this. The example code provided there :

import time
import tkinter
from OpenGL import GL
from pyopengltk import OpenGLFrame

class AppOgl(OpenGLFrame):

    def initgl(self):
        """Initalize gl states when the frame is created"""
        GL.glViewport(0, 0, self.width, self.height)
        GL.glClearColor(0.0, 1.0, 0.0, 0.0)
        self.start = time.time()
        self.nframes = 0

    def redraw(self):
        """Render a single frame"""
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        tm = time.time() - self.start
        self.nframes += 1
        print("fps",self.nframes / tm, end="\r" )

if __name__ == '__main__':
    root = tkinter.Tk()
    app = AppOgl(root, width=320, height=200)
    app.pack(fill=tkinter.BOTH, expand=tkinter.YES)
    app.animate = 1
    app.after(100, app.printContext)
    app.mainloop()

I can run it fine but i sligthly confused because i usually use tkinter with this format :

class frontpage(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent=parent

        '''Creating'''
        #Window 1
        label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
        frame1 = tk.Frame(self)

        ''' Some code '''

        label1.pack(fill='x')
        frame1.pack()

    def func1(self):
        #some function

if __name__ == '__main__':
    frontapp = frontpage(None)
    frontapp.title('App v0.1')
    frontapp.mainloop()

Given that, is there anyway i could insert normal tkinter item such as frame, button, etc using pyopengltk?

Body:
Based on solution suggested by @stovfl, we just need to insert our opengl class into our tkinter class __init__. Then it become :

from __future__ import print_function

import sys, math, time
import tkinter as tk
from OpenGL import GL, GLU
from pyopengltk import OpenGLFrame

class AppOgl(OpenGLFrame):

    def initgl(self):
        """Initalize gl states when the frame is created"""
        GL.glViewport(0, 0, self.width, self.height)
        GL.glClearColor(0.0, 1.0, 0.0, 0.0)
        self.start = time.time()
        self.nframes = 0

    def redraw(self):
        """Render a single frame"""
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        tm = time.time() - self.start
        self.nframes += 1
        print("fps",self.nframes / tm, end="\r" )

class frontpage(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent=parent

        open_gl_frame = AppOgl(self, width=320, height=200)
        '''Creating'''
        #Window 1
        label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
        frame1 = tk.Frame(self)

        ''' Some code '''

        open_gl_frame.animate=1 #dont forget this, or your simulation would not animated
        open_gl_frame.pack()
        label1.pack(fill='x')
        frame1.pack()

    def func1(self):
        pass

if __name__ == '__main__':
        frontapp = frontpage(None)
        frontapp.title('App v0.1')
        frontapp.mainloop()


问:
Using Autotools to compile and install a python module to the python library path
I started using Autotool in my project and I have a python module that I would like to compile into a pyc and to copy to the default path for python libraries, so that after installation it can be imported without the need to define extra environment variables.
I could find many examples of Makefile.am configurations for python libraries, but they are all using SWIG, which is not my case.
Up to now, my Makefile.am file in the pythonlib subfolder has only one line

```<code>python_PYTHON = mymodule.py
</code>```

In configure.ac I have:

```<code>AM_PATH_PYTHON([2.4])
</code>```

and in the topdir Makefile.am :

```<code>ACLOCAL_AMFLAGS = -I m4
SUBDIRS=src pythonlib
CCLD = $(CC)
LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
</code>```

but when after configuration I run the make command I get:

```<code>Making all in pythonlib
make[2]: Entering directory '/home/golosio/myproject/pythonlib'
make[2]: *** No rule to make target 'all'.  Stop.
make[2]: Leaving directory '/home/golosio/myproject/pythonlib'
make[1]: *** [Makefile:426: all-recursive] Error 1
make[1]: Leaving directory '/home/golosio/myproject'
make: *** [Makefile:358: all] Error 2
</code>```

I also tried to define pyexec_LTLIBRARIES, but without success. What should I write in the Makefile.am file to compile and install the module?

答:
Sorry, it was a trivial mistake on my part, the problem was not in the Makefile.am files, but in the configure.ac file, I just had to add the path "pythonlib" to AC_CONFIG_FILES:

```<code>AC_CONFIG_FILES([Makefile
src/Makefile
pythonlib/Makefile])
</code>```

with this everything works fine.

Body:
I started using Autotool in my project and I have a python module that I would like to compile into a pyc and to copy to the default path for python libraries, so that after installation it can be imported without the need to define extra environment variables.
I could find many examples of Makefile.am configurations for python libraries, but they are all using SWIG, which is not my case.
Up to now, my Makefile.am file in the pythonlib subfolder has only one line

python_PYTHON = mymodule.py

In configure.ac I have:

AM_PATH_PYTHON([2.4])

and in the topdir Makefile.am :

ACLOCAL_AMFLAGS = -I m4
SUBDIRS=src pythonlib
CCLD = $(CC)
LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@

but when after configuration I run the make command I get:

Making all in pythonlib
make[2]: Entering directory '/home/golosio/myproject/pythonlib'
make[2]: *** No rule to make target 'all'.  Stop.
make[2]: Leaving directory '/home/golosio/myproject/pythonlib'
make[1]: *** [Makefile:426: all-recursive] Error 1
make[1]: Leaving directory '/home/golosio/myproject'
make: *** [Makefile:358: all] Error 2

I also tried to define pyexec_LTLIBRARIES, but without success. What should I write in the Makefile.am file to compile and install the module?

Body:
Sorry, it was a trivial mistake on my part, the problem was not in the Makefile.am files, but in the configure.ac file, I just had to add the path "pythonlib" to AC_CONFIG_FILES:

AC_CONFIG_FILES([Makefile
src/Makefile
pythonlib/Makefile])

with this everything works fine.


问:
Numpy Infinity constants - Difference among inf, infty, Inf, Infty. Which one to use when?
Numpy has several constants providing similar functionality of mathematical inifinity value.
These are - np.inf, np.infty, np.Inf, np.Infty.

The docs (https://numpy.org/devdocs/reference/constants.html) says that these are all aliases of np.inf.

It seems very unpythonic (multiple redundant ways to achieve exact same thing)!
Is there really no difference among them?

答:
the documentation says

Use inf because Inf, Infinity, PINF and infty are aliases for inf. For
  more details, see inf.

You can the check the docs right here.


问:
Can't figure out why my ActivityTransition example doesn't work with BroadcastReceiver
I have looked at multiple examples and implementations, I have no more ideas to check. I hope for outside perspective to see if I have missed something. Here is complete project on github for full source

It doesn't give me any errors or anything, it even shows that I have registered my request successfully. But I don't get any result in my BroadcastReceiver.

Manifest:

```<code><uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:exported="true"
        android:enabled="true"
        android:name="com.example.myapplication.ActivityTransitionBroadcastReceiver"
        android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
        <intent-filter>
            <action android:name="com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"/>
        </intent-filter>
    </receiver>

</application>
</code>```

Main Activity:

```<code>    List<ActivityTransition> transitions = new ArrayList<>();

    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());

    ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

    Intent intent = new Intent(this.getApplicationContext(), ActivityTransitionBroadcastReceiver.class);
    intent.setAction(ActivityTransitionBroadcastReceiver.INTENT_ACTION);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    Task<Void> task = ActivityRecognition.getClient(this.getApplicationContext())
            .requestActivityTransitionUpdates(request, pendingIntent);
    task.addOnSuccessListener(aVoid -> Log.i(TAG, "\n\nTransitions API was successfully registered.\n\n"))
            .addOnFailureListener(e -> Log.e(TAG, "Transitions API could not be registered: " + e));
</code>```

答:
Have you tried to register BroadcastReceiver in the Activity's onCreate or `onStart' method

```<code>class CustomBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //do some stuff here
        Log.d("Broadcast", "Success");
    }
}

CustomBroadcast broadcast = new CustomBroadcast();

LocalBroadcastManager.getInstance(this).registerReceiver(broadcast,
                    new IntentFilter("com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"));
</code>```

Then in onStop unsubscribe:

```<code>LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcast);

</code>```

I do it like that since after 26 it is quite problematic to use manifest declared ones.

Hope it helps.

Body:
I have looked at multiple examples and implementations, I have no more ideas to check. I hope for outside perspective to see if I have missed something. Here is complete project on github for full source

It doesn't give me any errors or anything, it even shows that I have registered my request successfully. But I don't get any result in my BroadcastReceiver.

Manifest:

<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:exported="true"
        android:enabled="true"
        android:name="com.example.myapplication.ActivityTransitionBroadcastReceiver"
        android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
        <intent-filter>
            <action android:name="com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"/>
        </intent-filter>
    </receiver>

</application>

Main Activity:

    List<ActivityTransition> transitions = new ArrayList<>();

    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());

    ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

    Intent intent = new Intent(this.getApplicationContext(), ActivityTransitionBroadcastReceiver.class);
    intent.setAction(ActivityTransitionBroadcastReceiver.INTENT_ACTION);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    Task<Void> task = ActivityRecognition.getClient(this.getApplicationContext())
            .requestActivityTransitionUpdates(request, pendingIntent);
    task.addOnSuccessListener(aVoid -> Log.i(TAG, "\n\nTransitions API was successfully registered.\n\n"))
            .addOnFailureListener(e -> Log.e(TAG, "Transitions API could not be registered: " + e));

Body:
Have you tried to register BroadcastReceiver in the Activity's onCreate or `onStart' method

class CustomBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //do some stuff here
        Log.d("Broadcast", "Success");
    }
}

CustomBroadcast broadcast = new CustomBroadcast();

LocalBroadcastManager.getInstance(this).registerReceiver(broadcast,
                    new IntentFilter("com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"));

Then in onStop unsubscribe:

LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcast);

I do it like that since after 26 it is quite problematic to use manifest declared ones.

Hope it helps.


问:
Restore deleted docker container that is still running
I accidentally deleted a docker container. (Via rm -R ) However, it's still running and sending data. Is it possible to restore it?</p>

答:
I'm curios where you executed rm -R, i assume it was in your dev folders? i find it hard to imagine you actually accidently deleted the folders containing the volume/journal for the container itself.

If you run docker container ps what do you see? if your container is there and still running then run docker container inspect containerNameOrSha this will give you the directories which contain the data and the image which the container was created from.

If the containers directory really is gone?? how? i.e the actual file system then I cant see how the container is running! But lets find out. run docker container exec -it containerNameOrSha sh this will give you an interactive shell into the container. What can you see, are your files still here? are the processes you expect to see running?

If you want to get to the data inside the running container you can use docker cp which can copy data from your container to your host.

Its unclear 'why' you need to get this container back, maybe if you update your question someone might be able to get a better answer than this rather generic one.


问:
What's up with this JavaScript pattern?
I saw this pattern:

```<code>Money = (function() {
    function Money(rawString) {
        this.cents = this.parseCents(rawString);
    }
});
</code>```

in this CoffeeScript screencast preview. (The homepage for the screencast is here.)

Now, I don't understand this pattern. There is a Money function that contains a Money function. What's that about?

Could someone explain?

答:
I'm the author of the screencast mentioned, and the source of the snippet. A few clarifications:

The context in which the snippet was mentioned was in an animated comparison of JavaScript and CoffeeScript syntax.

It was intentionally simplified so as to not add extra confusion in the context of the CoffeeScript concept being taught at that exact moment in the video (the video was not trying to teach JavaScript constructor or class syntax).

You can get the full JavaScript text of any CoffeeScript snippet by running it through the CoffeeScript compiler as shown in the screencast, or by running it on the official CoffeeScript website.

I'll add a clarification to the video and preview mentioned above.

Otherwise, the other explanations here on Stack Overflow are correct. If you're building a JavaScript class you should return the current object and call the anonymous function shown above. But that's not the point of CoffeeScript. ;-)

Title: What's up with this JavaScript pattern?

Body:
I saw this pattern:

Money = (function() {
    function Money(rawString) {
        this.cents = this.parseCents(rawString);
    }
});

in this CoffeeScript screencast preview. (The homepage for the screencast is here.)

Now, I don't understand this pattern. There is a Money function that contains a Money function. What's that about?

Could someone explain?


问:
How to check if NA within replace() function in R?
In my dataset, the duration of a activity is either given in hours (column duration_hours) or in minutes (column duration_minutes). If it is given in hours, the duration_minutes column is empty (NA) and vice versa.

I now want to convert the values given in minutes into hours by dividing them by 60 (minutes).

To do so I tried this command:

df <- df %>% mutate(duration_recoded = replace(duration_minutes, !is.na(duration_minutes), duration_minutes / 60))

However, the command produces incorrect results and this warning message is shown:

```<code>Warning message:
In x[list] <- values :
  number of items to replace is not a multiple of replacement length
</code>```

Can anybody tell me where my mistake is?

Here's some sample data:

```<code>df <- structure(list(duration_hours = c(1, NA, 2, NA, 1), duration_minutes = c(NA, 25, NA, 30, NA)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
We can make use of the coalesce() function from the dplyr package here:

```<code>library(dplyr)
df <- df %>% mutate(duration_recoded = coalesce(duration_hours, duration_minutes / 60))
</code>```

This should work because if the duration_hours be non NA, then coalesce would simply grab it and assign it to duration_recorded.  If duration_hours is actually NA, then it would pass and instead take duration_minutes divided by 60.

Body:
In my dataset, the duration of a activity is either given in hours (column duration_hours) or in minutes (column duration_minutes). If it is given in hours, the duration_minutes column is empty (NA) and vice versa.

I now want to convert the values given in minutes into hours by dividing them by 60 (minutes).

To do so I tried this command:

df <- df %>% mutate(duration_recoded = replace(duration_minutes, !is.na(duration_minutes), duration_minutes / 60))

However, the command produces incorrect results and this warning message is shown:

Warning message:
In x[list] <- values :
  number of items to replace is not a multiple of replacement length

Can anybody tell me where my mistake is?

Here's some sample data:

df <- structure(list(duration_hours = c(1, NA, 2, NA, 1), duration_minutes = c(NA, 25, NA, 30, NA)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

Body:
We can make use of the coalesce() function from the dplyr package here:

library(dplyr)
df <- df %>% mutate(duration_recoded = coalesce(duration_hours, duration_minutes / 60))

This should work because if the duration_hours be non NA, then coalesce would simply grab it and assign it to duration_recorded.  If duration_hours is actually NA, then it would pass and instead take duration_minutes divided by 60.


问:
map int over 2D array python
To parse

```<code>s="1,2,3,4_5,6,7,8"
</code>```

as [[1,2,3,4],[5,6,7,8]]

I am currently using

```<code>import numpy as np
a=np.array([list(map(int,r.split(","))) for r in s.split("_")])
</code>```

Is there a more pythonic or one-shot inbuilt way of doing this or am I on the right track here?

Python newbie.

答:
Using list-comprehensions:</p>

```<code>s="1,2,3,4_5,6,7,8"

a = np.array([[int(x) for x in r.split(',')] for r in s.split('_')])
</code>```

Title: map int over 2D array python

Body:
To parse

s="1,2,3,4_5,6,7,8"

as [[1,2,3,4],[5,6,7,8]]

I am currently using

import numpy as np
a=np.array([list(map(int,r.split(","))) for r in s.split("_")])

Is there a more pythonic or one-shot inbuilt way of doing this or am I on the right track here?

Python newbie.

Body:
Using list-comprehensions:

s="1,2,3,4_5,6,7,8"

a = np.array([[int(x) for x in r.split(',')] for r in s.split('_')])


问:
HTML using a function to write the <options> of a select inside a form
So I have a very complex form that contains selects with the same options that repeat probably around 300 times. The following is a very slimmed down example of that.

```<code><select name="HelmAtt1">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select><input type="number" name="Ha1val" value="0"><br>
</code>```

Doing it this way is obviously very code intensive and not easily editable.
Is it possible to create a function that will display the options inside of a select for me, so I can end up with something like these two?

```<code><select name="HelmAtt1">
printHTML();
</select><input type="number" name="Ha1val" value="0"><br>

<script>
function printHTML()
{
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
}
</script>
</code>```

```<code>printHTML(HelmAtt1);
<input type="number" name="Ha1val" value="0"><br>

<script>
function printHTML(val)
{
<select name="val">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select>
}
</script>
</code>```

I'm not sure if its possible and any research I've found doesn't specify this exact problem or doesn't solve the issue so here I am.

答:
IMHO you should do that on the backend layer when you render your template, but here goes a frontend solution:

function addOptions(classname) {
  let elements = document.getElementsByClassName(classname);
  for (let i=0; i<elements.length; i++){
    let option = document.createElement('option');
    option.innerText = 'your option';
    option.value = 'your value';
    elements[i].appendChild(option);
  }
}

addOptions('foo');```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Foo <select class="foo"></select>
Bar <select class="foo"></select>
Baz <select class="foo"></select></code>```

Body:
So I have a very complex form that contains selects with the same options that repeat probably around 300 times. The following is a very slimmed down example of that.

<select name="HelmAtt1">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select><input type="number" name="Ha1val" value="0">

Doing it this way is obviously very code intensive and not easily editable.
Is it possible to create a function that will display the options inside of a select for me, so I can end up with something like these two?

<select name="HelmAtt1">
printHTML();
</select><input type="number" name="Ha1val" value="0">

printHTML(HelmAtt1);
<input type="number" name="Ha1val" value="0">

I'm not sure if its possible and any research I've found doesn't specify this exact problem or doesn't solve the issue so here I am.

Body:
IMHO you should do that on the backend layer when you render your template, but here goes a frontend solution:

function addOptions(classname) {
  let elements = document.getElementsByClassName(classname);
  for (let i=0; i<elements.length; i++){
    let option = document.createElement('option');
    option.innerText = 'your option';
    option.value = 'your value';
    elements[i].appendChild(option);
  }
}

addOptions('foo');

Foo <select class="foo"></select>
Bar <select class="foo"></select>
Baz <select class="foo"></select>


问:
Having unique random numbers in more than one variables
Is it possible to have more than one variables and each have a unique and distinct random number from one another. The sample range is the same, yet I do not want the variables to have same numbers.

```<code>import random

A=random.sample(range(1,4),1)
B=random.sample(range(1,4),1)
C=random.sample(range(1,4),1)
</code>```

So the above example, I want A, B and C to have different random numbers. In other words, no two variables must have the same number.

How to go about this?

答:
This should work:

```<code>A, B, C = random.sample(range(1, 4), k=3)
</code>```

As far as I know, does random.choice not prevent from having all three Variables containing the same value, while sample does assign each value given in the range only once each call

Body:
Is it possible to have more than one variables and each have a unique and distinct random number from one another. The sample range is the same, yet I do not want the variables to have same numbers.

import random

A=random.sample(range(1,4),1)
B=random.sample(range(1,4),1)
C=random.sample(range(1,4),1)

So the above example, I want A, B and C to have different random numbers. In other words, no two variables must have the same number.

How to go about this?

Body:
This should work:

A, B, C = random.sample(range(1, 4), k=3)

As far as I know, does random.choice not prevent from having all three Variables containing the same value, while sample does assign each value given in the range only once each call


问:
Asp calendar control
I am working on an asp page. I need to have a calendar control in it.My requirement is to poplulate a textbox with selected Calendar date where the textbox is dynamically generated. So please can anyone help me out. How can I do that? </p>

答: Here is a classic ASP calendar sample code for you LINK</p>

Title: Asp calendar control


问:
Show placeholder text in ReactJS input until click then show "typing"
Once I click the text box some of my div will show a "typing." Before clicking, it should show "this is just a sample."

<input type="text" onClick={this.state}>
```

答:
if I understood correctly you want to display the word 'Typing' once you click on the div.
I think this will help you </p>

```<code>import React from "react";

export default class Typing extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            yourStateName: ""
        }
        this.onChangeState = this.onChangeState.bind(this);
    }

    onChangeState(e) {
        this.setState({
            yourStateName: "Typing"
        })
    }

    render() {
        const {yourStateName} = this.state;
        return (
            <div>
                <input type="text" onClick={e => this.onChangeState(e)}>
                value: {yourStateName}
            <div/>
        )
    }
}
</code>```

Body:
if I understood correctly you want to display the word 'Typing' once you click on the div.
I think this will help you

import React from "react";

export default class Typing extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            yourStateName: ""
        }
        this.onChangeState = this.onChangeState.bind(this);
    }

    onChangeState(e) {
        this.setState({
            yourStateName: "Typing"
        })
    }

    render() {
        const {yourStateName} = this.state;
        return (
            <div>
                <input type="text" onClick={e => this.onChangeState(e)}>
                value: {yourStateName}
            <div/>
        )
    }
}


答:
You can use np.genfromtxt:

```<code>from io import StringIO
import numpy as np

s="1,2,3,4_5,6,7,8"

np.genfromtxt(StringIO(s.replace("_", "\n")), delimiter=",")

array([[1., 2., 3., 4.],
       [5., 6., 7., 8.]])
</code>```

Title: map int over 2D array python

Body:
You can use np.genfromtxt:

from io import StringIO
import numpy as np

s="1,2,3,4_5,6,7,8"

np.genfromtxt(StringIO(s.replace("_", "\n")), delimiter=",")

array([[1., 2., 3., 4.],
       [5., 6., 7., 8.]])


问:
Use a form inside a form or How to work with foreign keys in forms
I am going to use the documentation model as an example:

```<code>class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...

class Manufacturer(models.Model):
    # ...
</code>```

Let's say I want to create a form to add a new Manufacturer, and in this form I want to be able to add new cars. How would it be done with django-forms?

Is it even possible?

Thank you in advance for your help!

答:
The short answer:

You want modelformset_factory, documented here: http://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#model-formsets

The still-rather-short answer, but with a couple of gotchas to watch for:

On the processing side, if you're creating both the Manufacturer and the multiple Car instances, you'll want to be sure to save the manufacturer first, before saving the individual cars (which must reference the manufacturer). Make sure this happens in a database transaction if you can help it.

One more note: if this is a bit confusing to you, beat in mind that there's no hard and fast rule saying that you can only process one form in a request. You just have multiple forms.Form (or subclasses thereof) objects within the HTML <form> tag, which posts to a single request location that processes each form individually and saves them out. Again, use a database transaction so that if something fails at the end, the entire thing gets rolled back and the user can correct their error without having bad or orphan data in the database.

Body:
I am going to use the documentation model as an example:

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...

class Manufacturer(models.Model):
    # ...

Let's say I want to create a form to add a new Manufacturer, and in this form I want to be able to add new cars. How would it be done with django-forms?

Is it even possible?

Thank you in advance for your help!


问:
SQL update with multiple joins
While transferring an existing database from Access to SQL, I'm trying to update a table in SQL called Component, but it is taking duplicates. The query I've written looks like this:

```<code>update CDB2020.dbo.Components
set PartType_ID = pt.PartType_ID
from CDB2020.dbo.PartType as pt
inner join AccessDataMigration_1.dbo.[B-K Data] as a on pt.Name = a.[Part Type]
inner join CDB2020.dbo.ComponentType as ct on ct.Name = a.[Component Type]
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no];
</code>```

The tables I'm using is created like so:

```<code>CREATE TABLE [dbo].[Components](
    [BK_ID] [nchar](255) NOT NULL,
    [Value] [nchar](255) NULL,
    [Description] [nchar](255) NULL,
    [PartType_ID] [int] NULL,
 CONSTRAINT [PK_Components] PRIMARY KEY CLUSTERED
(
GO

ALTER TABLE [dbo].[Components]  WITH CHECK ADD  CONSTRAINT [FK_ComponentsPartType] FOREIGN KEY([PartType_ID])
REFERENCES [dbo].[PartType] ([PartType_ID])
</code>```

The table already holds the BK_ID, Value, and Description data. Now I need to insert the PartType_ID.

The table PartType is created like so:

```<code>CREATE TABLE [dbo].[PartType](
    [PartType_ID] [int] IDENTITY(0,1) NOT NULL,
    [Name] [nchar](50) NOT NULL,
    [ComponentType_ID] [int] NOT NULL,
 CONSTRAINT [PK_PartType] PRIMARY KEY CLUSTERED

ALTER TABLE [dbo].[PartType]  WITH CHECK ADD  CONSTRAINT [FK_PartTypeComponentType] FOREIGN KEY([ComponentType_ID])
REFERENCES [dbo].[ComponentType] ([ComponentType_ID])
GO

ALTER TABLE [dbo].[PartType] CHECK CONSTRAINT [FK_PartTypeComponentType]
</code>```

Which refers to:

```<code>CREATE TABLE [dbo].[ComponentType](
    [ComponentType_ID] [int] IDENTITY(0,1) NOT NULL,
    [Name] [nchar](50) NOT NULL,
 CONSTRAINT [PK_ComponentType] PRIMARY KEY CLUSTERED
</code>```

The table [B-K Data] in the AccessDataMigration_1 DB is the table holding the information about legal combinations of component ID, part type and component type:

```<code>CREATE TABLE [dbo].[B-K Data](
    [B-K no] [nvarchar](255) NULL,
    [Value] [nvarchar](255) NULL,
    [Text] [nvarchar](255) NULL,
    [Component Type] [nvarchar](50) NULL,
    [Part Type] [nvarchar](255) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code>```

The problem is, that when I've used the update query, it creates duplicates. Here, I've used the following select query to demonstrate the problem:

```<code>Select comp.BK_ID, pt.PartType_ID, pt.Name as PartType, ct.Name as ComponentType
from (((AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as comp on comp.BK_ID = a.[B-K no])
inner join CDB2020.dbo.ComponentType as ct on ct.Name = a.[Component Type])
inner join CDB2020.dbo.PartType as pt on pt.Name = a.[Part Type])

where BK_ID = 'CK0820'
</code>```

As seen from the picture, it knows that the component type is Capacitor, and that the part type is MISCELLANEOUS. However, the PartType_ID have 7(!) different instances, which is because it found 7 different instances where a component type was MISCELLANEOUS.

I want my table to only hold ONE instance with the correct PartType_ID. What am I doing wrong in my Update query?

I've tried changing the update query to the following, but with same results.

```<code>CDB2020.dbo.Components
set PartType_ID = pt.PartType_ID
from CDB2020.dbo.PartType as pt
inner join AccessDataMigration_1.dbo.[B-K Data] as a on pt.Name = a.[Part Type]
inner join CDB2020.dbo.ComponentType as ct on ct.ComponentType_ID = pt.ComponentType_ID
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no];
</code>```

答:
I can see that the JOINs don't look right.  For instance you have:

```<code>CDB2020.dbo.ComponentType ct join
CDB2020.dbo.PartType pt
on pt.Name = a.[Part Type]
</code>```

From what I can tell, though, this should be:

```<code>CDB2020.dbo.ComponentType ct join
CDB2020.dbo.PartType pt
on pt.ComponentType_ID = ct.ComponentType_ID
</code>```

I can't tell if you have other problems of this sort.

Title: SQL update with multiple joins

Body:
While transferring an existing database from Access to SQL, I'm trying to update a table in SQL called Component, but it is taking duplicates. The query I've written looks like this:

update CDB2020.dbo.Components
set PartType_ID = pt.PartType_ID
from CDB2020.dbo.PartType as pt
inner join AccessDataMigration_1.dbo.[B-K Data] as a on pt.Name = a.[Part Type]
inner join CDB2020.dbo.ComponentType as ct on ct.Name = a.[Component Type]
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no];

The tables I'm using is created like so:

CREATE TABLE [dbo].[Components](
    [BK_ID] [nchar](255) NOT NULL,
    [Value] [nchar](255) NULL,
    [Description] [nchar](255) NULL,
    [PartType_ID] [int] NULL,
 CONSTRAINT [PK_Components] PRIMARY KEY CLUSTERED
(
GO

ALTER TABLE [dbo].[Components]  WITH CHECK ADD  CONSTRAINT [FK_ComponentsPartType] FOREIGN KEY([PartType_ID])
REFERENCES [dbo].[PartType] ([PartType_ID])

The table already holds the BK_ID, Value, and Description data. Now I need to insert the PartType_ID.

The table PartType is created like so:

CREATE TABLE [dbo].[PartType](
    [PartType_ID] [int] IDENTITY(0,1) NOT NULL,
    [Name] [nchar](50) NOT NULL,
    [ComponentType_ID] [int] NOT NULL,
 CONSTRAINT [PK_PartType] PRIMARY KEY CLUSTERED

ALTER TABLE [dbo].[PartType]  WITH CHECK ADD  CONSTRAINT [FK_PartTypeComponentType] FOREIGN KEY([ComponentType_ID])
REFERENCES [dbo].[ComponentType] ([ComponentType_ID])
GO

ALTER TABLE [dbo].[PartType] CHECK CONSTRAINT [FK_PartTypeComponentType]

Which refers to:

CREATE TABLE [dbo].[ComponentType](
    [ComponentType_ID] [int] IDENTITY(0,1) NOT NULL,
    [Name] [nchar](50) NOT NULL,
 CONSTRAINT [PK_ComponentType] PRIMARY KEY CLUSTERED

The table [B-K Data] in the AccessDataMigration_1 DB is the table holding the information about legal combinations of component ID, part type and component type:

CREATE TABLE [dbo].[B-K Data](
    [B-K no] [nvarchar](255) NULL,
    [Value] [nvarchar](255) NULL,
    [Text] [nvarchar](255) NULL,
    [Component Type] [nvarchar](50) NULL,
    [Part Type] [nvarchar](255) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

The problem is, that when I've used the update query, it creates duplicates. Here, I've used the following select query to demonstrate the problem:

Select comp.BK_ID, pt.PartType_ID, pt.Name as PartType, ct.Name as ComponentType
from (((AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as comp on comp.BK_ID = a.[B-K no])
inner join CDB2020.dbo.ComponentType as ct on ct.Name = a.[Component Type])
inner join CDB2020.dbo.PartType as pt on pt.Name = a.[Part Type])

where BK_ID = 'CK0820'

As seen from the picture, it knows that the component type is Capacitor, and that the part type is MISCELLANEOUS. However, the PartType_ID have 7(!) different instances, which is because it found 7 different instances where a component type was MISCELLANEOUS.

I want my table to only hold ONE instance with the correct PartType_ID. What am I doing wrong in my Update query?

I've tried changing the update query to the following, but with same results.

CDB2020.dbo.Components
set PartType_ID = pt.PartType_ID
from CDB2020.dbo.PartType as pt
inner join AccessDataMigration_1.dbo.[B-K Data] as a on pt.Name = a.[Part Type]
inner join CDB2020.dbo.ComponentType as ct on ct.ComponentType_ID = pt.ComponentType_ID
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no];

Body:
I can see that the JOINs don't look right.  For instance you have:

CDB2020.dbo.ComponentType ct join
CDB2020.dbo.PartType pt
on pt.Name = a.[Part Type]

From what I can tell, though, this should be:

CDB2020.dbo.ComponentType ct join
CDB2020.dbo.PartType pt
on pt.ComponentType_ID = ct.ComponentType_ID

I can't tell if you have other problems of this sort.


问:
Using PDFbox to determine the coordinates of words in a document
I'm using PDFbox to extract the coordinates of words/strings in a PDF document, and have so far had success determining the position of individual characters. this is the code thus far, from the PDFbox doc:

```<code>package printtextlocations;

import java.io.*;
import org.apache.pdfbox.exceptions.InvalidPasswordException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.pdfbox.util.TextPosition;

import java.io.IOException;
import java.util.List;

public class PrintTextLocations extends PDFTextStripper {

    public PrintTextLocations() throws IOException {
        super.setSortByPosition(true);
    }

    public static void main(String[] args) throws Exception {

        PDDocument document = null;
        try {
            File input = new File("C:\\path\\to\\PDF.pdf");
            document = PDDocument.load(input);
            if (document.isEncrypted()) {
                try {
                    document.decrypt("");
                } catch (InvalidPasswordException e) {
                    System.err.println("Error: Document is encrypted with a password.");
                    System.exit(1);
                }
            }
            PrintTextLocations printer = new PrintTextLocations();
            List allPages = document.getDocumentCatalog().getAllPages();
            for (int i = 0; i < allPages.size(); i++) {
                PDPage page = (PDPage) allPages.get(i);
                System.out.println("Processing page: " + i);
                PDStream contents = page.getContents();
                if (contents != null) {
                    printer.processStream(page, page.findResources(), page.getContents().getStream());
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }

    /**
     * @param text The text to be processed
     */
    @Override /* this is questionable, not sure if needed... */
    protected void processTextPosition(TextPosition text) {
        System.out.println("String[" + text.getXDirAdj() + ","
                + text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="
                + text.getXScale() + " height=" + text.getHeightDir() + " space="
                + text.getWidthOfSpace() + " width="
                + text.getWidthDirAdj() + "]" + text.getCharacter());
    }
}
</code>```

This produces a series of lines containing the position of each character, including spaces, that looks like this:

```<code>String[202.5604,41.880127 fs=1.0 xscale=13.98 height=9.68814 space=3.8864403 width=9.324661]P
</code>```

Where 'P' is the character. I have not been able to find a function in PDFbox to find words, and I am not familiar enough with Java to be able to accurately concatenate these characters back into words to search through even though the spaces are also included. Has anyone else been in a similar situation, and if so how did you approach it? I really only need the coordinate of the first character in the word so that parts simplified, but as to how I'm going to match a string against that kind of output is beyond me.

答:
For those who still need assistance, this is what I used in my code and should be useful to start with. It uses PDFBox 2.0.16

```<code>public class PDFTextLocator extends PDFTextStripper {

    private static String key_string;
    private static float x;
    private static float y;

    public PDFTextLocator() throws IOException {
        x = -1;
        y = -1;
    }

    /**
     * Takes in a PDF Document, phrase to find, and page to search and returns the x,y in float array
     * @param document
     * @param phrase
     * @param page
     * @return
     * @throws IOException
     */
    public static float[] getCoordiantes(PDDocument document, String phrase, int page) throws IOException {
        key_string = phrase;
        PDFTextStripper stripper = new PDFTextLocator();
        stripper.setSortByPosition(true);
        stripper.setStartPage(page);
        stripper.setEndPage(page);
        stripper.writeText(document, new OutputStreamWriter(new ByteArrayOutputStream()));
        y = document.getPage(page).getMediaBox().getHeight()-y;

        return new float[]{x,y};
    }

    /**
     * Override the default functionality of PDFTextStripper.writeString()
     */
    @Override
    protected void writeString(String string, List<TextPosition> textPositions) throws IOException {
        if(string.contains(key_string)) {
            TextPosition text = textPositions.get(0);
            if(x == -1) {
                x = text.getXDirAdj();
                y = text.getYDirAdj();
            }
        }
    }
}
</code>```

Below is the Maven dependency details,

```<code><dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.16</version>
</dependency>
</code>```

Body:
I'm using PDFbox to extract the coordinates of words/strings in a PDF document, and have so far had success determining the position of individual characters. this is the code thus far, from the PDFbox doc:

package printtextlocations;

import java.io.*;
import org.apache.pdfbox.exceptions.InvalidPasswordException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.pdfbox.util.TextPosition;

import java.io.IOException;
import java.util.List;

public class PrintTextLocations extends PDFTextStripper {

    public PrintTextLocations() throws IOException {
        super.setSortByPosition(true);
    }

    public static void main(String[] args) throws Exception {

        PDDocument document = null;
        try {
            File input = new File("C:\\path\\to\\PDF.pdf");
            document = PDDocument.load(input);
            if (document.isEncrypted()) {
                try {
                    document.decrypt("");
                } catch (InvalidPasswordException e) {
                    System.err.println("Error: Document is encrypted with a password.");
                    System.exit(1);
                }
            }
            PrintTextLocations printer = new PrintTextLocations();
            List allPages = document.getDocumentCatalog().getAllPages();
            for (int i = 0; i < allPages.size(); i++) {
                PDPage page = (PDPage) allPages.get(i);
                System.out.println("Processing page: " + i);
                PDStream contents = page.getContents();
                if (contents != null) {
                    printer.processStream(page, page.findResources(), page.getContents().getStream());
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }

    /**
     * @param text The text to be processed
     */
    @Override /* this is questionable, not sure if needed... */
    protected void processTextPosition(TextPosition text) {
        System.out.println("String[" + text.getXDirAdj() + ","
                + text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="
                + text.getXScale() + " height=" + text.getHeightDir() + " space="
                + text.getWidthOfSpace() + " width="
                + text.getWidthDirAdj() + "]" + text.getCharacter());
    }
}

This produces a series of lines containing the position of each character, including spaces, that looks like this:

String[202.5604,41.880127 fs=1.0 xscale=13.98 height=9.68814 space=3.8864403 width=9.324661]P

Where 'P' is the character. I have not been able to find a function in PDFbox to find words, and I am not familiar enough with Java to be able to accurately concatenate these characters back into words to search through even though the spaces are also included. Has anyone else been in a similar situation, and if so how did you approach it? I really only need the coordinate of the first character in the word so that parts simplified, but as to how I'm going to match a string against that kind of output is beyond me.

Body:
For those who still need assistance, this is what I used in my code and should be useful to start with. It uses PDFBox 2.0.16

public class PDFTextLocator extends PDFTextStripper {

    private static String key_string;
    private static float x;
    private static float y;

    public PDFTextLocator() throws IOException {
        x = -1;
        y = -1;
    }

    /**
     * Takes in a PDF Document, phrase to find, and page to search and returns the x,y in float array
     * @param document
     * @param phrase
     * @param page
     * @return
     * @throws IOException
     */
    public static float[] getCoordiantes(PDDocument document, String phrase, int page) throws IOException {
        key_string = phrase;
        PDFTextStripper stripper = new PDFTextLocator();
        stripper.setSortByPosition(true);
        stripper.setStartPage(page);
        stripper.setEndPage(page);
        stripper.writeText(document, new OutputStreamWriter(new ByteArrayOutputStream()));
        y = document.getPage(page).getMediaBox().getHeight()-y;

        return new float[]{x,y};
    }

    /**
     * Override the default functionality of PDFTextStripper.writeString()
     */
    @Override
    protected void writeString(String string, List<TextPosition> textPositions) throws IOException {
        if(string.contains(key_string)) {
            TextPosition text = textPositions.get(0);
            if(x == -1) {
                x = text.getXDirAdj();
                y = text.getYDirAdj();
            }
        }
    }
}

Below is the Maven dependency details,

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.16</version>
</dependency>


问:
How I can understand from which URL the request came to the controller?
I tried to watch,

```<code>request.path_parameters
</code>```

but its not bring any result. I would be grateful for any advice

答:
original_url

Returns the original request URL as a String.

```<code># get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"
</code>```

Unless your asking about the referer header which can contain the URL that linked / redirected to your site. Which you can get through request.referer. But there is no real guarantee that the referer header is sent by the client.

Body:
I tried to watch,

request.path_parameters

but its not bring any result. I would be grateful for any advice

Body:
original_url

Returns the original request URL as a String.

# get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"

Unless your asking about the referer header which can contain the URL that linked / redirected to your site. Which you can get through request.referer. But there is no real guarantee that the referer header is sent by the client.


问:
Azure Blob Storage: Is there a timestamp for blob file?
I need to find out the most recently added blob files to the blob storage. Is there a timestamp associated with each blob file? If not, what's the best way (for easy retrieval) to add it?</p>

答:
Solution was based on above solution provided by @Lukkha only .
PSB the solution where I used a dictionary with name of blob as key and DateStamp as Value.(K-V pair)</p>

```<code>blob_service = BlockBlobService(account_name=account, account_key=key, endpoint_suffix=domain)
generator = blob_service.list_blobs(container_name=container)

available_json_dict = {}
for blob in generator:
    blobName = blob.name.split('/')[-1]+'.json'
    available_json_dict[blobName] = last_modified
    last_modified = blob.properties.last_modified.strftime('%Y%m%d')
    print(blobName,'--->',last_modified)
</code>```

Body:
Solution was based on above solution provided by @Lukkha only .
PSB the solution where I used a dictionary with name of blob as key and DateStamp as Value.(K-V pair)

blob_service = BlockBlobService(account_name=account, account_key=key, endpoint_suffix=domain)
generator = blob_service.list_blobs(container_name=container)

available_json_dict = {}
for blob in generator:
    blobName = blob.name.split('/')[-1]+'.json'
    available_json_dict[blobName] = last_modified
    last_modified = blob.properties.last_modified.strftime('%Y%m%d')
    print(blobName,'--->',last_modified)


问:
Predicting class label for single image in image classification
I am designing a Static Hand Gesture Recognition using deep learning neural networks.
I started with this implementation on kaggle - https://www.kaggle.com/ranjeetjain3/deep-learning-using-sign-langugage/notebook#Sign-Language.
The accuracy of this looks very high, but when I try predictions for custom images, I am getting wrong results. As a newbie, I doubt my interpretation and need help for it.

Below is my code with prediction:

```<code>import matplotlib.image as mpimg
import matplotlib.pyplot as plt

# Read Images
infer_image = mpimg.imread('D:\\Mayuresh\\DL using SL MNIST\\input\\infer\\7.png')
plt.imshow(infer_image)

# Resizing before the prediction
infer_image = np.resize(infer_image, (28,28,1))
infer_image_arr = np.array(infer_image)
infer_image_arr = infer_image_arr.reshape(1,28,28,1)

# Prediction
y_pred = model.predict_classes(infer_image_arr)
print(y_pred)

# Dictionary for translation
my_dict2 = {
    0: 'a',
    1: 'b',
    2: 'c',
    3: 'd',
    4: 'e',
    5: 'f',
    6: 'g',
    7: 'h',
    8: 'i',
    9: 'k',
    10: 'l',
    11: 'm',
    12: 'n',
    13: 'o',
    14: 'p',
    15: 'q',
    16: 'r',
    17: 's',
    18: 't',
    19: 'u',
    20: 'v',
    21: 'w',
    22: 'x',
    23: 'y'
}

my_dict2[int(y_pred)]

</code>```

Can someone suggest changes needed or a snippet to predict the hand gesture for one image?

答:
I believe you need a codebase where you can train your model on the dataset that you generate. Based on things like your background, light settings etc. That would be better than using a pre-trained model which is trained on the data from the different distribution

I would recommend using this where you can start video feed and training images will be automatically taken for the gestures. You also can select the number of classes you want. That can improve your performance. Or else you can use the original code Emojinator which can detect 13 hand gestures

Body:
I am designing a Static Hand Gesture Recognition using deep learning neural networks.
I started with this implementation on kaggle - https://www.kaggle.com/ranjeetjain3/deep-learning-using-sign-langugage/notebook#Sign-Language.
The accuracy of this looks very high, but when I try predictions for custom images, I am getting wrong results. As a newbie, I doubt my interpretation and need help for it.

Below is my code with prediction:

import matplotlib.image as mpimg
import matplotlib.pyplot as plt

# Read Images
infer_image = mpimg.imread('D:\\Mayuresh\\DL using SL MNIST\\input\\infer\\7.png')
plt.imshow(infer_image)

# Resizing before the prediction
infer_image = np.resize(infer_image, (28,28,1))
infer_image_arr = np.array(infer_image)
infer_image_arr = infer_image_arr.reshape(1,28,28,1)

# Prediction
y_pred = model.predict_classes(infer_image_arr)
print(y_pred)

# Dictionary for translation
my_dict2 = {
    0: 'a',
    1: 'b',
    2: 'c',
    3: 'd',
    4: 'e',
    5: 'f',
    6: 'g',
    7: 'h',
    8: 'i',
    9: 'k',
    10: 'l',
    11: 'm',
    12: 'n',
    13: 'o',
    14: 'p',
    15: 'q',
    16: 'r',
    17: 's',
    18: 't',
    19: 'u',
    20: 'v',
    21: 'w',
    22: 'x',
    23: 'y'
}

my_dict2[int(y_pred)]

Can someone suggest changes needed or a snippet to predict the hand gesture for one image?