qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
32,586,612 | I was getting started with **AWS' Elastic Beanstalk**.
I am following this [tutorial](https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/) to **deploy a Django/PostgreSQL app**.
I did everything before the 'Configuring a Database' section. The deployment was also successful but I am g... | 2015/09/15 | [
"https://Stackoverflow.com/questions/32586612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4201498/"
] | The answer (<https://stackoverflow.com/a/47209268/6169225>) by [carl-g](https://stackoverflow.com/users/39396/carl-g) is correct. One thing that got me was that `requirements.txt` was in the wrong directory. Let's say you created a django project called `mysite`. This is the directory in which you run the `eb` command(... | If you forget the **.ebextensions** folder you will get the same error.
I was following along with a good simple (non Elastic Beanstalk) [tutorial](https://scotch.io/tutorials/build-your-first-python-and-django-application) and missed step 3 & 4 of [Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/lates... |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | It may be because you are using a virtual environment inside pyCharm, while you might have installed the library using system's default pip.
Check `Preferences->Project->Python Interpreter` inside Pycharm, and see if your library is listed there. If not, install it using **`+`** icon. Normally, if you use pyCharm's in... | Go to project interpreter and download mysql-connector.You need to install it also in pycharm |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | It may be because you are using a virtual environment inside pyCharm, while you might have installed the library using system's default pip.
Check `Preferences->Project->Python Interpreter` inside Pycharm, and see if your library is listed there. If not, install it using **`+`** icon. Normally, if you use pyCharm's in... | I was having this exact issue as well, after a while i solved it by **simply changing the name of my script in PyCharm**, turns out i had named my script mysql.py (because it was my first time attempting to connect it to python) and it was critically interfering with the import.
TLDR: **Change the name file if it's as... |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | It may be because you are using a virtual environment inside pyCharm, while you might have installed the library using system's default pip.
Check `Preferences->Project->Python Interpreter` inside Pycharm, and see if your library is listed there. If not, install it using **`+`** icon. Normally, if you use pyCharm's in... | People have commented with reasonable responses (and I'm sure OP is good on this by now) but they weren't super clear to me...
Don't use "pip3 install" in terminal in your pycharm project. In fact, uninstall any mysql connectors you have already using this method.
So now that you have verified there are no other mysq... |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | You need to import the connector as
```
import mysql.connector
```
Check the examples in the [docs](https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html) for this
If that doesn't work, then there might be an inconsistency between the interpreter that pycharm uses and the one you in... | Go to project interpreter and download mysql-connector.You need to install it also in pycharm |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | You need to import the connector as
```
import mysql.connector
```
Check the examples in the [docs](https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html) for this
If that doesn't work, then there might be an inconsistency between the interpreter that pycharm uses and the one you in... | I was having this exact issue as well, after a while i solved it by **simply changing the name of my script in PyCharm**, turns out i had named my script mysql.py (because it was my first time attempting to connect it to python) and it was critically interfering with the import.
TLDR: **Change the name file if it's as... |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | You need to import the connector as
```
import mysql.connector
```
Check the examples in the [docs](https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html) for this
If that doesn't work, then there might be an inconsistency between the interpreter that pycharm uses and the one you in... | People have commented with reasonable responses (and I'm sure OP is good on this by now) but they weren't super clear to me...
Don't use "pip3 install" in terminal in your pycharm project. In fact, uninstall any mysql connectors you have already using this method.
So now that you have verified there are no other mysq... |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | Go to project interpreter and download mysql-connector.You need to install it also in pycharm | I was having this exact issue as well, after a while i solved it by **simply changing the name of my script in PyCharm**, turns out i had named my script mysql.py (because it was my first time attempting to connect it to python) and it was critically interfering with the import.
TLDR: **Change the name file if it's as... |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | Go to project interpreter and download mysql-connector.You need to install it also in pycharm | People have commented with reasonable responses (and I'm sure OP is good on this by now) but they weren't super clear to me...
Don't use "pip3 install" in terminal in your pycharm project. In fact, uninstall any mysql connectors you have already using this method.
So now that you have verified there are no other mysq... |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | **EDIT:**
The answer is incorrect, because it is one type of recursion. It is called indirect recursion <https://en.wikipedia.org/wiki/Recursion_(computer_science)#Indirect_recursion>.
~~I think the simplest way to do this without recursion is the following:~~
```
import java.util.LinkedList;
import java.util.List... | Since the question is very interesting, I have tried to simplify the answer of *hide* :
```
public class Stackoverflow {
static class Handler {
void handle(Chain chain){
chain.process();
System.out.println("yeah");
}
}
static class Chain {
private List<Han... |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | Since the question is very interesting, I have tried to simplify the answer of *hide* :
```
public class Stackoverflow {
static class Handler {
void handle(Chain chain){
chain.process();
System.out.println("yeah");
}
}
static class Chain {
private List<Han... | Of course we can do it :) . No recursion at all!
```
public static void main(String[] args) {
throw new StackOverflowError();
}
``` |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | **EDIT:**
The answer is incorrect, because it is one type of recursion. It is called indirect recursion <https://en.wikipedia.org/wiki/Recursion_(computer_science)#Indirect_recursion>.
~~I think the simplest way to do this without recursion is the following:~~
```
import java.util.LinkedList;
import java.util.List... | Java stores primitive types on the stack. Objects created in local scope are allocated on the heap, with the reference to them on the stack.
You can overflow the stack without recursion by allocating too many primitive types in method scope. With normal stack size settings, you would have to allocate an excessive numb... |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | **EDIT:**
The answer is incorrect, because it is one type of recursion. It is called indirect recursion <https://en.wikipedia.org/wiki/Recursion_(computer_science)#Indirect_recursion>.
~~I think the simplest way to do this without recursion is the following:~~
```
import java.util.LinkedList;
import java.util.List... | Here is the implementation of [Eric J.](https://stackoverflow.com/users/141172/eric-j) idea of generating excessive number of local variables using javassist library:
```
class SoeNonRecursive {
static final String generatedMethodName = "holderForVariablesMethod";
@SneakyThrows
Class<?> createClassWithLot... |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | Here is the implementation of [Eric J.](https://stackoverflow.com/users/141172/eric-j) idea of generating excessive number of local variables using javassist library:
```
class SoeNonRecursive {
static final String generatedMethodName = "holderForVariablesMethod";
@SneakyThrows
Class<?> createClassWithLot... | Looking at this answer below, not sure if this works for Java, but sounds like you can declare an array of pointers? Might be able to achieve Eric J's idea without requiring a generator.
[Is it on the Stack or Heap?](https://stackoverflow.com/questions/1056444/is-it-on-the-stack-or-heap)
```
int* x[LARGENUMBER]; //... |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | Java stores primitive types on the stack. Objects created in local scope are allocated on the heap, with the reference to them on the stack.
You can overflow the stack without recursion by allocating too many primitive types in method scope. With normal stack size settings, you would have to allocate an excessive numb... | Looking at this answer below, not sure if this works for Java, but sounds like you can declare an array of pointers? Might be able to achieve Eric J's idea without requiring a generator.
[Is it on the Stack or Heap?](https://stackoverflow.com/questions/1056444/is-it-on-the-stack-or-heap)
```
int* x[LARGENUMBER]; //... |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | Here is the implementation of [Eric J.](https://stackoverflow.com/users/141172/eric-j) idea of generating excessive number of local variables using javassist library:
```
class SoeNonRecursive {
static final String generatedMethodName = "holderForVariablesMethod";
@SneakyThrows
Class<?> createClassWithLot... | Of course we can do it :) . No recursion at all!
```
public static void main(String[] args) {
throw new StackOverflowError();
}
``` |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | Java stores primitive types on the stack. Objects created in local scope are allocated on the heap, with the reference to them on the stack.
You can overflow the stack without recursion by allocating too many primitive types in method scope. With normal stack size settings, you would have to allocate an excessive numb... | Of course we can do it :) . No recursion at all!
```
public static void main(String[] args) {
throw new StackOverflowError();
}
``` |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | **EDIT:**
The answer is incorrect, because it is one type of recursion. It is called indirect recursion <https://en.wikipedia.org/wiki/Recursion_(computer_science)#Indirect_recursion>.
~~I think the simplest way to do this without recursion is the following:~~
```
import java.util.LinkedList;
import java.util.List... | Of course we can do it :) . No recursion at all!
```
public static void main(String[] args) {
throw new StackOverflowError();
}
``` |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | Since the question is very interesting, I have tried to simplify the answer of *hide* :
```
public class Stackoverflow {
static class Handler {
void handle(Chain chain){
chain.process();
System.out.println("yeah");
}
}
static class Chain {
private List<Han... | Looking at this answer below, not sure if this works for Java, but sounds like you can declare an array of pointers? Might be able to achieve Eric J's idea without requiring a generator.
[Is it on the Stack or Heap?](https://stackoverflow.com/questions/1056444/is-it-on-the-stack-or-heap)
```
int* x[LARGENUMBER]; //... |
59,707,234 | I'm unable to install pygraphviz even after installing graphviz and ensuring that cgraph.h is present in the directory.
I've also manually specified the directory for install. e.g. install-path
fatal error C1083: Cannot open include file: 'graphviz/cgraph.h': No such file or directory
Looking for any and all suggest... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59707234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9682236/"
] | On Ubuntu please do
`sudo apt install graphviz-dev` | For those who visit this page, you may already come across to this [fix](https://github.com/tan-wei/pygraphviz) or this [issue](https://github.com/pygraphviz/pygraphviz/issues/155) on GitHub and try to install GraphViz2.38 manually. But neither of them will work since GraphViz and PyGraphViz are 2 different libraries
... |
59,707,234 | I'm unable to install pygraphviz even after installing graphviz and ensuring that cgraph.h is present in the directory.
I've also manually specified the directory for install. e.g. install-path
fatal error C1083: Cannot open include file: 'graphviz/cgraph.h': No such file or directory
Looking for any and all suggest... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59707234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9682236/"
] | I installed the latest graphviz using the latest win64 executable from graphviz.org
[graphviz 2.49 win64](https://gitlab.com/api/v4/projects/4207231/packages/generic/graphviz-releases/2.49.0/stable_windows_10_cmake_Release_x64_graphviz-install-2.49.0-win64.exe)
then installation using the following command worked for... | For those who visit this page, you may already come across to this [fix](https://github.com/tan-wei/pygraphviz) or this [issue](https://github.com/pygraphviz/pygraphviz/issues/155) on GitHub and try to install GraphViz2.38 manually. But neither of them will work since GraphViz and PyGraphViz are 2 different libraries
... |
14,119,978 | I'm a newbie and was trying something in python 2.7.2 with Numpy which wasn't working as expected so wanted to check if there was something basic I was misunderstanding.
I was calculating a value for a triangle (trinormals) and then updating a value per point of the triangle (vertnormals) using an array of triangle in... | 2013/01/02 | [
"https://Stackoverflow.com/questions/14119978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942439/"
] | First the column in which you store the date should be an long type. This column will store the milliseconds from epoch for the date.
Now for Query
```
Calendar calendar = Calendar.getInstance(); // This will give you the current time.
// Removing the timestamp from current time to point to todays date
ca... | ```
Select *
From TABLE_NAME
WHERE DATEDIFF(day, GETDATE(), COLUMN_TABLE) <= 3
``` |
41,914,398 | I've written this very short spider to go to a U.S. News link and take the names of the colleges listed there.
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import scrapy
class CollegesSpider(scrapy.Spider):
name = "colleges"
start_urls = [
'http://colleges.usnews.rankingsandreviews.com/best-colleges... | 2017/01/28 | [
"https://Stackoverflow.com/questions/41914398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535448/"
] | Got it! It is because the robot detection.
Encode
```
>>> r = requests.get('http://colleges.usnews.rankingsandreviews.com/best-colleges/rankings/national-universities?_mode=list&acceptance-rate-max=20', headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 ... | I am on my mobile so don't remember exact variable name, but it should be robots\_follow
Set it to False |
41,914,398 | I've written this very short spider to go to a U.S. News link and take the names of the colleges listed there.
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import scrapy
class CollegesSpider(scrapy.Spider):
name = "colleges"
start_urls = [
'http://colleges.usnews.rankingsandreviews.com/best-colleges... | 2017/01/28 | [
"https://Stackoverflow.com/questions/41914398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535448/"
] | Got it! It is because the robot detection.
Encode
```
>>> r = requests.get('http://colleges.usnews.rankingsandreviews.com/best-colleges/rankings/national-universities?_mode=list&acceptance-rate-max=20', headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 ... | The page you're referring to as start url doesn't contain any element with id `view-1c4ddd8a-8b04-4c93-8b68-9b7b4e5d8969`- it looks like quite unique and doesn't seem to be the good choice for pretty universal XPath expression. I'd recommend to use something like `school.xpath('.//div[@data-view="colleges-search-result... |
28,610,556 | I'm a beginner in python, and I'm trying to write a program that makes a call to Weibo(Chinese Twitter) API and receive a json response. It's just a basic keyword search and fetching search result example.
But the problem is I don't know how to make an api call from python, so I'm keep getting error messages. The API ... | 2015/02/19 | [
"https://Stackoverflow.com/questions/28610556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4584513/"
] | If "if clause" has to span more than one lines of code you have to surround it with curly brackets "{}". Change your code to :
```
using System;
class Program
{
static void Main(string[] args)
{
int tal1, tal2;
int slinga;
tal2 = Convert.ToInt32(Console.ReadLine());
for (slin... | Following code lines are wrong
```
if (tal1 == 56)
Console.WriteLine(Addera(slinga, tal1));
tal2--;
else tal1 = 56;
```
You need to update it to
```
if (tal1 == 56){
Console.WriteLine(Addera(slinga, tal1));
tal2--;
}
else {
tal1 = 56;
}
```
Reason : You need `{ }` for multi-lined `if-el... |
28,610,556 | I'm a beginner in python, and I'm trying to write a program that makes a call to Weibo(Chinese Twitter) API and receive a json response. It's just a basic keyword search and fetching search result example.
But the problem is I don't know how to make an api call from python, so I'm keep getting error messages. The API ... | 2015/02/19 | [
"https://Stackoverflow.com/questions/28610556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4584513/"
] | If "if clause" has to span more than one lines of code you have to surround it with curly brackets "{}". Change your code to :
```
using System;
class Program
{
static void Main(string[] args)
{
int tal1, tal2;
int slinga;
tal2 = Convert.ToInt32(Console.ReadLine());
for (slin... | Change
```
if (tal1 == 56)
Console.WriteLine(Addera(slinga, tal1));
tal2--;
else tal1 = 56;
```
to
```
if (tal1 == 56)
{
Console.WriteLine(Addera(slinga, tal1));
tal2--;
}
else tal1 = 56;
```
The {} tells the compiler ... |
27,270,530 | I am worrying that this might be a really stupid question. However I can't find a solution.
I want to do the following operation in python without using a loop, because I am dealing with large size arrays.
Is there any suggestion?
```
import numpy as np
a = np.array([1,2,3,..., N]) # arbitrary 1d array
b = np.array([[... | 2014/12/03 | [
"https://Stackoverflow.com/questions/27270530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683468/"
] | To avoid Python-level loops, you could use `np.newaxis` to expand `a` (or None, which is the same thing):
```
>>> a = np.arange(1,5)
>>> b = np.arange(1,10).reshape((3,3))
>>> a[:,None,None]*b
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[ 2, 4, 6],
[ 8, 10, 12],
[14, 1... | Didn't understand this multiplication.. but here is a way to make matrix multiplication in python using numpy:
```
import numpy as np
a = np.matrix([1, 2])
b = np.matrix([[1, 2], [3, 4]])
result = a*b
print(result)
>>>result
matrix([7, 10])
``` |
27,270,530 | I am worrying that this might be a really stupid question. However I can't find a solution.
I want to do the following operation in python without using a loop, because I am dealing with large size arrays.
Is there any suggestion?
```
import numpy as np
a = np.array([1,2,3,..., N]) # arbitrary 1d array
b = np.array([[... | 2014/12/03 | [
"https://Stackoverflow.com/questions/27270530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683468/"
] | My answer uses only `numpy` primitives, in particular for the array multiplication (what you want to do has a name, it is an *outer product*).
Due to a restriction in `numpy`'s outer multiplication function we have to reshape the result, but this is very cheap because the data block of the `ndarray` is not involved.
... | Didn't understand this multiplication.. but here is a way to make matrix multiplication in python using numpy:
```
import numpy as np
a = np.matrix([1, 2])
b = np.matrix([[1, 2], [3, 4]])
result = a*b
print(result)
>>>result
matrix([7, 10])
``` |
36,774,171 | While building python from source on a MacOS, I accidntally overwrote the python that came with MacOS, now it doesn't have SSL. I tried to build again by running `--with-ssl` option
```
./configure --with-ssl
```
but when I subsequently ran `make`, it said this
```
Python build finished, but the necessary bits to b... | 2016/04/21 | [
"https://Stackoverflow.com/questions/36774171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577455/"
] | Just open `setup.py` and find method `detect_modules()`. It has some lines like (2.7.11 for me):
```
# Detect SSL support for the socket module (via _ssl)
search_for_ssl_incs_in = [
'/usr/local/ssl/include',
'/usr/contrib/ssl/include/'
... | First of all, MacOS only includes LibreSSL 2.2.7 libraries and no headers, you really want to install OpenSSL using homebrew:
```
$ brew install openssl
```
The openssl formula is a *keg-only* formula because the LibreSSL library is shadowing OpenSSL and Homebrew will not interfere with this. This means that you can... |
58,738,629 | I'm trying to convert string to date using `arrow` module.
During the conversion, I received this error:
`arrow.parser.ParserMatchError: Failed to match '%A %d %B %Y %I:%M:%S %p %Z' when parsing 'Wednesday 06 November 2019 03:05:42 PM CDT'`
The conversion is done using one simple line according to this [documentation]... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58738629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4193208/"
] | This looks like a [regex](https://www.regular-expressions.info/) kind of problem to me so use [Pattern](https://docs.oracle.com/javase/9/docs/api/java/util/regex/Pattern.html) class. By positively matching what we want, it implicitly ignores files that don't conform (like your `._` example)
```
final Pattern p = Patte... | What if instead of looking at the end of the filename, you inspected the beginning? It looks like the first part of the filename is consistently YYYY-MM, you could then parse out the year and the month using `.substring()` like so:
```
String year = pdfBills.substring(0, 4);
String month = pdfBills.substring(5, 7);
`... |
52,996,227 | I have a JSON file that looks like this:
```
{
"authors": [
{
"name": "John Steinbeck",
"description": "An author from Salinas California"
},
{
"name": "Mark Twain",
"description": "An icon of american literature",
"publications": [
{
"book": "Huckleberry Fin"
},
{
"book": "The Myster... | 2018/10/25 | [
"https://Stackoverflow.com/questions/52996227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163962/"
] | >
> "Use the force, Linq!" - Obi Enum Kenobi
>
>
>
```
using System.Linq;
List<Int32> numbers = new List<Int32>()
{
1,
2,
3,
4
};
String asString = String
.Join(
", ",
numbers.Select( n => n.ToString( CultureInfo.InvariantCulture ) )
);
List<Int32> fromString = asString
... | The easiest way is to make a new list each time and casting each item as you iterate. |
52,996,227 | I have a JSON file that looks like this:
```
{
"authors": [
{
"name": "John Steinbeck",
"description": "An author from Salinas California"
},
{
"name": "Mark Twain",
"description": "An icon of american literature",
"publications": [
{
"book": "Huckleberry Fin"
},
{
"book": "The Myster... | 2018/10/25 | [
"https://Stackoverflow.com/questions/52996227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163962/"
] | >
> "Use the force, Linq!" - Obi Enum Kenobi
>
>
>
```
using System.Linq;
List<Int32> numbers = new List<Int32>()
{
1,
2,
3,
4
};
String asString = String
.Join(
", ",
numbers.Select( n => n.ToString( CultureInfo.InvariantCulture ) )
);
List<Int32> fromString = asString
... | String is the 2nd worst format you can have. Only binary is slightly worse. If you got an Int, keep it an int. Do not transform anything into a string unless you **really** need to (like sending it via XML, use IO). This does not seem like such a case.
The only reason I can think you want to turn them into strings to ... |
52,996,227 | I have a JSON file that looks like this:
```
{
"authors": [
{
"name": "John Steinbeck",
"description": "An author from Salinas California"
},
{
"name": "Mark Twain",
"description": "An icon of american literature",
"publications": [
{
"book": "Huckleberry Fin"
},
{
"book": "The Myster... | 2018/10/25 | [
"https://Stackoverflow.com/questions/52996227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163962/"
] | String is the 2nd worst format you can have. Only binary is slightly worse. If you got an Int, keep it an int. Do not transform anything into a string unless you **really** need to (like sending it via XML, use IO). This does not seem like such a case.
The only reason I can think you want to turn them into strings to ... | The easiest way is to make a new list each time and casting each item as you iterate. |
1,168,687 | Right now I'm working on a scripting language that doesn't yet have a FFI. I'd like to know what's the most convenient way to get it in, assuming that I'd like to write it like cool geeks do - I'd like to write the FFI in the scripting language itself.
The programming language I need to interface is C. So for basics I... | 2009/07/22 | [
"https://Stackoverflow.com/questions/1168687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] | I think an appropiate answer requires a [detailed essay](http://vmathew.in/dnc.html).
Basically, there should be wrappers for the library loading and symbol searching facilities provided by the host OS. If the core datatypes of your language are internally represented with a single C data structure, then a requiremen... | Check out <http://sourceware.org/libffi/>
Remember the calling conventions are going to be different on different architectures, i.e. what order function variables are popped onto the stack. I don't know about writing it in your own scripting language, I do know that Java JNI uses libffi. |
63,966,342 | ```
import pandas as pd
import datetime as dt
from pandas_datareader import data as web
import yfinance as yf
yf.pdr_override()
```
filename=r'C:\Users\User\Desktop\from\_python\data\_from\_python.xlsx'
```
yeah = pd.read_excel(filename, sheet_name='entry')
stock = []
stock = list(yeah['name'])
stock = [ s.repla... | 2020/09/19 | [
"https://Stackoverflow.com/questions/63966342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13933399/"
] | You can try this answer using a package called [yahooquery](https://github.com/dpguthrie/yahooquery). Disclaimer: I am the author of the package.
```
from yahooquery import Ticker
import pandas as pd
symbols = ['^GSPC', 'NQ=F', 'AAU', 'ALB', 'AOS', 'APPS', 'AQB', 'ASPN', 'ATHM', 'AZRE', 'BCYC', 'BGNE', 'CAT', 'CC', '... | It processes stocks and sectors at the same time. However, some stocks do not have a sector, so an error countermeasure is added.
Since the issue column name consists of sector and issue name, we change it to a hierarchical column and update the retrieved data frame. Finally, I save it in CSV format to import it into E... |
18,828,124 | I am running my django web app in httpd .
In httpd.conf this is what I have.
```
Listen 8090
User ctaftest
Group ctaftest
```
And after starting httpd server when I do
`netstat -anp |grep httpd`
I get
```
root 31621 1 1 17:23 ? 00:00:00 /usr/local/httpd-python/bin/httpd -k start
ctaftest 31625 31... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18828124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371989/"
] | What does your WSGIDaemonProcess configuration in the rest of your Apache config look like? You can set the user there.
```
WSGIDaemonProcess mysite user=ctaftest group=ctaftest threads=5
``` | To start with, if you call:
```
os.path.expanduser("dir_path")
```
it should return just:
```
dir_path
```
Did you instead mean:
```
os.path.expanduser("~/dir_path")
```
Anyway, when you use embedded mode of mod\_wsgi, your code runs in the Apache child worker processes. These processes can be shared with othe... |
18,828,124 | I am running my django web app in httpd .
In httpd.conf this is what I have.
```
Listen 8090
User ctaftest
Group ctaftest
```
And after starting httpd server when I do
`netstat -anp |grep httpd`
I get
```
root 31621 1 1 17:23 ? 00:00:00 /usr/local/httpd-python/bin/httpd -k start
ctaftest 31625 31... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18828124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371989/"
] | What does your WSGIDaemonProcess configuration in the rest of your Apache config look like? You can set the user there.
```
WSGIDaemonProcess mysite user=ctaftest group=ctaftest threads=5
``` | To solve it , the accepted answer helped , however I had to add
```
`WSGIProcessGroup` directive also
```
So I configured something like this.
```
WSGIDaemonProcess ctaf.com user=ctaftest group=ctaftest threads=10 python-path=/home/ctaftest/virtualpython/CTAFWEB_PRODUCTION/ctafweb
WSGIProcessGroup ctaf.com
``` |
18,828,124 | I am running my django web app in httpd .
In httpd.conf this is what I have.
```
Listen 8090
User ctaftest
Group ctaftest
```
And after starting httpd server when I do
`netstat -anp |grep httpd`
I get
```
root 31621 1 1 17:23 ? 00:00:00 /usr/local/httpd-python/bin/httpd -k start
ctaftest 31625 31... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18828124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371989/"
] | To start with, if you call:
```
os.path.expanduser("dir_path")
```
it should return just:
```
dir_path
```
Did you instead mean:
```
os.path.expanduser("~/dir_path")
```
Anyway, when you use embedded mode of mod\_wsgi, your code runs in the Apache child worker processes. These processes can be shared with othe... | To solve it , the accepted answer helped , however I had to add
```
`WSGIProcessGroup` directive also
```
So I configured something like this.
```
WSGIDaemonProcess ctaf.com user=ctaftest group=ctaftest threads=10 python-path=/home/ctaftest/virtualpython/CTAFWEB_PRODUCTION/ctafweb
WSGIProcessGroup ctaf.com
``` |
48,171,851 | I can't find a command example for archiving a set of files from a given prefix in S3 into a given vault in Glacier using ONLY COMMAND LINE, i.e. no Lifecycles, no python+boto. Thanks.
This doc has a lot of examples but none fit my request:
<https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html> | 2018/01/09 | [
"https://Stackoverflow.com/questions/48171851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872286/"
] | That's because you can't. As described in the [Amazon's S3 Documentation](https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html):
>
> You cannot specify GLACIER as the storage class at the time that you create an object. You create GLACIER objects by first uploading objects using STANDARD, RRS, or ... | You're looking for this:
<https://aws.amazon.com/premiumsupport/knowledge-center/restore-s3-object-glacier-storage-class/>
```
aws s3 cp s3://bucketname/key/file s3://bucketname/key/file --storage-class GLACIER
```
optionally use --recursive instead of a specific file name. |
27,712,101 | I am trying to sort dictionaries in MongoDB. However, I get the value error "too many values to unpack" because I think it's implying that there are too many values in each dictionary (there are 16 values in each one). This is my code:
```
FortyMinute.find().sort(['Rank', 1])
```
Anyone know how to get around this?
... | 2014/12/30 | [
"https://Stackoverflow.com/questions/27712101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4392607/"
] | You pass the arguments and values in **unpacked** as so:
```
FortyMinute.find().sort('Rank', 1)
```
---
It is only when you're passing **multiple sort parameters** that you group arguments and values using lists, and then too you must surround all your parameters with a tuple as so:
```
FortyMinute.find().sort([(R... | If you want mong/pymongo to sort:
```
FortyMinute.find().sort('Rank', 1)
```
If you want to sort using multiple fields:
```
FortyMinute.find().sort([('Rank': 1,), ('other', -1,)])
```
You also have constants to make it more clear what you're doing:
```
FortyMinute.find().sort('Rank',pymongo.DESCENDING)
```
If ... |
50,208,381 | I'm experimenting with developing python flask app, and would like to configure the app to apache as a daemon, so I wouldn't need to restart apache after every change. The configuration is now like [instructed here](https://code.google.com/archive/p/modwsgi/wikis/QuickConfigurationGuide.wiki#Mounting_At_Root_Of_Site%20... | 2018/05/07 | [
"https://Stackoverflow.com/questions/50208381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364931/"
] | You can use `sapply` or `lapply` to accomplish it .
```
#supposing your data.frame is called 'df'
sapply(df, unique)
#$x1
#[1] 1 2 3 4 6 7 8
#
#$x2
#[1] 2 5 7 8 9 0
#
#$x3
#[1] 6 5 1 2 3 4
```
or
```
lapply(df, unique)
#$x1
#[1] 1 2 3 4 6 7 8
#
#$x2
#[1] 2 5 7 8 9 0
#
#$x3
#[1] 6 5 1 2 3 4
``` | ```
# Imagine D is your data.frame object
apply(D,1, function(x) rle(x)$values)
``` |
50,208,381 | I'm experimenting with developing python flask app, and would like to configure the app to apache as a daemon, so I wouldn't need to restart apache after every change. The configuration is now like [instructed here](https://code.google.com/archive/p/modwsgi/wikis/QuickConfigurationGuide.wiki#Mounting_At_Root_Of_Site%20... | 2018/05/07 | [
"https://Stackoverflow.com/questions/50208381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364931/"
] | ```
# Imagine D is your data.frame object
apply(D,1, function(x) rle(x)$values)
``` | ```
A=apply(dat,1,unique)
data.frame(t(sapply(A,`length<-`,max(lengths(A)))))
X1 X2 X3 X4 X5 X6 X7
1 1 2 3 4 6 7 8
2 2 5 7 8 9 0 NA
3 6 5 1 2 3 4 NA
``` |
50,208,381 | I'm experimenting with developing python flask app, and would like to configure the app to apache as a daemon, so I wouldn't need to restart apache after every change. The configuration is now like [instructed here](https://code.google.com/archive/p/modwsgi/wikis/QuickConfigurationGuide.wiki#Mounting_At_Root_Of_Site%20... | 2018/05/07 | [
"https://Stackoverflow.com/questions/50208381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364931/"
] | You can use `sapply` or `lapply` to accomplish it .
```
#supposing your data.frame is called 'df'
sapply(df, unique)
#$x1
#[1] 1 2 3 4 6 7 8
#
#$x2
#[1] 2 5 7 8 9 0
#
#$x3
#[1] 6 5 1 2 3 4
```
or
```
lapply(df, unique)
#$x1
#[1] 1 2 3 4 6 7 8
#
#$x2
#[1] 2 5 7 8 9 0
#
#$x3
#[1] 6 5 1 2 3 4
``` | ```
A=apply(dat,1,unique)
data.frame(t(sapply(A,`length<-`,max(lengths(A)))))
X1 X2 X3 X4 X5 X6 X7
1 1 2 3 4 6 7 8
2 2 5 7 8 9 0 NA
3 6 5 1 2 3 4 NA
``` |
56,034,831 | I am using Keras with `fit_generator()`. My generator connects to a Database (MongoDB in my case) to fetch data for each batch. If I use the multiprocessing flag of `fit_generator()` I get this Warning:
```
UserWarning: MongoClient opened before fork. Create MongoClient only after forking.
```
I am connecting to the... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56034831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | I don't have a mongo DB to test on but this might work - you can get the collection (connection?) on the first get-item of each process.
```py
class MyCustomGenerator(tf.keras.utils.Sequence):
def __init__(self, ...):
self.collection = None
def __len__(self):
...
def __getitem__(self, idx... | if you're using Python 3.7 you could use [os.register\_at\_fork](https://docs.python.org/3/library/os.html#os.register_at_fork) to trigger creating the database connection
for example you could do something like:
```
from os import register_at_fork
def reinit_dbcon():
generator_obj.collection = MagicMongoDBConne... |
13,927,122 | Trying to get this line of code to work, I keep running into issues no matter how I change the formatting around:
```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, [str(x) for x in [year, month, day]])):
```
(year, month, day) can be either ints or strings.
Traceback:
```
Traceback (most recent cal... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13927122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247832/"
] | You are missing the '\*' here:
```
>>> os.path.join('foo', *['a','b'])
'foo/a/b'
```
You have to use the star operator here in order to pass the list items as unpacked variable argument list to the method. | add \* before `[str(x) for x in [year, month, day]]`
`*[str(x) for x in [year, month, day]]` |
13,927,122 | Trying to get this line of code to work, I keep running into issues no matter how I change the formatting around:
```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, [str(x) for x in [year, month, day]])):
```
(year, month, day) can be either ints or strings.
Traceback:
```
Traceback (most recent cal... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13927122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247832/"
] | You are missing the '\*' here:
```
>>> os.path.join('foo', *['a','b'])
'foo/a/b'
```
You have to use the star operator here in order to pass the list items as unpacked variable argument list to the method. | ```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, str(year), str(month), str(day))):
```
for readability:
```
fname = os.path.join(IncludeSettings.FILE_URL, str(year), str(month), str(day))
if not os.path.exists(fname):
``` |
13,927,122 | Trying to get this line of code to work, I keep running into issues no matter how I change the formatting around:
```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, [str(x) for x in [year, month, day]])):
```
(year, month, day) can be either ints or strings.
Traceback:
```
Traceback (most recent cal... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13927122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247832/"
] | You are missing the '\*' here:
```
>>> os.path.join('foo', *['a','b'])
'foo/a/b'
```
You have to use the star operator here in order to pass the list items as unpacked variable argument list to the method. | @user1833746 had the answer first, so if you accept any of these, accept that one :)
In addition to the unpacking, if you aren't going to use the resulting list, you can change the `[`'s to `(` to make it a true generator (as opposed to creating a list and then iterating through that). The `*` operator 'unpacks', mean... |
13,927,122 | Trying to get this line of code to work, I keep running into issues no matter how I change the formatting around:
```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, [str(x) for x in [year, month, day]])):
```
(year, month, day) can be either ints or strings.
Traceback:
```
Traceback (most recent cal... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13927122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247832/"
] | @user1833746 had the answer first, so if you accept any of these, accept that one :)
In addition to the unpacking, if you aren't going to use the resulting list, you can change the `[`'s to `(` to make it a true generator (as opposed to creating a list and then iterating through that). The `*` operator 'unpacks', mean... | add \* before `[str(x) for x in [year, month, day]]`
`*[str(x) for x in [year, month, day]]` |
13,927,122 | Trying to get this line of code to work, I keep running into issues no matter how I change the formatting around:
```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, [str(x) for x in [year, month, day]])):
```
(year, month, day) can be either ints or strings.
Traceback:
```
Traceback (most recent cal... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13927122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247832/"
] | @user1833746 had the answer first, so if you accept any of these, accept that one :)
In addition to the unpacking, if you aren't going to use the resulting list, you can change the `[`'s to `(` to make it a true generator (as opposed to creating a list and then iterating through that). The `*` operator 'unpacks', mean... | ```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, str(year), str(month), str(day))):
```
for readability:
```
fname = os.path.join(IncludeSettings.FILE_URL, str(year), str(month), str(day))
if not os.path.exists(fname):
``` |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I got the same error, but in my case I am subtracting dict.key from dict.value. I have fixed this by subtracting dict.value for corresponding key from other dict.value.
```
cosine_sim = cosine_similarity(e_b-e_a, w-e_c)
```
here I got error because e\_b, e\_a and e\_c are embedding vector for word a,b,c respectively... | I ran into the same issue, but in my case it was just a Python list instead of a Numpy array used. Using two Numpy arrays solved the issue for me. |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I got the same error, but in my case I am subtracting dict.key from dict.value. I have fixed this by subtracting dict.value for corresponding key from other dict.value.
```
cosine_sim = cosine_similarity(e_b-e_a, w-e_c)
```
here I got error because e\_b, e\_a and e\_c are embedding vector for word a,b,c respectively... | I had a similar issue where an integer in a row of a DataFrame I was iterating over was of type `numpy.int64`. I got the
>
> `TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')`
>
>
>
error when trying to subtract a float from it.
The easiest... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I had a similar issue where an integer in a row of a DataFrame I was iterating over was of type `numpy.int64`. I got the
>
> `TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')`
>
>
>
error when trying to subtract a float from it.
The easiest... | I am fairly new to this myself, but I had a similar error and found that it is due to a type casting issue. I was trying to concatenate rather than take the difference but I think the principle is the same here. I provided a similar answer on another [question](https://stackoverflow.com/questions/34264282/typeerror-ufu... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I had a similar issue where an integer in a row of a DataFrame I was iterating over was of type `numpy.int64`. I got the
>
> `TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')`
>
>
>
error when trying to subtract a float from it.
The easiest... | I think @James is right. I got stuck by same error while working on Polyval(). And yeah solution is to use the same type of variabes. You can use typecast to cast all variables in the same type.
BELOW IS A EXAMPLE CODE
```
import numpy
P = numpy.array(input().split(), float)
x = float(input())
print(numpy.polyval(P,x... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I am fairly new to this myself, but I had a similar error and found that it is due to a type casting issue. I was trying to concatenate rather than take the difference but I think the principle is the same here. I provided a similar answer on another [question](https://stackoverflow.com/questions/34264282/typeerror-ufu... | I ran into the same issue, but in my case it was just a Python list instead of a Numpy array used. Using two Numpy arrays solved the issue for me. |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | Why is it applying `diff` to an array of strings.
I get an error at the same point, though with a different message
```
In [23]: a=np.array([u'A' u'B' u'C' u'D' u'E'])
In [24]: np.diff(a)
---------------------------------------------------------------------------
TypeError Traceback (... | I had a similar issue where an integer in a row of a DataFrame I was iterating over was of type `numpy.int64`. I got the
>
> `TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')`
>
>
>
error when trying to subtract a float from it.
The easiest... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I am fairly new to this myself, but I had a similar error and found that it is due to a type casting issue. I was trying to concatenate rather than take the difference but I think the principle is the same here. I provided a similar answer on another [question](https://stackoverflow.com/questions/34264282/typeerror-ufu... | I think @James is right. I got stuck by same error while working on Polyval(). And yeah solution is to use the same type of variabes. You can use typecast to cast all variables in the same type.
BELOW IS A EXAMPLE CODE
```
import numpy
P = numpy.array(input().split(), float)
x = float(input())
print(numpy.polyval(P,x... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I got the same error, but in my case I am subtracting dict.key from dict.value. I have fixed this by subtracting dict.value for corresponding key from other dict.value.
```
cosine_sim = cosine_similarity(e_b-e_a, w-e_c)
```
here I got error because e\_b, e\_a and e\_c are embedding vector for word a,b,c respectively... | I am fairly new to this myself, but I had a similar error and found that it is due to a type casting issue. I was trying to concatenate rather than take the difference but I think the principle is the same here. I provided a similar answer on another [question](https://stackoverflow.com/questions/34264282/typeerror-ufu... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | Why is it applying `diff` to an array of strings.
I get an error at the same point, though with a different message
```
In [23]: a=np.array([u'A' u'B' u'C' u'D' u'E'])
In [24]: np.diff(a)
---------------------------------------------------------------------------
TypeError Traceback (... | I am fairly new to this myself, but I had a similar error and found that it is due to a type casting issue. I was trying to concatenate rather than take the difference but I think the principle is the same here. I provided a similar answer on another [question](https://stackoverflow.com/questions/34264282/typeerror-ufu... |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | Why is it applying `diff` to an array of strings.
I get an error at the same point, though with a different message
```
In [23]: a=np.array([u'A' u'B' u'C' u'D' u'E'])
In [24]: np.diff(a)
---------------------------------------------------------------------------
TypeError Traceback (... | I think @James is right. I got stuck by same error while working on Polyval(). And yeah solution is to use the same type of variabes. You can use typecast to cast all variables in the same type.
BELOW IS A EXAMPLE CODE
```
import numpy
P = numpy.array(input().split(), float)
x = float(input())
print(numpy.polyval(P,x... |
18,624,148 | I'm struggling to find documentation on what the ^ does in python.
EX.
>
>
> >
> >
> > >
> > > 6^1 =
> > > 7
> > >
> > >
> > > 6^2 =
> > > 4
> > >
> > >
> > > 6^3 =
> > > 5
> > >
> > >
> > > 6^4 =
> > > 2
> > >
> > >
> > > 6^5 =
> > > 3
> > >
> > >
> > > 6^6 =
> > > 0
> > >
> > >
> > >
> >
> ... | 2013/09/04 | [
"https://Stackoverflow.com/questions/18624148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2748552/"
] | It is the [bitwise exclusive-or operator](https://en.wikipedia.org/wiki/Xor#Bitwise_operation), often called "xor". For each pair of corresponding bits in the operands, the corresponding bit in the result is 0 if the operand bits are the same, 1 if they are different.
Consider `6^4`:
```
6 = 0b0110
4 = 0b0100
6^4... | for more information on XOR , please react the documentation on Python.org at here:
<http://docs.python.org/2/library/operator.html> |
38,943,673 | I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like:
```
{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26',... | 2016/08/14 | [
"https://Stackoverflow.com/questions/38943673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6715128/"
] | You can achieve this using separate routes, or change your parameters to be optional.
When using 3 attributes, you add separate routes for each of the options that you have - when no parameters are specified, when only `movieId` is specified, and when all 3 parameters are specified.
```
[Route("Everything/MovieCustom... | >
> Keep in mind that neither sample supports the case where you provide only customerId.
>
>
>
Check it out. I think you can use the multiple route method with EVEN ANOTHER route like this if you do want to provide only customerId:
```
[Route("Everything/MovieCustomer/null/{customerId}")]
``` |
38,943,673 | I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like:
```
{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26',... | 2016/08/14 | [
"https://Stackoverflow.com/questions/38943673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6715128/"
] | You can achieve this using separate routes, or change your parameters to be optional.
When using 3 attributes, you add separate routes for each of the options that you have - when no parameters are specified, when only `movieId` is specified, and when all 3 parameters are specified.
```
[Route("Everything/MovieCustom... | Interstingly, I had to add optional parameter to the signature as well for it to work from Angular client like so:
```
[HttpGet]
[Route("IsFooBar/{movieId?}/{customerId?}")]
[Route("IsFooBar/null/{customerId?}")]
public bool IsFooBar(int? movieId = null, int? customerId = null)
{
// the rest of the code
}
```
In... |
47,117,625 | I want to split any matrix (most likely will be a 3x4) into two. One part will be the left hand and then the right hand - only the last column.
```
[[1,0,0,4], [[1,0,0], [4,
[1,0,0,2], ---> A= [1,0,0], B = 2,
[4,3,1,6]] [4,3,1]] 6]
```
Is there a way to do this in ... | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8606331/"
] | Yes, you could do like this:
```
def split_last_col(mat):
"""returns a tuple of two matrices corresponding
to the Left and Right parts"""
A = [line[:-1] for line in mat]
B = [line[-1] for line in mat]
return A, B
split_last_col([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
```
### output:
```
([[1, 2], [... | You could create A and B manually, like this:
```
def split(matrix):
a = list()
b = list()
for row in matrix:
row_length = len(row)
a_row = list()
for index, col in enumerate(row):
if index == row_length - 1:
b.append(col)
else:
a_row.append(col)
a.append(a_row)
re... |
59,363,950 | I'm trying to get started with Tensorflow-Hub to extract feature vectors from images. However, I'm not sure how one is meant to convert Tensorflow-Hub outputs (Tensors) to numpy vectors. Here's a simple example:
```
from keras.preprocessing.image import load_img
import tensorflow_hub as hub
import tensorflow as tf
imp... | 2019/12/16 | [
"https://Stackoverflow.com/questions/59363950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1727392/"
] | The following should work. But I did not check if the output is meaningful. But it is returning consistent results over multiple runs.
```
im = load_img('sample.png')
im = np.expand_dims(im.resize((299,299)), 0)
module = hub.Module("https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1")
out = module(im)
... | You can use
```py
out.numpy()
type(out)
# <class 'tensorflow.python.framework.ops.EagerTensor'>
type(out.numpy()
# <class 'numpy.ndarray'>
``` |
44,805,535 | I am an anaconda user and Jupyter is a neat tool to run python code. However, for my macbook, I can't open it in Chrome (This page isn’t working
localhost didn’t send any data.),but it works in Safari, I have tried to reinstall chrome, but I still can't fix it. My system is Mac OS 10.11.5.
Who knows how I can fix it?
... | 2017/06/28 | [
"https://Stackoverflow.com/questions/44805535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3013618/"
] | You could change your approach to avoid fixed padding values:
```css
#secondary-menu {
background: #007dc5;
width: 80%;
}
ul#topnav {
list-style: none;
padding: 0;
height: 70px;
display: flex;
align-items: center;
justify-content: center;
}
ul#topnav li a {
text-transform: uppercase;
... | Add `overflow:hidden` to your `ul#topnav` rules:
```
ul#topnav {
list-style: none;
margin: 0 auto;
height: 70px;
display: flex;
align-items: center;
overflow:hidden;
}
```
```css
#secondary-menu {
background: #007dc5;
width: 80%;
}
ul#topnav {
list-style: none;
margin: 0 auto;
height: 7... |
54,411,732 | So far I'm able to print at the end if the user selects 'n' to not order another hard drive, but need to write to a file. I've tried running the code as 'python hdorders.py >> orders.txt', but it won't prompt for the questions; only shows a blank line and if I break out using Ctrl-C, it writes blank entries and while l... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54411732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9638138/"
] | No. One team project has one process template. You can customize that process template however you wish, of course. | What you could do is create an inherited process in order to make your customizations, and change every Team Project to that Process.
You have to take into account that the customizations you have made to your Team Project could be affected when you change to a inherited process.
Test carefully with some test Team Pr... |
35,719,165 | I have a python program with one main thread and let's say 2 other threads (or maybe even more, probably doesn't matter). I would like to let the main thread sleep until ONE of the other threads is finished. It's easy to do with polling (by calling t.join(1) and waiting for one second for every thread t).
Is it possi... | 2016/03/01 | [
"https://Stackoverflow.com/questions/35719165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2384856/"
] | Here is an example of using condition object.
```
from threading import Thread, Condition, Lock
from time import sleep
from random import random
_lock = Lock()
def run(idx, condition):
sleep(random() * 3)
print('thread_%d is waiting for notifying main thread.' % idx)
_lock.acquire()
with condition:
... | You can create a Thread Class and the main thread keeps a reference to it. So you can check whether the thread has finished and make your main thread continue again easily.
If that doesn't helped you, I suggest you to look at the **Queue** library!
```
import threading
import time, random
#THREAD CLASS#
class Thread... |
35,719,165 | I have a python program with one main thread and let's say 2 other threads (or maybe even more, probably doesn't matter). I would like to let the main thread sleep until ONE of the other threads is finished. It's easy to do with polling (by calling t.join(1) and waiting for one second for every thread t).
Is it possi... | 2016/03/01 | [
"https://Stackoverflow.com/questions/35719165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2384856/"
] | One solution is to use a `multiprocessing.dummy.Pool`; `multiprocessing.dummy` provides an API almost identical to `multiprocessing`, but backed by threads, so it gets you a thread pool for free.
For example, you can do:
```
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(2) # Two workers
for... | You can create a Thread Class and the main thread keeps a reference to it. So you can check whether the thread has finished and make your main thread continue again easily.
If that doesn't helped you, I suggest you to look at the **Queue** library!
```
import threading
import time, random
#THREAD CLASS#
class Thread... |
35,719,165 | I have a python program with one main thread and let's say 2 other threads (or maybe even more, probably doesn't matter). I would like to let the main thread sleep until ONE of the other threads is finished. It's easy to do with polling (by calling t.join(1) and waiting for one second for every thread t).
Is it possi... | 2016/03/01 | [
"https://Stackoverflow.com/questions/35719165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2384856/"
] | One solution is to use a `multiprocessing.dummy.Pool`; `multiprocessing.dummy` provides an API almost identical to `multiprocessing`, but backed by threads, so it gets you a thread pool for free.
For example, you can do:
```
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(2) # Two workers
for... | Here is an example of using condition object.
```
from threading import Thread, Condition, Lock
from time import sleep
from random import random
_lock = Lock()
def run(idx, condition):
sleep(random() * 3)
print('thread_%d is waiting for notifying main thread.' % idx)
_lock.acquire()
with condition:
... |
35,667,252 | I have installed the python 3.5 interpretor in my device (Windows).
Can anybody guide me through the process of using packages to run it like `SublimeREPL`? | 2016/02/27 | [
"https://Stackoverflow.com/questions/35667252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5987890/"
] | Yes, you can use any Python version you want to run programs from Sublime - you just need to define a new [build system](http://sublimetext.info/docs/en/reference/build_systems.html). Select **`Tools -> Build System -> New Build System`**, then delete its contents and replace it with:
```js
{
"cmd": ["C:/Python35/... | if you have installed python3 and SublimeREPL, you can try setting up key bindings with the correct path to the python3 file.
```
[
{
"keys":["super+ctrl+r"],
"command": "repl_open",
"caption": "Python 3.6 - Open File",
"id": "repl_python",
... |
36,142,393 | In the terminal, after I enter the python interpreter I use `help('modules')` to see which modules are installed but Numpy, matplotlib and scipy are not listed.
When I try to import them, I get the following:
>
> ImportError: no module named xxx.
>
>
>
However, when I try to install these modules using `apt-get... | 2016/03/21 | [
"https://Stackoverflow.com/questions/36142393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5255941/"
] | You have a typo in the iframe rule - that might be the cause, since the absolute positioning won't work as expected:
```
iframe{
...
possition: absolute; ---> must be "position"
}
``` | You have position spelled wrong in your CSS. |
58,724,581 | Below is my playbook which has a variable `running_processes` which contains a list of pids(one or more)
Next, I read the user ids for each of the pids. All good so far.
I then try to print the list of user ids in `curr_user_ids` variable using `-debug module` is when i get the error: 'dict object' has no attribute '... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58724581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11143113/"
] | Few points to note why your solution didn't work.
The task `Get running processes list from remote host` returns a newline splitted `\n` string. So you will need to process this and turn the output into a propper list object first.
The task `Gather USER IDs from processes id before killing.` is returning a dictionary... | The variable *curr\_user\_ids* registers results of each iteration
```
register: curr_user_ids
with_items: "{{ running_processes.stdout_lines }}"
```
The list of the results is stored in
```
curr_user_ids.results
```
Take a look at the variable
```
- debug:
var: curr_user_ids
```
and loop the stdout\_lines... |
29,634,019 | I'm not sure what I'm doing wrong here, and am hoping someone else has the same problem. I don't get any error, and my json matches what should be correct both on Jira's docs and jira-python questions online. My versions are valid Jira versions. I also have no problem doing this directly through the API, but we are re-... | 2015/04/14 | [
"https://Stackoverflow.com/questions/29634019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797963/"
] | Here's a code example of how I got it working for anyone who comes across this later...
```
fixVersions = []
issue = jira.issue('issue_key')
for version in issue.fields.fixVersions:
if version.name != 'version_to_remove':
fixVersions.append({'name': version.name})
fixVersions.append... | I did it other way:
1. Create version in the target project.
2. Update ticket.
ver = jira.create\_version(name='version\_name', project='PROJECT\_NAME')
issue = jira.issue('ISSUE\_NUM')
i.update(fields={'fixVersions': [{'name': ver.name}]})}
In my case that worked. |
29,634,019 | I'm not sure what I'm doing wrong here, and am hoping someone else has the same problem. I don't get any error, and my json matches what should be correct both on Jira's docs and jira-python questions online. My versions are valid Jira versions. I also have no problem doing this directly through the API, but we are re-... | 2015/04/14 | [
"https://Stackoverflow.com/questions/29634019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797963/"
] | Here's a code example of how I got it working for anyone who comes across this later...
```
fixVersions = []
issue = jira.issue('issue_key')
for version in issue.fields.fixVersions:
if version.name != 'version_to_remove':
fixVersions.append({'name': version.name})
fixVersions.append... | A little bit more pythonic version of user797963 solution, may look like that.
```
def change_fix_version(tickets, remove_versions=[], add_versions=[]):
fix_versions={version.name for version in ticket.fields.fixVersions}
fix_versions.difference_update(set(remove_versions))
fix_versions.update(set(add_vers... |
29,634,019 | I'm not sure what I'm doing wrong here, and am hoping someone else has the same problem. I don't get any error, and my json matches what should be correct both on Jira's docs and jira-python questions online. My versions are valid Jira versions. I also have no problem doing this directly through the API, but we are re-... | 2015/04/14 | [
"https://Stackoverflow.com/questions/29634019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797963/"
] | I did it other way:
1. Create version in the target project.
2. Update ticket.
ver = jira.create\_version(name='version\_name', project='PROJECT\_NAME')
issue = jira.issue('ISSUE\_NUM')
i.update(fields={'fixVersions': [{'name': ver.name}]})}
In my case that worked. | A little bit more pythonic version of user797963 solution, may look like that.
```
def change_fix_version(tickets, remove_versions=[], add_versions=[]):
fix_versions={version.name for version in ticket.fields.fixVersions}
fix_versions.difference_update(set(remove_versions))
fix_versions.update(set(add_vers... |
16,209,640 | Here is strange issue I'm facing with wxpython on Mac. Though this works completely fine with wxpython on Windows7. I'm trying to update wx.StaticText label before and after time.sleep() like this:
```
self.lblStatus = wx.StaticText(self, label="", pos=(180, 80))
self.lblStatus.SetLabel("Processing....")
time.sleep(10... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16209640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1324914/"
] | I have never seen time.sleep() NOT block the GUI on Windows. The sleep function blocks wx's main loop, plain and simple. As JHolta mentioned, you can put the sleep into a thread and update the GUI from there, assuming you use a threadsafe method, such as wx.CallAfter, wx.CallLater or wx.PostEvent.
But if you just want... | The wxPython gui is a loop, to make a part of the code sleep without causing the gui to sleep one would need to multithread.
I would write a function that calls a threaded function, now this is a dirty example but should show you what needs to be done:
```
import wx
from threading import Thread
import time
from wx.li... |
39,024,816 | ```
#####################################
# Portscan TCP #
# #
#####################################
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket
ip = input("Digite o IP ou endereco: ")
ports = []
count = 0
while count < 10:
ports.append(int(input("Digite a porta: ")))
count += 1
for por... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39024816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6693417/"
] | As @Upsampled mentioned, you might use raw sockets (<https://en.wikipedia.org/>) as you only need a subset of TCP protocol (send **SYN** and recieve **RST-ACK** or **SYN-ACK**
).
As coding something like <http://www.binarytides.com/raw-socket-programming-in-python-linux/>
could be a good excersice, I would also sugges... | First, you will have to generate your own SYN packets using RAW sockets. You can find an example [here](http://www.binarytides.com/raw-socket-programming-in-python-linux/)
Second, you will need to listen for SYN-ACKs from the scanned host in order to determine which ports actually try to start the TCP Handshake (SYN,S... |
59,159,462 | I want to find the largest value in a JSON file, using python (so it would be a dictionary).
My JSON has this shape:
```
[{
"probability": 0.623514056,
"boundingBox": { "left": 36, "top": 1, "width": 403, "height": 95 }
},
{
"probability": 0.850905955,
"boundingBox": { "left": 42, "top": 200, "width": 412, "he... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59159462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11476888/"
] | The cleanest solution is probably:
```
widths = [d['boundingBox']['width'] for d in json_file]
min_value = min(widths)
max_value = max(widths)
```
However, `min` and `max` just use loops under the hood, which you mentioned may be slow. Test the above solution first, and if that is too slow for your needs, you can co... | That's fairly easy to do:
```
max_width = max(d["boundingBox"]["width"] for d in dicts)
min_width = min(d["boundingBox"]["height"] for d in dicts)
``` |
59,159,462 | I want to find the largest value in a JSON file, using python (so it would be a dictionary).
My JSON has this shape:
```
[{
"probability": 0.623514056,
"boundingBox": { "left": 36, "top": 1, "width": 403, "height": 95 }
},
{
"probability": 0.850905955,
"boundingBox": { "left": 42, "top": 200, "width": 412, "he... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59159462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11476888/"
] | That's fairly easy to do:
```
max_width = max(d["boundingBox"]["width"] for d in dicts)
min_width = min(d["boundingBox"]["height"] for d in dicts)
``` | I would use a lambda function
```
max(data, key=lambda d: d['boundingBox']['width'])
min(data, key=lambda d: d['boundingBox']['width'])
``` |
59,159,462 | I want to find the largest value in a JSON file, using python (so it would be a dictionary).
My JSON has this shape:
```
[{
"probability": 0.623514056,
"boundingBox": { "left": 36, "top": 1, "width": 403, "height": 95 }
},
{
"probability": 0.850905955,
"boundingBox": { "left": 42, "top": 200, "width": 412, "he... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59159462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11476888/"
] | The cleanest solution is probably:
```
widths = [d['boundingBox']['width'] for d in json_file]
min_value = min(widths)
max_value = max(widths)
```
However, `min` and `max` just use loops under the hood, which you mentioned may be slow. Test the above solution first, and if that is too slow for your needs, you can co... | I would use a lambda function
```
max(data, key=lambda d: d['boundingBox']['width'])
min(data, key=lambda d: d['boundingBox']['width'])
``` |
25,060,752 | Okay I got a file container that is a product of a Webcrawler containing a lot of different file types, likely but not all are HTML XML JPG PNG PDF. Most of the container is HTML text so I tried to open it with:
```
with open(fname) as f:
content = f.readlines()
```
which basically fails when I hit a PDF. The fi... | 2014/07/31 | [
"https://Stackoverflow.com/questions/25060752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3749379/"
] | You can [retrieve changes](http://msdn.microsoft.com/en-us/library/thc1eetk.aspx) in a `DataTable` using `GetChanges`.
So you can use this code with a `DataGridView`:
```
CType(YourDataGridView.DataSource, DataTable).GetChanges(DataRowState.Modified).Rows
``` | I have come up with a working solution in C# where I account for a user editing the current cell then performing a Save/Update without moving out of the edited row. The call to `GetChanges()` won't recognize the current edited row due to its `RowState` still being marked as "`Unchanged`". I also make a call to move to ... |
25,060,752 | Okay I got a file container that is a product of a Webcrawler containing a lot of different file types, likely but not all are HTML XML JPG PNG PDF. Most of the container is HTML text so I tried to open it with:
```
with open(fname) as f:
content = f.readlines()
```
which basically fails when I hit a PDF. The fi... | 2014/07/31 | [
"https://Stackoverflow.com/questions/25060752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3749379/"
] | You can [retrieve changes](http://msdn.microsoft.com/en-us/library/thc1eetk.aspx) in a `DataTable` using `GetChanges`.
So you can use this code with a `DataGridView`:
```
CType(YourDataGridView.DataSource, DataTable).GetChanges(DataRowState.Modified).Rows
``` | Here is a simple way to get all rows which have been modified in a DataGridView using C#:
```
DataRowCollection modifiedRows = ((DataTable)YourGridView.DataSource).GetChanges(DataRowState.Modified).Rows;
``` |
25,060,752 | Okay I got a file container that is a product of a Webcrawler containing a lot of different file types, likely but not all are HTML XML JPG PNG PDF. Most of the container is HTML text so I tried to open it with:
```
with open(fname) as f:
content = f.readlines()
```
which basically fails when I hit a PDF. The fi... | 2014/07/31 | [
"https://Stackoverflow.com/questions/25060752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3749379/"
] | I have come up with a working solution in C# where I account for a user editing the current cell then performing a Save/Update without moving out of the edited row. The call to `GetChanges()` won't recognize the current edited row due to its `RowState` still being marked as "`Unchanged`". I also make a call to move to ... | Here is a simple way to get all rows which have been modified in a DataGridView using C#:
```
DataRowCollection modifiedRows = ((DataTable)YourGridView.DataSource).GetChanges(DataRowState.Modified).Rows;
``` |
13,452,761 | i have a table with add/remove buttons, those buttons add and remove rows from the table, the buttons are also added with each new row
here what i have as html
```
<table>
<tr>
<th>catalogue</th>
<th>date</th>
<th>add</th>
<th>remove</th>
</tr>
<- target row ->
<tr id="cat_row">
<td>something</td>
<... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13452761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747201/"
] | **SOLVED**
Because my service was running in separate process i had to add this flag when accesing shared preference
```
private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;
```
and change like this
```
sharedPrefs = this.getSharedPreferences("preference name", PREFERENCES_MODE);
``` | Ensure you write your data to shared preferences correctly, specifically you `commit()` your changes, [as docs say](http://developer.android.com/reference/android/content/SharedPreferences.Editor.html):
>
> All changes you make in an editor are batched, and not copied back to
> the original SharedPreferences until y... |
13,452,761 | i have a table with add/remove buttons, those buttons add and remove rows from the table, the buttons are also added with each new row
here what i have as html
```
<table>
<tr>
<th>catalogue</th>
<th>date</th>
<th>add</th>
<th>remove</th>
</tr>
<- target row ->
<tr id="cat_row">
<td>something</td>
<... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13452761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747201/"
] | **SOLVED**
Because my service was running in separate process i had to add this flag when accesing shared preference
```
private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;
```
and change like this
```
sharedPrefs = this.getSharedPreferences("preference name", PREFERENCES_MODE);
``` | I think the error is on the line
```
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
```
where you are passing 'this' from inside a thread? Can you change it with the application context? |
16,844,182 | This is my first time delving into web development in python. My only other experience is PHP, and I never used a framework before, so I'm finding this very intimidating and confusing.
I'm interested in learning CherryPy/Jinja2 to make a ZFS Monitor for my NAS. I've read through the basics of the docs on CherryPy/Jinj... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16844182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2437919/"
] | Congratulations on choosing Python, I'm sure you'll learn to love it as have I.
Regarding CherryPy, I'm not an expert, but was also in the same boat as you a few days ago and I'd agree that the tutorials are a little disjointed in parts.
For integrating Jinja2, as in their [doc page](http://docs.cherrypy.org/stable/p... | Application structure
=====================
First about standard directory structure of a project. There is none, as CherryPy doesn't mandate it, neither it tells you what data layer, form validation or template engine to use. It's all up to you and your requirements. And of course as this is a great flexibility as it... |
39,971,929 | Python 3.6 is about to be released. [PEP 494 -- Python 3.6 Release Schedule](https://www.python.org/dev/peps/pep-0494/) mentions the end of December, so I went through [What's New in Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html) to see they mention the *variable annotations*:
>
> [PEP 484](https://www.py... | 2016/10/11 | [
"https://Stackoverflow.com/questions/39971929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983854/"
] | Everything between `:` and the `=` is a type hint, so `primes` is indeed defined as `List[int]`, and initially set to an empty list (and `stats` is an empty dictionary initially, defined as `Dict[str, int]`).
`List[int]` and `Dict[str, int]` are not part of the next syntax however, these were already defined in the Py... | >
> *What are variable annotations?*
>
>
>
Variable annotations are just the next step from `# type` comments, as they were defined in `PEP 484`; the rationale behind this change is highlighted in the [respective section of PEP 526](https://www.python.org/dev/peps/pep-0526/#rationale).
So, instead of hinting the... |
6,943,172 | What does the [] mean?
Also how can I identify variables as empty arrays in python?
Thanks!
```
perl: xcoords = ()
```
How do I translate that? | 2011/08/04 | [
"https://Stackoverflow.com/questions/6943172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | [] - is an empty list in Python and is the same as calling list() e.g. [] == list()
To check that list is empty you can use len(l) or:
```
listV = [] # an empty list
if listV:
# do something if list is not empty
else:
# do something if list is really empty
```
To read more about list you can use [the followi... | Lists are like C++ arrays with some difference. One of difference is they can cary different types even lists. to check if lists is empty
```
lists = []
len(lists)
lists[0]= "More of me"
len(lists)
```
More check [Python official](http://docs.python.org/tutorial/introduction.html#lists) tutorial and above Docs |
62,763,634 | I currently have a dictionary that I have imported from a csv file, that I have converted into a list of variables. The original dictionary looks like this:
* server01, server01.fqdn:port
* server02, server02.fqdn:port
* server03, server03.fqdn:port
* server04, server04.fqdn:port
What I'd like to do is create another... | 2020/07/06 | [
"https://Stackoverflow.com/questions/62763634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13795713/"
] | The [`format`](https://trino.io/docs/current/functions/conversion.html#format) function accepts any of the Java [format string specifiers](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax):
```
presto> select format('%.2f%%', 0.18932 * 100);
_col0
--------
18.93%
(1 row)
``` | For those of you who, like me, came here looking to round a `decimal` or `double` field down to `n` decimal places but didn't care about the `%` sign, you have a few other options than Martin's answer.
If you want the output to be type `double` then [`truncate(x,n)`](https://prestodb.io/docs/current/functions/math.htm... |
71,293,767 | I need to get the value from one element using several others as filters using Selenium on a dynamic website ([LogTrail](https://github.com/sivasamyk/logtrail) using [Kibana](https://en.wikipedia.org/wiki/Kibana)).
I got this:
```python
from selenium import webdriver
import time
from selenium.webdriver.common.keys im... | 2022/02/28 | [
"https://Stackoverflow.com/questions/71293767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17914605/"
] | Given a dataframe with a `DatetimeIndex` which doesn't have any missing days like this
```
df = pd.DataFrame(
{"A": range(500)}, index=pd.date_range("2022-03-01", periods=500, freq="1D")
)
A
2022-03-01 0
2022-03-02 1
... ...
2023-07-12 498
2023-07-13 499
```
you could do the follow... | We can use [`relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html), [`pandas.to_datetime`](https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html) and [`pandas.DataFrame.apply`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html).
```
from dateutil.relativede... |
15,136,456 | I want to parse dxf file for obtain objects (line, point, text and so on) with dxfgrabber library.
The code is as below
```
#!/usr/bin/env python
import dxfgrabber
dxf = dxfgrabber.readfile("1.dxf")
print ("DXF version : {}".format(dxf.dxfversion))
```
But it gets some error...
```
Traceback (most recent call las... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15136456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1761178/"
] | I contacted the developer and he says that in current version 0.5.1 make line 49 of `__init__.py` the following: `with io.open(filename) as fp:`.
Then it works (`io` was missing).
He will make this correction official in version 0.5.2 soon. | You can only read dxf made in AutoCAD format!
Try "DraftSight" which is a free AutoCAD clone which exports dxf quite well. Try dxf R12 format.
This will solve your problems. |
35,737,178 | Thanks in advance for the help.
I'm relatively new to python and am trying to write a python script to load partial csv files from 1000 files. For example, I have 1000 files that have this format
```
x,y
1,2
2,4
2,2
3,9
...
```
I would like to load only lines, for example, where `x=2`. I've seen a lot of posts on h... | 2016/03/02 | [
"https://Stackoverflow.com/questions/35737178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2736423/"
] | Try [pandas](https://github.com/pydata/pandas) library. It has an interoperability with numpy and way more flexible. With this library you do next thing:
```py
data = pandas.read_csv('file.csv')
# keep only rows with x equals to 2
data = data[data['x'] == 2]
# convert to numpy array
arr = numpy.asarray(data)
```
Yo... | The csv library comes with python and it allows for partial reading of a file.
```
import csv
def partial_load(filename):
ds = []
c = csv.reader( open(filename) )
legend = next( c )
for row in c:
row = [float(r) for r in row]
if len(row) > 0:
if row[0] > 2:
... |
17,406,453 | I have started a month ago with GAE and have successfully deployed our current startup via Flask on GAE. It works fantastically well. Now being all too exited about GAE, I am thinking about porting a couple of my older Django apps on GAE as well.
To my surprise the documentation of it is surprisingly inconsistent and ... | 2013/07/01 | [
"https://Stackoverflow.com/questions/17406453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92153/"
] | you can easily use `@request.getHeader("referer")` in your Templates, for example if you have a cancel button that should redirect you to the previous page, use this :
```
<a href="@request.getHeader("referer")">Cancel</a>
```
in this way, you don't need to pass any extra information to your templates. (tested with... | This is what I came up with in the end, although it isn't particularly elegant, and I'd be interested in better ways of doing it. I added a hidden input to my form with the current page URL:
```
@(implicit request: RequestHeader)
...
<form action="@routes.Controller.doStuff()" method="post">
<input type="hidden" n... |
17,406,453 | I have started a month ago with GAE and have successfully deployed our current startup via Flask on GAE. It works fantastically well. Now being all too exited about GAE, I am thinking about porting a couple of my older Django apps on GAE as well.
To my surprise the documentation of it is surprisingly inconsistent and ... | 2013/07/01 | [
"https://Stackoverflow.com/questions/17406453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92153/"
] | This is what I came up with in the end, although it isn't particularly elegant, and I'd be interested in better ways of doing it. I added a hidden input to my form with the current page URL:
```
@(implicit request: RequestHeader)
...
<form action="@routes.Controller.doStuff()" method="post">
<input type="hidden" n... | The easiest way I've found to do this, is from within your controller method, use this:
```
String refererUrl = request().getHeader("referer");
```
So, you'd do something like:
```
public static Result query(String queryStr, int page, int offset) {
String refererUrl = request().getHeader("referer");
Logge... |
17,406,453 | I have started a month ago with GAE and have successfully deployed our current startup via Flask on GAE. It works fantastically well. Now being all too exited about GAE, I am thinking about porting a couple of my older Django apps on GAE as well.
To my surprise the documentation of it is surprisingly inconsistent and ... | 2013/07/01 | [
"https://Stackoverflow.com/questions/17406453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92153/"
] | you can easily use `@request.getHeader("referer")` in your Templates, for example if you have a cancel button that should redirect you to the previous page, use this :
```
<a href="@request.getHeader("referer")">Cancel</a>
```
in this way, you don't need to pass any extra information to your templates. (tested with... | The easiest way I've found to do this, is from within your controller method, use this:
```
String refererUrl = request().getHeader("referer");
```
So, you'd do something like:
```
public static Result query(String queryStr, int page, int offset) {
String refererUrl = request().getHeader("referer");
Logge... |
43,852,802 | Python 3.6
I have a program that is generating a list of dictionaries.
If I print it to the screen with:
```
print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
```
It prints out exactly as I want to see it:
```
[
{
"runts": 0,
"giants": 0,
"throttles": 0,
... | 2017/05/08 | [
"https://Stackoverflow.com/questions/43852802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7535419/"
] | I think all you need is `json.dump` with `indent` and it should be fine:
```
outputfile = ("d:\\mark\\python\\Projects\\error_detect\\" + hostname)
# print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# output_lines.append(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# del output_lines[-1... | Try simply outputting the formatted `json.dumps`, rather than running it through `json.dump` again.
```
with open(outputfile, 'w') as f:
f.write(output_lines)
``` |
43,852,802 | Python 3.6
I have a program that is generating a list of dictionaries.
If I print it to the screen with:
```
print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
```
It prints out exactly as I want to see it:
```
[
{
"runts": 0,
"giants": 0,
"throttles": 0,
... | 2017/05/08 | [
"https://Stackoverflow.com/questions/43852802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7535419/"
] | Try simply outputting the formatted `json.dumps`, rather than running it through `json.dump` again.
```
with open(outputfile, 'w') as f:
f.write(output_lines)
``` | Say your program generates this list of dictionaries
```
>>> list_of_dicts = [dict(zip(list(range(2)),list(range(2)))), dict(zip(list(range(2)),list(range(2))))]
>>> list_of_dicts
[{0: 0, 1: 1}, {0: 0, 1: 1}]
```
What you can do is
```
>>> import json
>>> str_object = json.dumps(list_of_dicts, indent=4)
>>> repr(st... |
43,852,802 | Python 3.6
I have a program that is generating a list of dictionaries.
If I print it to the screen with:
```
print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
```
It prints out exactly as I want to see it:
```
[
{
"runts": 0,
"giants": 0,
"throttles": 0,
... | 2017/05/08 | [
"https://Stackoverflow.com/questions/43852802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7535419/"
] | I think all you need is `json.dump` with `indent` and it should be fine:
```
outputfile = ("d:\\mark\\python\\Projects\\error_detect\\" + hostname)
# print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# output_lines.append(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# del output_lines[-1... | Say your program generates this list of dictionaries
```
>>> list_of_dicts = [dict(zip(list(range(2)),list(range(2)))), dict(zip(list(range(2)),list(range(2))))]
>>> list_of_dicts
[{0: 0, 1: 1}, {0: 0, 1: 1}]
```
What you can do is
```
>>> import json
>>> str_object = json.dumps(list_of_dicts, indent=4)
>>> repr(st... |
8,461,306 | I'm tracking a linux filesystem (that could be any type) with pyinotify module for python (which is actually the linux kernel behind doing the job). Many directories/folders/files (as much as the user want to) are being tracked with my application and now i would like track the md5sum of each file and store them on a d... | 2011/12/11 | [
"https://Stackoverflow.com/questions/8461306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952870/"
] | You could use this:
```
string q = Regex.Replace(query, @"[:#/\\]", ".");
q = Regex.Replace(q, @""|['"",&?%\.*-]", " ");
```
EDIT:
=====
On closer inspection of what you're doing, your code is translating several characters into `.`, and *then* translating all `.` into spaces. So you could just do this:
```
s... | Try this.
```
string pattern = @"[^a-zA-Z0-9]";
string test = Regex.Replace("abc*&34567*opdldld(aododod';", pattern, " ");
``` |
11,191,946 | I have spent many hours trying to build RDKit on ubuntu 11.10 for
Python 2.7 (rdkit\_201106+dfsg.orig.tar.gz) using a precompiled version
of boost 1.49. And I am failing miserably.
The recurring error is in the CMake GUI:
```
CMake Error at CMakeLists.txt:11 (install):
install FILES given no DESTINATION!
CMake... | 2012/06/25 | [
"https://Stackoverflow.com/questions/11191946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395874/"
] | make sure you have the environment variables set:
(you might need to fix the paths with what you have): using bash on mac:
```
export RDBASE=/usr/local/share/RDKit
export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages
```
you might want to add those lines to a bash script to automate the process. | For Ubuntu 12.04.2 LTS setting this environment variables works for me
```
export RDBASE=/usr/share/RDKit
export PYTHONPATH=$PYTHONPATH:/usr/lib/pymodules/python2.7
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.