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
|
|---|---|---|---|---|---|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
Can't you just write a function mapping to each? In fact, a dictionary will do.
```
def convert_monthname(monthname):
table = {"January": datetime.datetime(month=1, day=1, year=2018),
"February": datetime.datetime(month=2, day=1, year=2018),
...}
return table.get(monthname, monthname)
f['Month'] = f['Month'].apply(convert_monthname)
```
|
The whole point of passing a format string like `%m/%d/%y` to `strftime` is that you're specifying what format the input strings are going to be in.
You can see [the documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), but it's pretty obvious that a format like `%m/%d/%y` is not going to handle strings like `'October'`. You're asking for a (zero-padded) month number, a slash, a (zero-padded) day number, a slash, and a (zero-padded) (two-digit) years.
If you specify a format that actually *does* match your input, everything works without error:
```
>>> datetime.datetime.strptime('October', '%B')
datetime.datetime(1900, 10, 1, 0, 0)
```
However, that still isn't what you want, because the default year is 1900, not 2018. So, you either need to [`replace`](https://docs.python.org/3/library/datetime.html#datetime.datetime.replace) that, or pull the month out and build a new datetime object.
```
>>> datetime.datetime.strptime('October', '%B').replace(year=2018)
datetime.datetime(2018, 10, 1, 0, 0)
```
Also, notice that all of the strings that `strptime` knows about are locale-specific. If you've set an English-speaking locale, like `en_US.UTF-8`, or `C`, then `%B` means the English months, so everything is great. But if you've set, say, `br_PT.UTF-8`, then you're asking it to match the Brazilian Portuguese month names, like `Outubro` instead of `October`.1
---
1. Since I don't actually know Brazilian Portuguese, that was a pretty dumb example for me to pick… but Google says it's Outubro, and when Google Translate did so ever lead wrong one?
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
Can't you just write a function mapping to each? In fact, a dictionary will do.
```
def convert_monthname(monthname):
table = {"January": datetime.datetime(month=1, day=1, year=2018),
"February": datetime.datetime(month=2, day=1, year=2018),
...}
return table.get(monthname, monthname)
f['Month'] = f['Month'].apply(convert_monthname)
```
|
I'm assuming the data is mostly in the format you have specified (`mm/dd/yyyy`) but some outlier rows have month names in them.
Without adding any extra dependencies:
```
DATE_FORMAT = '%m/%d/Y'
MONTH_NAME_MAP = {
"january": 1,
"jan": 1,
"february": 2,
"feb": 2,
# ...
}
def parse_month_value(value):
# check if the value is a name of a month
month_int = MONTH_NAME_MAP.get(value.lower())
if month_int:
this_year = datetime.date.today().year
return datetime.datetime(month=month_int, day=1, year=this_year)
# try to parse it normally, failing and raising exception if needed.
return datetime.datetime.strptime(value, DATE_FORMAT)
```
---
then
```
f['Month'] = f['Month'].apply(parse_month_value)
```
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
Can't you just write a function mapping to each? In fact, a dictionary will do.
```
def convert_monthname(monthname):
table = {"January": datetime.datetime(month=1, day=1, year=2018),
"February": datetime.datetime(month=2, day=1, year=2018),
...}
return table.get(monthname, monthname)
f['Month'] = f['Month'].apply(convert_monthname)
```
|
The answer from @DYZ actually did it for me, I added the strftime to create the dict as the date string I wanted
```
months = {str(name).lower(): datetime.datetime(month=val, day=1, year=2016).strftime('%d/%m/%Y')
for val, name in enumerate(calendar.month_abbr) if val>0}
```
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
As an elaboration of the answer by @AdamSmith, a better way to define a mapping between names and dates is to use the `calendar` module that already has a list of names:
```
import calendar
table = {name: datetime.datetime(month=1, day=val, year=2018)
for val, name in enumerate(calendar.month_name) if val>0}
```
|
The whole point of passing a format string like `%m/%d/%y` to `strftime` is that you're specifying what format the input strings are going to be in.
You can see [the documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), but it's pretty obvious that a format like `%m/%d/%y` is not going to handle strings like `'October'`. You're asking for a (zero-padded) month number, a slash, a (zero-padded) day number, a slash, and a (zero-padded) (two-digit) years.
If you specify a format that actually *does* match your input, everything works without error:
```
>>> datetime.datetime.strptime('October', '%B')
datetime.datetime(1900, 10, 1, 0, 0)
```
However, that still isn't what you want, because the default year is 1900, not 2018. So, you either need to [`replace`](https://docs.python.org/3/library/datetime.html#datetime.datetime.replace) that, or pull the month out and build a new datetime object.
```
>>> datetime.datetime.strptime('October', '%B').replace(year=2018)
datetime.datetime(2018, 10, 1, 0, 0)
```
Also, notice that all of the strings that `strptime` knows about are locale-specific. If you've set an English-speaking locale, like `en_US.UTF-8`, or `C`, then `%B` means the English months, so everything is great. But if you've set, say, `br_PT.UTF-8`, then you're asking it to match the Brazilian Portuguese month names, like `Outubro` instead of `October`.1
---
1. Since I don't actually know Brazilian Portuguese, that was a pretty dumb example for me to pick… but Google says it's Outubro, and when Google Translate did so ever lead wrong one?
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
As an elaboration of the answer by @AdamSmith, a better way to define a mapping between names and dates is to use the `calendar` module that already has a list of names:
```
import calendar
table = {name: datetime.datetime(month=1, day=val, year=2018)
for val, name in enumerate(calendar.month_name) if val>0}
```
|
I'm assuming the data is mostly in the format you have specified (`mm/dd/yyyy`) but some outlier rows have month names in them.
Without adding any extra dependencies:
```
DATE_FORMAT = '%m/%d/Y'
MONTH_NAME_MAP = {
"january": 1,
"jan": 1,
"february": 2,
"feb": 2,
# ...
}
def parse_month_value(value):
# check if the value is a name of a month
month_int = MONTH_NAME_MAP.get(value.lower())
if month_int:
this_year = datetime.date.today().year
return datetime.datetime(month=month_int, day=1, year=this_year)
# try to parse it normally, failing and raising exception if needed.
return datetime.datetime.strptime(value, DATE_FORMAT)
```
---
then
```
f['Month'] = f['Month'].apply(parse_month_value)
```
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
As an elaboration of the answer by @AdamSmith, a better way to define a mapping between names and dates is to use the `calendar` module that already has a list of names:
```
import calendar
table = {name: datetime.datetime(month=1, day=val, year=2018)
for val, name in enumerate(calendar.month_name) if val>0}
```
|
The answer from @DYZ actually did it for me, I added the strftime to create the dict as the date string I wanted
```
months = {str(name).lower(): datetime.datetime(month=val, day=1, year=2016).strftime('%d/%m/%Y')
for val, name in enumerate(calendar.month_abbr) if val>0}
```
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
The whole point of passing a format string like `%m/%d/%y` to `strftime` is that you're specifying what format the input strings are going to be in.
You can see [the documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), but it's pretty obvious that a format like `%m/%d/%y` is not going to handle strings like `'October'`. You're asking for a (zero-padded) month number, a slash, a (zero-padded) day number, a slash, and a (zero-padded) (two-digit) years.
If you specify a format that actually *does* match your input, everything works without error:
```
>>> datetime.datetime.strptime('October', '%B')
datetime.datetime(1900, 10, 1, 0, 0)
```
However, that still isn't what you want, because the default year is 1900, not 2018. So, you either need to [`replace`](https://docs.python.org/3/library/datetime.html#datetime.datetime.replace) that, or pull the month out and build a new datetime object.
```
>>> datetime.datetime.strptime('October', '%B').replace(year=2018)
datetime.datetime(2018, 10, 1, 0, 0)
```
Also, notice that all of the strings that `strptime` knows about are locale-specific. If you've set an English-speaking locale, like `en_US.UTF-8`, or `C`, then `%B` means the English months, so everything is great. But if you've set, say, `br_PT.UTF-8`, then you're asking it to match the Brazilian Portuguese month names, like `Outubro` instead of `October`.1
---
1. Since I don't actually know Brazilian Portuguese, that was a pretty dumb example for me to pick… but Google says it's Outubro, and when Google Translate did so ever lead wrong one?
|
I'm assuming the data is mostly in the format you have specified (`mm/dd/yyyy`) but some outlier rows have month names in them.
Without adding any extra dependencies:
```
DATE_FORMAT = '%m/%d/Y'
MONTH_NAME_MAP = {
"january": 1,
"jan": 1,
"february": 2,
"feb": 2,
# ...
}
def parse_month_value(value):
# check if the value is a name of a month
month_int = MONTH_NAME_MAP.get(value.lower())
if month_int:
this_year = datetime.date.today().year
return datetime.datetime(month=month_int, day=1, year=this_year)
# try to parse it normally, failing and raising exception if needed.
return datetime.datetime.strptime(value, DATE_FORMAT)
```
---
then
```
f['Month'] = f['Month'].apply(parse_month_value)
```
|
51,976,580
|
I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', index_col=None)
keep_col = ['Month']
new_f = f[keep_col]
f['Month'] = f['Month'].apply(lambda v: datetime.datetime.strptime(v, '%m/%d/%Y'))
new_f.to_csv("output.csv", index=False)
```
Any help would be appreciated
|
2018/08/22
|
[
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] |
The whole point of passing a format string like `%m/%d/%y` to `strftime` is that you're specifying what format the input strings are going to be in.
You can see [the documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), but it's pretty obvious that a format like `%m/%d/%y` is not going to handle strings like `'October'`. You're asking for a (zero-padded) month number, a slash, a (zero-padded) day number, a slash, and a (zero-padded) (two-digit) years.
If you specify a format that actually *does* match your input, everything works without error:
```
>>> datetime.datetime.strptime('October', '%B')
datetime.datetime(1900, 10, 1, 0, 0)
```
However, that still isn't what you want, because the default year is 1900, not 2018. So, you either need to [`replace`](https://docs.python.org/3/library/datetime.html#datetime.datetime.replace) that, or pull the month out and build a new datetime object.
```
>>> datetime.datetime.strptime('October', '%B').replace(year=2018)
datetime.datetime(2018, 10, 1, 0, 0)
```
Also, notice that all of the strings that `strptime` knows about are locale-specific. If you've set an English-speaking locale, like `en_US.UTF-8`, or `C`, then `%B` means the English months, so everything is great. But if you've set, say, `br_PT.UTF-8`, then you're asking it to match the Brazilian Portuguese month names, like `Outubro` instead of `October`.1
---
1. Since I don't actually know Brazilian Portuguese, that was a pretty dumb example for me to pick… but Google says it's Outubro, and when Google Translate did so ever lead wrong one?
|
The answer from @DYZ actually did it for me, I added the strftime to create the dict as the date string I wanted
```
months = {str(name).lower(): datetime.datetime(month=val, day=1, year=2016).strftime('%d/%m/%Y')
for val, name in enumerate(calendar.month_abbr) if val>0}
```
|
45,686,298
|
I have followed [official doc](https://learn.microsoft.com/en-us/visualstudio/python/debugging-cross-platform-remote) to install ptvsd 3.2.0, and put below code in the very beginning of target code.
```
import ptvsd
ptvsd.enable_attach('my_secret')
```
If run this code, I got error:
```
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/__init__.py", line 87, in enable_attach
return _attach_server().enable_attach(secret, address, certfile, keyfile, redirect_output)
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/__init__.py", line 31, in _attach_server
import ptvsd.attach_server
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/attach_server.py", line 40, in <module>
import ptvsd.debugger as vspd
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/debugger.py", line 49, in <module>
import ptvsd.repl as _vspr
```
ModuleNotFoundError: No module named 'ptvsd.repl'
|
2017/08/15
|
[
"https://Stackoverflow.com/questions/45686298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4198142/"
] |
I had the same problem today. I've checked the [last version](https://pypi.python.org/pypi/ptvsd/3.2.0) and was released yesterday. I've decided to roll back to version 3.1.0, and that is working fine for me.
I've reported the problem to the [gitter room](https://gitter.im/Microsoft/PTVS). I'll update this answer as soon as I get more information.
|
The `ptvsd` module is not using semantic versioning, which means you cannot safely update it whenever you like. The plan is to switch to semantic versioning when it is fully decoupled from Visual Studio.
`ptvsd==3.2.0` was released at the same time that Visual Studio 2017 Update 15.3 because they have dependencies on each other. If you also update Visual Studio then you should update to `ptvsd==3.2.0`. Otherwise, stay with an older version.
Currently Visual Studio Code requires `ptvsd<3`. It has not been updated for recent changes.
|
45,686,298
|
I have followed [official doc](https://learn.microsoft.com/en-us/visualstudio/python/debugging-cross-platform-remote) to install ptvsd 3.2.0, and put below code in the very beginning of target code.
```
import ptvsd
ptvsd.enable_attach('my_secret')
```
If run this code, I got error:
```
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/__init__.py", line 87, in enable_attach
return _attach_server().enable_attach(secret, address, certfile, keyfile, redirect_output)
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/__init__.py", line 31, in _attach_server
import ptvsd.attach_server
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/attach_server.py", line 40, in <module>
import ptvsd.debugger as vspd
File "~/.virtualenvs/py3/lib/python3.6/site-packages/ptvsd/debugger.py", line 49, in <module>
import ptvsd.repl as _vspr
```
ModuleNotFoundError: No module named 'ptvsd.repl'
|
2017/08/15
|
[
"https://Stackoverflow.com/questions/45686298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4198142/"
] |
I had the same problem today. I've checked the [last version](https://pypi.python.org/pypi/ptvsd/3.2.0) and was released yesterday. I've decided to roll back to version 3.1.0, and that is working fine for me.
I've reported the problem to the [gitter room](https://gitter.im/Microsoft/PTVS). I'll update this answer as soon as I get more information.
|
I've installed it globally by specifying certain python because my default python is 3.9 but for azure-functions I needed it installed in 3.8
`/Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8 -m pip install ptvsd`
Of course you must replace my python version with yours
But [***ptvsd***](https://github.com/microsoft/ptvsd) IS DEPRECATED and replaced with [***debugpy***](https://github.com/microsoft/debugpy)
|
65,046,032
|
I'm trying to create an .exe from my python script. The script uses the cloudscraper package. When I create the .exe and I execute it, it shows the following error:
```
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\...\\MEI1....\\cloudscraper\\user_agent\\browsers.json'
```
The error ONLY APPEARS WHEN I TRY TO EXECUTE THE .exe file.
Why is this happening? Is cloudscraper unavailable with pyinstaller?
The project structure looks like this:
```
C:\Users\andre\OneDrive\Documentos\Programming\Python\Python3\proyect
proyect
|
|______ main.py
|
|______ services
|________ __init__.py
|_______ main_service.py
|_______ sql_service.py
```
This is very similar to my project structure since obviously, I cannot share the actual project structure of my project.
|
2020/11/28
|
[
"https://Stackoverflow.com/questions/65046032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14134850/"
] |
The found solution is to copy the required folder inside the .exe path but as for now a days, **I found that this could not be achieved if you're using the** `--onefile` **modifier to create the .exe**, instead you should not use it and copy the cloudscraper folder inside such .exe path, and that should work
**NOTE:**
The path is **NOT THE PARENT FOLDER cloudscraper**, instead is the nested folder which in it has the `user_agent` folder
|
Your .exe file is looking for browsers.json, but you didn't move that file to the same path as the .exe file. Working with pyinstaller requires good experience handling relative and absolute paths, otherwise, you will face that kind of errors.
If cloudscraper is not part of your project tree (maybe is a hidden import):
1. Try copy the folder named 'cloudscrapper' from [here](https://github.com/VeNoMouS/cloudscraper) and paste it in the same path of your .exe file
|
65,046,032
|
I'm trying to create an .exe from my python script. The script uses the cloudscraper package. When I create the .exe and I execute it, it shows the following error:
```
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\...\\MEI1....\\cloudscraper\\user_agent\\browsers.json'
```
The error ONLY APPEARS WHEN I TRY TO EXECUTE THE .exe file.
Why is this happening? Is cloudscraper unavailable with pyinstaller?
The project structure looks like this:
```
C:\Users\andre\OneDrive\Documentos\Programming\Python\Python3\proyect
proyect
|
|______ main.py
|
|______ services
|________ __init__.py
|_______ main_service.py
|_______ sql_service.py
```
This is very similar to my project structure since obviously, I cannot share the actual project structure of my project.
|
2020/11/28
|
[
"https://Stackoverflow.com/questions/65046032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14134850/"
] |
Check this link: <https://stackoverflow.com/a/64586862/14509818>
**or**
Add this command while creating your exe.
```
--add-data "path_for_cloudscraper_folder;./cloudscraper/"
```
Replace ***path\_for\_cloudscraper\_folder*** with the path of your cloudscraper folder.
You can explore and find your path of cloudscraper folder from pc or dowload it from github.
Here ***./cloudscraper/*** is used to add cloudscraper folder in your root directory of output. (expecting that it is searching in root directory for missing cloudscraper folder)
|
Your .exe file is looking for browsers.json, but you didn't move that file to the same path as the .exe file. Working with pyinstaller requires good experience handling relative and absolute paths, otherwise, you will face that kind of errors.
If cloudscraper is not part of your project tree (maybe is a hidden import):
1. Try copy the folder named 'cloudscrapper' from [here](https://github.com/VeNoMouS/cloudscraper) and paste it in the same path of your .exe file
|
65,046,032
|
I'm trying to create an .exe from my python script. The script uses the cloudscraper package. When I create the .exe and I execute it, it shows the following error:
```
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\...\\MEI1....\\cloudscraper\\user_agent\\browsers.json'
```
The error ONLY APPEARS WHEN I TRY TO EXECUTE THE .exe file.
Why is this happening? Is cloudscraper unavailable with pyinstaller?
The project structure looks like this:
```
C:\Users\andre\OneDrive\Documentos\Programming\Python\Python3\proyect
proyect
|
|______ main.py
|
|______ services
|________ __init__.py
|_______ main_service.py
|_______ sql_service.py
```
This is very similar to my project structure since obviously, I cannot share the actual project structure of my project.
|
2020/11/28
|
[
"https://Stackoverflow.com/questions/65046032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14134850/"
] |
Check this link: <https://stackoverflow.com/a/64586862/14509818>
**or**
Add this command while creating your exe.
```
--add-data "path_for_cloudscraper_folder;./cloudscraper/"
```
Replace ***path\_for\_cloudscraper\_folder*** with the path of your cloudscraper folder.
You can explore and find your path of cloudscraper folder from pc or dowload it from github.
Here ***./cloudscraper/*** is used to add cloudscraper folder in your root directory of output. (expecting that it is searching in root directory for missing cloudscraper folder)
|
The found solution is to copy the required folder inside the .exe path but as for now a days, **I found that this could not be achieved if you're using the** `--onefile` **modifier to create the .exe**, instead you should not use it and copy the cloudscraper folder inside such .exe path, and that should work
**NOTE:**
The path is **NOT THE PARENT FOLDER cloudscraper**, instead is the nested folder which in it has the `user_agent` folder
|
60,609,578
|
I have two sets `set([1,2,3]` and `set([4,5,6]`. I want to add them in order to get set `1,2,3,4,5,6`.
I tried:
```
b = set([1,2,3]).add(set([4,5,6]))
```
but it gives me this error:
```
Traceback (most recent call last):
File "<ipython-input-27-d2646d891a38>", line 1, in <module>
b = set([1,2,3]).add(set([4,5,6]))
TypeError: unhashable type: 'set'
```
**Question:** How to correct my code?
|
2020/03/09
|
[
"https://Stackoverflow.com/questions/60609578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601703/"
] |
You can take the union of sets with `|`
```
> set([1, 2, 4]) | set([5, 6, 7])
{1, 2, 4, 5, 6, 7}
```
Trying to use `add(set([4,5,6]))` is not working because it tries to add the entire set as a single element rather than the elements in the set — and since it's not hashable, it fails.
|
You should use the union operation with the `.union` method or the `|` operator:
```py
>>> a = set([1, 2, 3])
>>> b = set([4, 5, 3])
>>> c = a.union(b)
>>> print(c)
{1, 2, 3, 4, 5}
>>> d = a | b
>>> print(d)
{1, 2, 3, 4, 5}
```
See the complete list of operations for [set](https://docs.python.org/3/library/stdtypes.html#set).
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
"If you have a problem, and decide to use regex, now you have two problems..."
If you are reading one particular web page and you know how it is formatted, then regex is fine - you can use S. Mark's answer. To parse a particular link, you can use Kimvai's answer. However, to get all the links from a page, you're better off using something more serious. Any regex solution you come up with will have flaws,
I recommend [mechanize](http://wwwsearch.sourceforge.net/mechanize/). If you notice, the `Browser` class there has a `links` method which gets you all the links in a page. It has the added benefit of being able to download the page for you =) .
|
This will work irrespective of how your links are formatted (e.g. if some look like `<a href="foo=123"/>` and some look like `<A TARGET="_blank" HREF='foo=123'/>`).
```
import re
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
p = re.compile('^.*=([\d]*)$')
for a in soup.findAll('a'):
m = p.match(a["href"])
if m:
print m.groups()[0]
```
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
import re
re.findall("\?read\.php=(\d+)",data)
```
|
This will work irrespective of how your links are formatted (e.g. if some look like `<a href="foo=123"/>` and some look like `<A TARGET="_blank" HREF='foo=123'/>`).
```
import re
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
p = re.compile('^.*=([\d]*)$')
for a in soup.findAll('a'):
m = p.match(a["href"])
if m:
print m.groups()[0]
```
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This will work irrespective of how your links are formatted (e.g. if some look like `<a href="foo=123"/>` and some look like `<A TARGET="_blank" HREF='foo=123'/>`).
```
import re
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
p = re.compile('^.*=([\d]*)$')
for a in soup.findAll('a'):
m = p.match(a["href"])
if m:
print m.groups()[0]
```
|
/[0-9]/
thats the regex sytax you want
for reference see
<http://gnosis.cx/publish/programming/regular_expressions.html>
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
While the other answers are sort of correct, you should probably use the urllib2 library instead;
```
from urllib2 import urlparse
import re
urlre = re.compile('<a[^>]+href="([^"]+)"[^>]*>',re.IGNORECASE)
links = urlre.findall('<a href="http://www.example.com?read.php=123">')
for link in links:
url = urlparse.urlparse(link)
s = [x.split("=") for x in url[4].split(';')]
d = {}
for k,v in s:
d[k]=v
print d["read.php"]
```
It's not as simple as some of the above, but guaranteed to work even with more complex urls.
|
/[0-9]/
thats the regex sytax you want
for reference see
<http://gnosis.cx/publish/programming/regular_expressions.html>
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This will work irrespective of how your links are formatted (e.g. if some look like `<a href="foo=123"/>` and some look like `<A TARGET="_blank" HREF='foo=123'/>`).
```
import re
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
p = re.compile('^.*=([\d]*)$')
for a in soup.findAll('a'):
m = p.match(a["href"])
if m:
print m.groups()[0]
```
|
One without the need for regex
```
>>> s='<a href="http://www.example.com?read.php=123">'
>>> for item in s.split(">"):
... if "href" in item:
... print item[item.index("a href")+len("a href="): ]
...
"http://www.example.com?read.php=123"
```
if you want to extract the numbers
```
item[item.index("a href")+len("a href="): ].split("=")[-1]
```
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
"If you have a problem, and decide to use regex, now you have two problems..."
If you are reading one particular web page and you know how it is formatted, then regex is fine - you can use S. Mark's answer. To parse a particular link, you can use Kimvai's answer. However, to get all the links from a page, you're better off using something more serious. Any regex solution you come up with will have flaws,
I recommend [mechanize](http://wwwsearch.sourceforge.net/mechanize/). If you notice, the `Browser` class there has a `links` method which gets you all the links in a page. It has the added benefit of being able to download the page for you =) .
|
One without the need for regex
```
>>> s='<a href="http://www.example.com?read.php=123">'
>>> for item in s.split(">"):
... if "href" in item:
... print item[item.index("a href")+len("a href="): ]
...
"http://www.example.com?read.php=123"
```
if you want to extract the numbers
```
item[item.index("a href")+len("a href="): ].split("=")[-1]
```
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
While the other answers are sort of correct, you should probably use the urllib2 library instead;
```
from urllib2 import urlparse
import re
urlre = re.compile('<a[^>]+href="([^"]+)"[^>]*>',re.IGNORECASE)
links = urlre.findall('<a href="http://www.example.com?read.php=123">')
for link in links:
url = urlparse.urlparse(link)
s = [x.split("=") for x in url[4].split(';')]
d = {}
for k,v in s:
d[k]=v
print d["read.php"]
```
It's not as simple as some of the above, but guaranteed to work even with more complex urls.
|
One without the need for regex
```
>>> s='<a href="http://www.example.com?read.php=123">'
>>> for item in s.split(">"):
... if "href" in item:
... print item[item.index("a href")+len("a href="): ]
...
"http://www.example.com?read.php=123"
```
if you want to extract the numbers
```
item[item.index("a href")+len("a href="): ].split("=")[-1]
```
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
"If you have a problem, and decide to use regex, now you have two problems..."
If you are reading one particular web page and you know how it is formatted, then regex is fine - you can use S. Mark's answer. To parse a particular link, you can use Kimvai's answer. However, to get all the links from a page, you're better off using something more serious. Any regex solution you come up with will have flaws,
I recommend [mechanize](http://wwwsearch.sourceforge.net/mechanize/). If you notice, the `Browser` class there has a `links` method which gets you all the links in a page. It has the added benefit of being able to download the page for you =) .
|
While the other answers are sort of correct, you should probably use the urllib2 library instead;
```
from urllib2 import urlparse
import re
urlre = re.compile('<a[^>]+href="([^"]+)"[^>]*>',re.IGNORECASE)
links = urlre.findall('<a href="http://www.example.com?read.php=123">')
for link in links:
url = urlparse.urlparse(link)
s = [x.split("=") for x in url[4].split(';')]
d = {}
for k,v in s:
d[k]=v
print d["read.php"]
```
It's not as simple as some of the above, but guaranteed to work even with more complex urls.
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
import re
re.findall("\?read\.php=(\d+)",data)
```
|
One without the need for regex
```
>>> s='<a href="http://www.example.com?read.php=123">'
>>> for item in s.split(">"):
... if "href" in item:
... print item[item.index("a href")+len("a href="): ]
...
"http://www.example.com?read.php=123"
```
if you want to extract the numbers
```
item[item.index("a href")+len("a href="): ].split("=")[-1]
```
|
1,899,412
|
I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
2009/12/14
|
[
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
import re
re.findall("\?read\.php=(\d+)",data)
```
|
/[0-9]/
thats the regex sytax you want
for reference see
<http://gnosis.cx/publish/programming/regular_expressions.html>
|
62,163,714
|
`which python` returns:
`/Library/Frameworks/Python.framework/Versions/2.7/bin/python`
When I open my shell, the first couple lines of the shell read:
`Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.`
And finally, the issue is that when I am in my shell and I try to import pandas (which is installed), I receive `no module named 'pandas'`. Which, according to [this article](https://github.com/pandas-dev/pandas/issues/11604), is due to having multiple installations of Python and running Python from the system.
The solution proposed by the aforementioned article is to use conda. But, will simply installing conda solve my issue of my shell returning something different from terminal? I am really new to programming so assume I don't know how any of this works!
|
2020/06/03
|
[
"https://Stackoverflow.com/questions/62163714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12304196/"
] |
CSS:
```
.bi-headphones::before {
display: inline-block;
content: "";
background-image: url("data:image/svg+xml,%3Csvg width='1em' height='1em' viewBox='0 0 16 16' class='bi bi-headphones' fill='currentColor' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' d='M8 3a5 5 0 0 0-5 5v4.5H2V8a6 6 0 1 1 12 0v4.5h-1V8a5 5 0 0 0-5-5z'/%3E%3Cpath d='M11 10a1 1 0 0 1 1-1h2v4a1 1 0 0 1-1 1h-1a1 1 0 0 1-1-1v-3zm-6 0a1 1 0 0 0-1-1H2v4a1 1 0 0 0 1 1h1a1 1 0 0 0 1-1v-3z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-size: 1rem 1rem;
width:1rem; height:1rem;
}
```
Usage:
```
<i class="bi-headphones"></i>
```
I use URl SVG encoder to prepare svg for css: <https://yoksel.github.io/url-encoder/>
|
i cant find in the doc that bootstrap icon is fontawesome icon
after you install it you use it as a svg like this one
```
<svg class="bi bi-app" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M11 2H5a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V5a3 3 0 0 0-3-3zM5 1a4 4 0 0 0-4 4v6a4 4 0 0 0 4 4h6a4 4 0 0 0 4-4V5a4 4 0 0 0-4-4H5z"/>
</svg>
```
or you can use it this way after you download the svg to you project
```
<img src="/assets/img/bootstrap.svg" alt="" width="32" height="32" title="Bootstrap">
```
or on your css
```
.bi::before {
display: inline-block;
content: "";
background-image: url("data:image/svg+xml,<svg viewBox='0 0 16 16' fill='%23333' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z' clip-rule='evenodd'/></svg>");
background-repeat: no-repeat;
background-size: 1rem 1rem;
}
```
|
17,461,134
|
I am using Python2.7.5 in Windows 7. I'm new to command line arguments. I am trying to do this exercise:
Write a program that reads in a string on the command line and returns a table of the letters which occur in the string with the number of times each letter occurs. For example:
```
$ python letter_counts.py "ThiS is String with Upper and lower case Letters."
a 2
c 1
d 1
# etc.
```
I know how to add command line arguments to a file name and output them in a list in cmd (windows command prompt).
However, I would like to learn how to work with command line arguments in python script- because I need to add/access the additional command line arguments and create a loop in order to count their letters.
Outside of cmd, I currently only have letter\_counts.py as the filename- that's only one command line argument.
In python not cmd : how do I add and access command line arguments?
|
2013/07/04
|
[
"https://Stackoverflow.com/questions/17461134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547317/"
] |
You want to use the [`sys.argv`](http://docs.python.org/2/library/sys.html#sys.argv) list from the [sys](http://docs.python.org/2/library/sys.html#module-sys) module. It lets you access arguments passed in the command line.
For example, if your command line input was `python myfile.py a b c`, `sys.argv[0]` is myfile.py, `sys.argv[1]` is a, `sys.argv[2]` is b, and `sys.argv[3]` is c.
A running example (`testcode.py`):
```
if __name__ == "__main__":
import sys
print sys.argv
```
Then, running (in the command line):
```
D:\some_path>python testcode.py a b c
['testcode.py', 'a', 'b', 'c']
```
|
You can do something along these lines:
```
#!/usr/bin/python
import sys
print sys.argv
counts={}
for st in sys.argv[1:]:
for c in st:
counts.setdefault(c.lower(),0)
counts[c.lower()]+=1
for k,v in sorted(counts.items(), key=lambda t: t[1], reverse=True):
print "'{}' {}".format(k,v)
```
When invoked with `python letter_counts.py "ThiS is String with Upper and lower case Letters."` prints:
```
['./letter_counts.py', 'ThiS is String with Upper and lower case Letters.']
' ' 8
'e' 5
's' 5
't' 5
'i' 4
'r' 4
'a' 2
'h' 2
'l' 2
'n' 2
'p' 2
'w' 2
'c' 1
'd' 1
'g' 1
'o' 1
'u' 1
'.' 1
```
If you instead do not use quotes, like this: `python letter_counts.py ThiS is String with Upper and lower case Letters.` it prints:
```
['./letter_counts.py', 'ThiS', 'is', 'String', 'with', 'Upper', 'and', 'lower', 'case', 'Letters.']
'e' 5
's' 5
't' 5
'i' 4
'r' 4
'a' 2
'h' 2
'l' 2
'n' 2
'p' 2
'w' 2
'c' 1
'd' 1
'g' 1
'o' 1
'u' 1
'.' 1
```
Note the difference in the list `sys.argv` at the top of the output. The result is that whitespace between words is lost and the letter counts are the same.
|
47,069,829
|
This may be a repeated question of attempting to run a mysql query on a remote machine using python.
Im using pymysql and SSHTunnelForwarder for this.
The mysqldb is located on different server (192.168.10.13 and port 5555).
Im trying to use the following snippet:
```
with SSHTunnelForwarder(
(host, ssh_port),
ssh_username = ssh_user,
ssh_password = ssh_pass,
remote_bind_address=('127.0.0.1', 5555)) as server:
with pymysql.connect("192.168.10.13", user, password, port=server.local_bind_port) as connection:
cursor = connection.cursor()
output = cursor.execute("select * from billing_cdr limit 1")
print output
```
Is this the correct approach ?
I see the following error:
```
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
```
Also is there any other recommended library to use ?
|
2017/11/02
|
[
"https://Stackoverflow.com/questions/47069829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4670651/"
] |
Found this to be working after some digging.
```
with SSHTunnelForwarder(
("192.168.10.13", 22),
ssh_username = ssh_user,
ssh_password = ssh_pass,
remote_bind_address=('127.0.0.1', 5555)) as server:
with pymysql.connect('127.0.0.1', user, password, port=server.local_bind_port) as connection:
output = connection.execute("select * from db.table limit 1")
print output
```
|
you can do it like this:
```
conn = MySQLdb.connect(
host=host,
port=port,
user=username,
passwd=password,
db=database
charset='utf8',)
cur = conn.cursor()
cur.execute("select * from billing_cdr limit 1")
rows = cur.fetchall()
for row in rows:
a=row[0]
b=row[1]
conn.close()
```
|
16,784,154
|
With the help of joksnet's programs [here](https://stackoverflow.com/questions/4460921/extract-the-first-paragraph-from-a-wikipedia-article-python) I've managed to get plaintext Wikipedia articles that I'm looking for.
The text returned includes Wiki markup for the headings, so for example, the sections of the [Albert Einstein article](http://en.wikipedia.org/wiki/Albert_einstein) are returned like this:
```
==Biography==
===Early life and education===
blah blah blah
```
What I'd really like to do is feed the retrieved text to a function and wrap all the top level sections in bold html tags and the second level sections in italics, like this:
```
<b>Biography</b>
<i>Early life and education</i>
blah blah blah
```
But I'm afraid I don't know how to even start, at least not without making the function dangerously naive. Do I need to use regular expressions?
Any suggestions greatly appreciated.
PS Sorry if "parsing" is too strong a word for what I'm trying to do here.
|
2013/05/28
|
[
"https://Stackoverflow.com/questions/16784154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/728286/"
] |
I think the best way here would be to let MediaWiki take care of the parsing. I don't know the library you're using, but basically this is the difference between
<http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Albert%20Einstein&rvprop=content>
which returns the raw wikitext and
<http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Albert%20Einstein&rvprop=content&rvparse>
which returns the parsed HTML.
|
You can use regex and scraping modules like Scrapy and Beautifulsoup to parse and scrape wiki pages.
Now that you clarified your question I suggest you use the py-wikimarkup module that is hosted on github. The link is <https://github.com/dcramer/py-wikimarkup/> . I hope that helps.
|
16,784,154
|
With the help of joksnet's programs [here](https://stackoverflow.com/questions/4460921/extract-the-first-paragraph-from-a-wikipedia-article-python) I've managed to get plaintext Wikipedia articles that I'm looking for.
The text returned includes Wiki markup for the headings, so for example, the sections of the [Albert Einstein article](http://en.wikipedia.org/wiki/Albert_einstein) are returned like this:
```
==Biography==
===Early life and education===
blah blah blah
```
What I'd really like to do is feed the retrieved text to a function and wrap all the top level sections in bold html tags and the second level sections in italics, like this:
```
<b>Biography</b>
<i>Early life and education</i>
blah blah blah
```
But I'm afraid I don't know how to even start, at least not without making the function dangerously naive. Do I need to use regular expressions?
Any suggestions greatly appreciated.
PS Sorry if "parsing" is too strong a word for what I'm trying to do here.
|
2013/05/28
|
[
"https://Stackoverflow.com/questions/16784154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/728286/"
] |
I ended up doing this:
```
def parseWikiTitles(x):
counter = 1
while '===' in x:
if counter == 1:
x = x.replace('===','<i>',1)
counter = 2
else:
x = x.replace('===',r'</i>',1)
counter = 1
counter = 1
while '==' in x:
if counter == 1:
x = x.replace('==','<b>',1)
counter = 2
else:
x = x.replace('==',r'</b>',1)
counter = 1
x = x.replace('<b> ', '<b>', 50)
x = x.replace(r' </b>', r'</b>', 50)
x = x.replace('<i> ', '<i>', 50)
x = x.replace(r' </i>', r'<i>', 50)
return x
```
I pass the string of text with wiki titles to that function and it returns the same text with the == and === replaced with bold and italics HTML tags. The last thing removes spaces before and after titles, for example `== title ==` gets converted to `<b>title</b>` instead of `<b> title </b>`
Has worked without problem so far.
Thanks for the help guys,
Alex
|
You can use regex and scraping modules like Scrapy and Beautifulsoup to parse and scrape wiki pages.
Now that you clarified your question I suggest you use the py-wikimarkup module that is hosted on github. The link is <https://github.com/dcramer/py-wikimarkup/> . I hope that helps.
|
19,542,883
|
I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
```
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
```
Based on my understanding of python, the line
```
if isintance(value, int) == True
break
```
should end the while loop if **value** is an integer, but it doesn't.
My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn't my code work?
|
2013/10/23
|
[
"https://Stackoverflow.com/questions/19542883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2826154/"
] |
The reason your code doesn't work is because `input()` will always return a string. Which will always cause `isinstance(value, int)` to always evaluate to `False`.
You probably want:
```
value = ''
while not value.strip().isdigit():
value = input("Please enter the value")
```
|
`input` always returns a string, you have to convert it to `int` yourself.
Try this snippet:
```
while True:
try:
value = int(input("Please enter the value: "))
except ValueError:
print ("Invalid value.")
else:
break
```
|
19,542,883
|
I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
```
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
```
Based on my understanding of python, the line
```
if isintance(value, int) == True
break
```
should end the while loop if **value** is an integer, but it doesn't.
My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn't my code work?
|
2013/10/23
|
[
"https://Stackoverflow.com/questions/19542883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2826154/"
] |
The reason your code doesn't work is because `input()` will always return a string. Which will always cause `isinstance(value, int)` to always evaluate to `False`.
You probably want:
```
value = ''
while not value.strip().isdigit():
value = input("Please enter the value")
```
|
Be aware when using `.isdigit()`, it will return False on negative integers. So `isinstance(value, int)` is maybe a better choice.
I cannot comment on accepted answer because of low rep.
|
19,542,883
|
I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
```
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
```
Based on my understanding of python, the line
```
if isintance(value, int) == True
break
```
should end the while loop if **value** is an integer, but it doesn't.
My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn't my code work?
|
2013/10/23
|
[
"https://Stackoverflow.com/questions/19542883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2826154/"
] |
The reason your code doesn't work is because `input()` will always return a string. Which will always cause `isinstance(value, int)` to always evaluate to `False`.
You probably want:
```
value = ''
while not value.strip().isdigit():
value = input("Please enter the value")
```
|
If you want to manage negative integers you should use :
```
value = ''
while not value.strip().lstrip("-").isdigit():
value = input("Please enter the value")
```
|
19,542,883
|
I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
```
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
```
Based on my understanding of python, the line
```
if isintance(value, int) == True
break
```
should end the while loop if **value** is an integer, but it doesn't.
My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn't my code work?
|
2013/10/23
|
[
"https://Stackoverflow.com/questions/19542883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2826154/"
] |
Be aware when using `.isdigit()`, it will return False on negative integers. So `isinstance(value, int)` is maybe a better choice.
I cannot comment on accepted answer because of low rep.
|
`input` always returns a string, you have to convert it to `int` yourself.
Try this snippet:
```
while True:
try:
value = int(input("Please enter the value: "))
except ValueError:
print ("Invalid value.")
else:
break
```
|
19,542,883
|
I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
```
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
```
Based on my understanding of python, the line
```
if isintance(value, int) == True
break
```
should end the while loop if **value** is an integer, but it doesn't.
My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn't my code work?
|
2013/10/23
|
[
"https://Stackoverflow.com/questions/19542883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2826154/"
] |
Be aware when using `.isdigit()`, it will return False on negative integers. So `isinstance(value, int)` is maybe a better choice.
I cannot comment on accepted answer because of low rep.
|
If you want to manage negative integers you should use :
```
value = ''
while not value.strip().lstrip("-").isdigit():
value = input("Please enter the value")
```
|
49,993,687
|
Let's say I am running multiple python processes(not threads) on a multi core CPU (say 4). GIL is process level so GIL within a particular process won't affect other processes.
My question here is if the GIL within one process will take hold of only single core out of 4 cores or will it take hold of all 4 cores?
If one process locks all cores at once, then multiprocessing should not be any better than multi threading in python. If not how do the cores get allocated to various processes?
>
> As an observation, in my system which is 8 cores (4\*2 because of
> hyperthreading), when I run a single CPU bound process, the CPU usage
> of 4 out of 8 cores goes up.
>
>
>
Simplifying this:
4 python threads (in one process) running on a 4 core CPU will take more time than single thread doing same work (considering the work is fully CPU bound). Will 4 different process doing that amount of work reduce the time taken by a factor of near 4?
|
2018/04/24
|
[
"https://Stackoverflow.com/questions/49993687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4510252/"
] |
Python doesn't do anything to [bind processes or threads to cores](https://en.wikipedia.org/wiki/Processor_affinity); it just leaves things up to the OS. When you spawn a bunch of independent processes (or threads, but that's harder to do in Python), the OS's scheduler will quickly and efficiently get them spread out across your cores without you, or Python, needing to do anything (barring really bad pathological cases).
---
The GIL isn't relevant here. I'll get to that later, but first let's explain what *is* relevant.
You don't have 8 cores. You have 4 cores, each of which is [hyperthreaded](https://en.wikipedia.org/wiki/Hyper-threading).
Modern cores have a whole lot of "super-scalar" capacity. Often, the instructions queued up in a pipeline aren't independent enough to take full advantage of that capacity. What hyperthreading does is to allow the core to go fetch other instructions off a second pipeline when this happens, which are virtually guaranteed to be independent. But it only allows that, not requires, because in some cases (which the CPU can usually decide better than you) the cost in cache locality would be worse than the gains in parallelism.
So, depending on the actual load you're running, with four hyperthreaded cores, you may get full 800% CPU usage, or you may only get 400%, or (pretty often) somewhere in between.
I'm assuming your system is configured to report 8 cores rather than 4 to userland, because that's the default, and that you're have at least 8 processes or a pool with default proc count and at least 8 tasks—obviously, if none of that is true, you can't possibly get 800% CPU usage…
I'm also assuming you aren't using explicit locks, other synchronization, `Manager` objects, or anything else that will serialize your code. If you do, obviously you can't get full parallelism.
And I'm also assuming you aren't using (mutable) shared memory, like a `multiprocessing.Array` that everyone writes to. This can cause cache and page conflicts that can be almost as bad as explicit locks.
---
So, what's the deal with the GIL? Well, if you were running multiple threads within a process, and they were all CPU-bound, and they were all spending most of that time running Python code (as opposed to, say, spending most of that time running numpy operations that release the GIL), only one thread would run at a time. You could see:
* 100% consistently on a single core, while the rest sit at 0%.
* 100% pingponging between two or more cores, while the rest sit at 0%.
* 100% pingponging between two or more cores, while the rest sit at 0%, but with some noticeable overlap where two cores at once are way over 0%. This last one might *look* like parallelism, but it isn't—that's just the switching overhead becoming visible.
But you're not running multiple threads, you're running separate processes, each of which has its own entirely independent GIL. And that's why you're seeing four cores at 100% rather than just one.
|
Process to CPU/CPU core allocation is handled by the Operating System.
|
54,193,625
|
I'm trying to fetch data for facebook account using selenium browser python but can't able to find the which element I can look out for clicking on an export button.
See attached screenshot[](https://i.stack.imgur.com/fd2Mf.png)
I tried but it seems giving me an error for the class.
```
def login_facebook(self, username, password):
chrome_options = webdriver.ChromeOptions()
preference = {"download.default_directory": self.section_value[24]}
chrome_options.add_experimental_option("prefs", preference)
self.driver = webdriver.Chrome(self.section_value[20], chrome_options=chrome_options)
self.driver.get(self.section_value[25])
username_field = self.driver.find_element_by_id("email")
password_field = self.driver.find_element_by_id("pass")
username_field.send_keys(username)
self.driver.implicitly_wait(10)
password_field.send_keys(password)
self.driver.implicitly_wait(10)
self.driver.find_element_by_id("loginbutton").click()
self.driver.implicitly_wait(10)
self.driver.get("https://business.facebook.com/select/?next=https%3A%2F%2Fbusiness.facebook.com%2F")
self.driver.get("https://business.facebook.com/home/accounts?business_id=698597566882728")
self.driver.get("https://business.facebook.com/adsmanager/reporting/view?act="
"717590098609803&business_id=698597566882728&selected_report_id=23843123660810666")
# self.driver.get("https://business.facebook.com/adsmanager/manage/campaigns?act=717590098609803&business_id"
# "=698597566882728&tool=MANAGE_ADS&date={}-{}_{}%2Clast_month".format(self.last_month,
# self.first_day_month,
# self.last_day_month))
self.driver.find_element_by_id("export_button").click()
self.driver.implicitly_wait(10)
self.driver.find_element_by_class_name("_43rl").click()
self.driver.implicitly_wait(10)
```
Can you please let me know how can i click on Export button?
|
2019/01/15
|
[
"https://Stackoverflow.com/questions/54193625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7684584/"
] |
Well, I'm able to resolve it by using xpath.
Here is the solution
```
self.driver.find_element_by_xpath("//*[contains(@class, '_271k _271m _1qjd layerConfirm')]").click()
```
|
to run automation scripts on applications like facebook, youtube quite a hard because they are huge coporations and their web applications are developed by the worlds best developers but its not impossible to run automation scripts sometimes elements are generated dynamically sometimes hidden or inactive you cant just go and click
one solution is you can do by click action by xpath realtive or absolute their is not id specified as "export\_button" in resource file i think this might help you
you can also find element by class name or css selector as i see in screen shot the class name is present "\_271K \_271m \_1qjd layerConfirm " you can perform click action on that
|
54,193,625
|
I'm trying to fetch data for facebook account using selenium browser python but can't able to find the which element I can look out for clicking on an export button.
See attached screenshot[](https://i.stack.imgur.com/fd2Mf.png)
I tried but it seems giving me an error for the class.
```
def login_facebook(self, username, password):
chrome_options = webdriver.ChromeOptions()
preference = {"download.default_directory": self.section_value[24]}
chrome_options.add_experimental_option("prefs", preference)
self.driver = webdriver.Chrome(self.section_value[20], chrome_options=chrome_options)
self.driver.get(self.section_value[25])
username_field = self.driver.find_element_by_id("email")
password_field = self.driver.find_element_by_id("pass")
username_field.send_keys(username)
self.driver.implicitly_wait(10)
password_field.send_keys(password)
self.driver.implicitly_wait(10)
self.driver.find_element_by_id("loginbutton").click()
self.driver.implicitly_wait(10)
self.driver.get("https://business.facebook.com/select/?next=https%3A%2F%2Fbusiness.facebook.com%2F")
self.driver.get("https://business.facebook.com/home/accounts?business_id=698597566882728")
self.driver.get("https://business.facebook.com/adsmanager/reporting/view?act="
"717590098609803&business_id=698597566882728&selected_report_id=23843123660810666")
# self.driver.get("https://business.facebook.com/adsmanager/manage/campaigns?act=717590098609803&business_id"
# "=698597566882728&tool=MANAGE_ADS&date={}-{}_{}%2Clast_month".format(self.last_month,
# self.first_day_month,
# self.last_day_month))
self.driver.find_element_by_id("export_button").click()
self.driver.implicitly_wait(10)
self.driver.find_element_by_class_name("_43rl").click()
self.driver.implicitly_wait(10)
```
Can you please let me know how can i click on Export button?
|
2019/01/15
|
[
"https://Stackoverflow.com/questions/54193625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7684584/"
] |
The element with text as **Export** is a dynamically generated element so to locate the element you have to induce *WebDriverWait* for the *element to be clickable* and you can use either of the [locator strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using *CSS\_SELECTOR*:
```
WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.layerConfirm>div[data-hover='tooltip'][data-tooltip-display='overflow']"))).click()
```
* Using *XPATH*:
```
WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'layerConfirm')]/div[@data-hover='tooltip' and text()='Export']"))).click()
```
* **Note** : You have to add the following imports :
```
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
```
|
to run automation scripts on applications like facebook, youtube quite a hard because they are huge coporations and their web applications are developed by the worlds best developers but its not impossible to run automation scripts sometimes elements are generated dynamically sometimes hidden or inactive you cant just go and click
one solution is you can do by click action by xpath realtive or absolute their is not id specified as "export\_button" in resource file i think this might help you
you can also find element by class name or css selector as i see in screen shot the class name is present "\_271K \_271m \_1qjd layerConfirm " you can perform click action on that
|
54,193,625
|
I'm trying to fetch data for facebook account using selenium browser python but can't able to find the which element I can look out for clicking on an export button.
See attached screenshot[](https://i.stack.imgur.com/fd2Mf.png)
I tried but it seems giving me an error for the class.
```
def login_facebook(self, username, password):
chrome_options = webdriver.ChromeOptions()
preference = {"download.default_directory": self.section_value[24]}
chrome_options.add_experimental_option("prefs", preference)
self.driver = webdriver.Chrome(self.section_value[20], chrome_options=chrome_options)
self.driver.get(self.section_value[25])
username_field = self.driver.find_element_by_id("email")
password_field = self.driver.find_element_by_id("pass")
username_field.send_keys(username)
self.driver.implicitly_wait(10)
password_field.send_keys(password)
self.driver.implicitly_wait(10)
self.driver.find_element_by_id("loginbutton").click()
self.driver.implicitly_wait(10)
self.driver.get("https://business.facebook.com/select/?next=https%3A%2F%2Fbusiness.facebook.com%2F")
self.driver.get("https://business.facebook.com/home/accounts?business_id=698597566882728")
self.driver.get("https://business.facebook.com/adsmanager/reporting/view?act="
"717590098609803&business_id=698597566882728&selected_report_id=23843123660810666")
# self.driver.get("https://business.facebook.com/adsmanager/manage/campaigns?act=717590098609803&business_id"
# "=698597566882728&tool=MANAGE_ADS&date={}-{}_{}%2Clast_month".format(self.last_month,
# self.first_day_month,
# self.last_day_month))
self.driver.find_element_by_id("export_button").click()
self.driver.implicitly_wait(10)
self.driver.find_element_by_class_name("_43rl").click()
self.driver.implicitly_wait(10)
```
Can you please let me know how can i click on Export button?
|
2019/01/15
|
[
"https://Stackoverflow.com/questions/54193625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7684584/"
] |
The element with text as **Export** is a dynamically generated element so to locate the element you have to induce *WebDriverWait* for the *element to be clickable* and you can use either of the [locator strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using *CSS\_SELECTOR*:
```
WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.layerConfirm>div[data-hover='tooltip'][data-tooltip-display='overflow']"))).click()
```
* Using *XPATH*:
```
WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'layerConfirm')]/div[@data-hover='tooltip' and text()='Export']"))).click()
```
* **Note** : You have to add the following imports :
```
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
```
|
Well, I'm able to resolve it by using xpath.
Here is the solution
```
self.driver.find_element_by_xpath("//*[contains(@class, '_271k _271m _1qjd layerConfirm')]").click()
```
|
55,915,109
|
Im trying to create a more dynamic program where I define a function's name based on a variable string.
Trying to define a function using a variable like this:
```py
__func_name__ = "fun"
def __func_name__():
print('Hello from ' + __func_name__)
fun()
```
Was wanting this to output:
```
Hello from fun
```
The only examples I found were:
[how to define a function from a string using python](https://stackoverflow.com/questions/5920120/how-to-define-a-function-from-a-string-using-python)
|
2019/04/30
|
[
"https://Stackoverflow.com/questions/55915109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6828625/"
] |
You can update `globals`:
```
>>> globals()["my_function_name"] = lambda x: x + 1
>>> my_function_name(10)
11
```
But usually is more convinient to use a dictionary that have the functions related:
```
my_func_dict = {
"__func_name__" : __func_name__,
}
def __func_name__():
print('Hello')
```
And then use the dict to take the funtion back using the name as a key:
```
my_func_dict["__func_name__"]()
```
|
This should do it as well, using the `globals` to update function name on the fly.
```
def __func_name__():
print('Hello from ' + __func_name__.__name__)
globals()['fun'] = __func_name__
fun()
```
The output will be
```
Hello from __func_name__
```
|
47,912,701
|
There is a solution posted [here](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) to create a stoppable thread. However, I am having some problems understanding how to implement this solution.
Using the code...
```
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
```
How can I create a thread that runs a function that prints "Hello" to the terminal every 1 second. After 5 seconds I use the .stop() to stop the looping function/thread.
Again I am having troubles understanding how to implement this stopping solution, here is what I have so far.
```
import threading
import time
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def funct():
while not testthread.stopped():
time.sleep(1)
print("Hello")
testthread = StoppableThread()
testthread.start()
time.sleep(5)
testthread.stop()
```
Code above creates the thread testthread which can be stopped by the testthread.stop() command. From what I understand this is just creating an empty thread... Is there a way I can create a thread that runs funct() and the thread will end when I use .stop(). Basically I do not know how to implement the StoppableThread class to run the funct() function as a thread.
Example of a regular threaded function...
```
import threading
import time
def example():
x = 0
while x < 5:
time.sleep(1)
print("Hello")
x = x + 1
t = threading.Thread(target=example)
t.start()
t.join()
#example of a regular threaded function.
```
|
2017/12/20
|
[
"https://Stackoverflow.com/questions/47912701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9124164/"
] |
There are a couple of problems with how you are using the code in your original example. First of all, you are not passing any constructor arguments to the base constructor. This is a problem because, as you can see in the plain-Thread example, constructor arguments are often necessary. You should rewrite `StoppableThread.__init__` as follows:
```
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
```
Since you are using Python 3, you do not need to provide arguments to `super`. Now you can do
```
testthread = StoppableThread(target=funct)
```
This is still not an optimal solution, because `funct` uses an external variable, `testthread` to stop itself. While this is OK-ish for a tiny example like yours, using global variables like that normally causes a huge maintenance burden and you don't want to do it. A much better solution would be to extend the generic `StoppableThread` class for your particular task, so you can access `self` properly:
```
class MyTask(StoppableThread):
def run(self):
while not self.stopped():
time.sleep(1)
print("Hello")
testthread = MyTask()
testthread.start()
time.sleep(5)
testthread.stop()
```
If you absolutely do not want to extend `StoppableThread`, you can use the [`current_thread`](https://docs.python.org/3/library/threading.html#threading.current_thread) function in your task in preference to reading a global variable:
```
def funct():
while not current_thread().stopped():
time.sleep(1)
print("Hello")
testthread = StoppableThread(target=funct)
testthread.start()
sleep(5)
testthread.stop()
```
|
Inspired by above solution I created a small library, ants, for this problem.
Example
```
from ants import worker
@worker
def do_stuff():
...
thread code
...
do_stuff.start()
...
do_stuff.stop()
```
In above example do\_stuff will run in a separate thread being called in a `while 1:` loop
You can also have triggering events , e.g. in above replace `do_stuff.start()` with `do_stuff.start(lambda: time.sleep(5))` and you will have it trigger every 5:th second
The library is very new and work is ongoing on GitHub <https://github.com/fa1k3n/ants.git>
|
47,912,701
|
There is a solution posted [here](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) to create a stoppable thread. However, I am having some problems understanding how to implement this solution.
Using the code...
```
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
```
How can I create a thread that runs a function that prints "Hello" to the terminal every 1 second. After 5 seconds I use the .stop() to stop the looping function/thread.
Again I am having troubles understanding how to implement this stopping solution, here is what I have so far.
```
import threading
import time
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def funct():
while not testthread.stopped():
time.sleep(1)
print("Hello")
testthread = StoppableThread()
testthread.start()
time.sleep(5)
testthread.stop()
```
Code above creates the thread testthread which can be stopped by the testthread.stop() command. From what I understand this is just creating an empty thread... Is there a way I can create a thread that runs funct() and the thread will end when I use .stop(). Basically I do not know how to implement the StoppableThread class to run the funct() function as a thread.
Example of a regular threaded function...
```
import threading
import time
def example():
x = 0
while x < 5:
time.sleep(1)
print("Hello")
x = x + 1
t = threading.Thread(target=example)
t.start()
t.join()
#example of a regular threaded function.
```
|
2017/12/20
|
[
"https://Stackoverflow.com/questions/47912701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9124164/"
] |
There are a couple of problems with how you are using the code in your original example. First of all, you are not passing any constructor arguments to the base constructor. This is a problem because, as you can see in the plain-Thread example, constructor arguments are often necessary. You should rewrite `StoppableThread.__init__` as follows:
```
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
```
Since you are using Python 3, you do not need to provide arguments to `super`. Now you can do
```
testthread = StoppableThread(target=funct)
```
This is still not an optimal solution, because `funct` uses an external variable, `testthread` to stop itself. While this is OK-ish for a tiny example like yours, using global variables like that normally causes a huge maintenance burden and you don't want to do it. A much better solution would be to extend the generic `StoppableThread` class for your particular task, so you can access `self` properly:
```
class MyTask(StoppableThread):
def run(self):
while not self.stopped():
time.sleep(1)
print("Hello")
testthread = MyTask()
testthread.start()
time.sleep(5)
testthread.stop()
```
If you absolutely do not want to extend `StoppableThread`, you can use the [`current_thread`](https://docs.python.org/3/library/threading.html#threading.current_thread) function in your task in preference to reading a global variable:
```
def funct():
while not current_thread().stopped():
time.sleep(1)
print("Hello")
testthread = StoppableThread(target=funct)
testthread.start()
sleep(5)
testthread.stop()
```
|
I found some implementation of a stoppable thread - and it does not rely that You check if it should continue to run inside the thread - it "injects" an exception into the wrapped function - that will work as long as You dont do something like :
```
while True:
try:
do something
except:
pass
```
definitely worth looking at !
see : <https://github.com/kata198/func_timeout>
maybe I will extend my wrapt\_timeout\_decorator with such kind of mechanism, which You can find here : <https://github.com/bitranox/wrapt_timeout_decorator>
|
47,912,701
|
There is a solution posted [here](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) to create a stoppable thread. However, I am having some problems understanding how to implement this solution.
Using the code...
```
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
```
How can I create a thread that runs a function that prints "Hello" to the terminal every 1 second. After 5 seconds I use the .stop() to stop the looping function/thread.
Again I am having troubles understanding how to implement this stopping solution, here is what I have so far.
```
import threading
import time
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def funct():
while not testthread.stopped():
time.sleep(1)
print("Hello")
testthread = StoppableThread()
testthread.start()
time.sleep(5)
testthread.stop()
```
Code above creates the thread testthread which can be stopped by the testthread.stop() command. From what I understand this is just creating an empty thread... Is there a way I can create a thread that runs funct() and the thread will end when I use .stop(). Basically I do not know how to implement the StoppableThread class to run the funct() function as a thread.
Example of a regular threaded function...
```
import threading
import time
def example():
x = 0
while x < 5:
time.sleep(1)
print("Hello")
x = x + 1
t = threading.Thread(target=example)
t.start()
t.join()
#example of a regular threaded function.
```
|
2017/12/20
|
[
"https://Stackoverflow.com/questions/47912701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9124164/"
] |
I found some implementation of a stoppable thread - and it does not rely that You check if it should continue to run inside the thread - it "injects" an exception into the wrapped function - that will work as long as You dont do something like :
```
while True:
try:
do something
except:
pass
```
definitely worth looking at !
see : <https://github.com/kata198/func_timeout>
maybe I will extend my wrapt\_timeout\_decorator with such kind of mechanism, which You can find here : <https://github.com/bitranox/wrapt_timeout_decorator>
|
Inspired by above solution I created a small library, ants, for this problem.
Example
```
from ants import worker
@worker
def do_stuff():
...
thread code
...
do_stuff.start()
...
do_stuff.stop()
```
In above example do\_stuff will run in a separate thread being called in a `while 1:` loop
You can also have triggering events , e.g. in above replace `do_stuff.start()` with `do_stuff.start(lambda: time.sleep(5))` and you will have it trigger every 5:th second
The library is very new and work is ongoing on GitHub <https://github.com/fa1k3n/ants.git>
|
71,719,341
|
I made a small pygame app that plays certain wav files in keypress using pygame.mixer
All seem to work just fine except the fact that if you minimize the pygame window the program stops working until you open it again. Is there a way to solve this issue or an alternative way to implement sound playing in python?
This is my repository: <https://github.com/Souvlaki42/HighPlayer>
|
2022/04/02
|
[
"https://Stackoverflow.com/questions/71719341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15354246/"
] |
Several ways. Here are a couple:
Standard SQL:
```sql
SELECT DISTINCT
CASE WHEN col1 < col2 THEN col1 ELSE col2 END AS col1
, CASE WHEN col1 < col2 THEN col2 ELSE col1 END AS col2
FROM tbl
;
```
or (MySQL supports this one):
```sql
SELECT DISTINCT
LEAST(col1, col2) AS col1
, GREATEST(col1, col2) AS col2
FROM tbl
;
```
There are other approaches, which have slightly different behavior.
For instance, we might want to keep ('B', 'A') if ('A', 'B') doesn't also exist.
Another thought is we could prevent this issue by correcting the data on INSERT by using similar LEAST / GREATEST logic in the INSERT (or a trigger), to be sure col1 was always less than or equal to col2.
Then add a unique constraint on (col1, col2) and a table check constraint (col1 <= col2) to prevent duplicates and reflections.
|
```
select distinct least(col_1, col_2), greatest(col_1, col_2)
from the_table
order by 1
```
|
66,239,918
|
I wrote this code to return a list of skills. If the user already has a specific skill, the list-item should be updated to `active = false`.
This is my initial code:
```js
setup () {
const user = ref ({
id: null,
skills: []
});
const available_skills = ref ([
{value: 'css', label: 'CSS', active: true},
{value: 'html', label: 'HTML', active: true},
{value: 'php', label: 'PHP', active: true},
{value: 'python', label: 'Python', active: true},
{value: 'sql', label: 'SQL', active: true},
]);
const computed_skills = computed (() => {
let result = available_skills.value.map ((skill) => {
if (user.value.skills.map ((sk) => {
return sk.name;
}).includes (skill.label)) {
skill.active = false;
}
return skill;
});
return result;
})
return {
user, computed_skills
}
},
```
This works fine on the initial rendering. But if I remove a skill from the user doing
`user.skills.splice(index, 1)` the `computed_skills` are not being updated.
Why is that the case?
|
2021/02/17
|
[
"https://Stackoverflow.com/questions/66239918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7510971/"
] |
In JavaScript user or an object is a refence to the object which is the pointer itself will not change upon changing the underling properties hence the computed is not triggered
kid of like computed property for an array and if that array get pushed with new values, the pointer of the array does not change but the underling reference only changes.
**Work around:**
try and reassign user by shadowing the variable
|
`slice` just returns a copy of the changed array, it doesn't change the original instance..hence computed property is not reactive
Try using below code
```
user.skills = user.skills.splice(index, 1);
```
|
66,239,918
|
I wrote this code to return a list of skills. If the user already has a specific skill, the list-item should be updated to `active = false`.
This is my initial code:
```js
setup () {
const user = ref ({
id: null,
skills: []
});
const available_skills = ref ([
{value: 'css', label: 'CSS', active: true},
{value: 'html', label: 'HTML', active: true},
{value: 'php', label: 'PHP', active: true},
{value: 'python', label: 'Python', active: true},
{value: 'sql', label: 'SQL', active: true},
]);
const computed_skills = computed (() => {
let result = available_skills.value.map ((skill) => {
if (user.value.skills.map ((sk) => {
return sk.name;
}).includes (skill.label)) {
skill.active = false;
}
return skill;
});
return result;
})
return {
user, computed_skills
}
},
```
This works fine on the initial rendering. But if I remove a skill from the user doing
`user.skills.splice(index, 1)` the `computed_skills` are not being updated.
Why is that the case?
|
2021/02/17
|
[
"https://Stackoverflow.com/questions/66239918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7510971/"
] |
The computed prop is actually being recomputed when you update `user.skills`, but the mapping of `available_skills` produces the same result, so there's no apparent change.
Assuming `user.skills` contains the full skill set from `available_skills`, the first computation sets all `skill.active` to `false`. When the user clicks the skill to remove it, the re-computation doesn't set `skill.active` again (there's no `else` clause).
```js
let result = available_skills.value.map((skill) => {
if (
user.value.skills
.map((sk) => {
return sk.name;
})
.includes(skill.label)
) {
skill.active = false;
}
// ❌ no else to set `skill.active`
return skill;
});
```
However, your computed prop has a side effect of mutating the original data (i.e., in `skill.active = false`), which [should be avoided](https://eslint.vuejs.org/rules/no-side-effects-in-computed-properties.html). The mapping above should clone the original `skill` item, and insert a new `active` property:
```js
const skills = user.value.skills.map(sk => sk.name);
let result = available_skills.value.map((skill) => {
return {
...skill,
active: skills.includes(skill.label)
}
});
```
[demo](https://codesandbox.io/s/computed-prop-dependency-cxqco?file=/src/components/Demo.vue:866-1091)
|
`slice` just returns a copy of the changed array, it doesn't change the original instance..hence computed property is not reactive
Try using below code
```
user.skills = user.skills.splice(index, 1);
```
|
66,670,964
|
I have the following python code:
```
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("example.com", 443))
client.send(b'POST /api HTTPS/1.1\r\nHost: example.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nAuthoriation: aa\r\nContent-Length: 22\r\n\r\n')
client.send(b'{"jsonPostData": "aaa"}')
response = client.recv(4096)
response = repr(response)
```
But it returns a 400 bad request error with no content, I tried same headers and json with requests and aiohttp and in both it works, any idea on what I am doing wrong?
|
2021/03/17
|
[
"https://Stackoverflow.com/questions/66670964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15414108/"
] |
It will **not overwrite** the secret if you create it manually in the console or using AWS SDK. The `aws_secretsmanager_secret` creates only the secret, but not its value. To set value you have to use [aws\_secretsmanager\_secret\_version](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret_version).
Anyway, this is something you can easily test yourself. Just run your code with a secret, update its value in AWS console, and re-run terraform apply. You should see no change in the secret's value.
|
You could have Terraform [generate random secret values](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/secretsmanager_random_password) for you using:
```
data "aws_secretsmanager_random_password" "dev_password" {
password_length = 16
}
```
Then create [the secret metadata](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret) using:
```
resource "aws_secretsmanager_secret" "dev_secret" {
name = "dev-secret"
recovery_window_in_days = 7
}
```
And then by creating [the secret version](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret_version):
```
resource "aws_secretsmanager_secret_version" "dev_sv" {
secret_id = aws_secretsmanager_secret.dev_secret.id
secret_string = data.aws_secretsmanager_random_password.dev_password.random_password
lifecycle {
ignore_changes = [secret_string, ]
}
}
```
Adding the 'ignore\_changes' [lifecycle block](https://www.terraform.io/language/meta-arguments/lifecycle#ignore_changes) to the secret version will prevent Terraform from overwriting the secret once it has been created. I tested this just now to confirm that a new secret with a new random value will be created, and subsequent executions of `terraform apply` do not overwrite the secret.
|
52,277,877
|
I'm trying to scrape this website using python and selenium. However all the information I need is not on the main page, so how would I click the links in the 'Application number' column one by one go to that page scrape the information then return to original page?
Ive tried:
```
def getData():
data = []
select = Select(driver.find_elements_by_xpath('//*[@id="node-41"]/div/div/div/div/div/div[1]/table/tbody/tr/td/a/@href'))
list_options = select.options
for item in range(len(list_options)):
item.click()
driver.get(url)
```
URL: <http://www.scilly.gov.uk/planning-development/planning-applications>
Screenshot of the site:
[](https://i.stack.imgur.com/oDOMT.png)
|
2018/09/11
|
[
"https://Stackoverflow.com/questions/52277877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10347887/"
] |
To open multiple hrefs within a webtable to scrape through selenium you can use the following solution:
* Code Block:
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
hrefs = []
options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
driver.get('http://www.scilly.gov.uk/planning-development/planning-applications')
windows_before = driver.current_window_handle # Store the parent_window_handle for future use
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "td.views-field.views-field-title>a"))) # Induce WebDriverWait for the visibility of the desired elements
for element in elements:
hrefs.append(element.get_attribute("href")) # Collect the required href attributes and store in a list
for href in hrefs:
driver.execute_script("window.open('" + href +"');") # Open the hrefs one by one through execute_script method in a new tab
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) # Induce WebDriverWait for the number_of_windows_to_be 2
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0] # Identify the newly opened window
# driver.switch_to_window(new_window) <!---deprecated>
driver.switch_to.window(new_window) # switch_to the new window
# perform your webscraping here
print(driver.title) # print the page title or your perform your webscraping
driver.close() # close the window
# driver.switch_to_window(windows_before) <!---deprecated>
driver.switch_to.window(windows_before) # switch_to the parent_window_handle
driver.quit() #Quit your program
```
* Console Output:
```
Planning application: P/18/064 | Council of the ISLES OF SCILLY
Planning application: P/18/063 | Council of the ISLES OF SCILLY
Planning application: P/18/062 | Council of the ISLES OF SCILLY
Planning application: P/18/061 | Council of the ISLES OF SCILLY
Planning application: p/18/059 | Council of the ISLES OF SCILLY
Planning application: P/18/058 | Council of the ISLES OF SCILLY
Planning application: P/18/057 | Council of the ISLES OF SCILLY
Planning application: P/18/056 | Council of the ISLES OF SCILLY
Planning application: P/18/055 | Council of the ISLES OF SCILLY
Planning application: P/18/054 | Council of the ISLES OF SCILLY
```
---
References
----------
You can find a couple of relevant detailed discussions in:
* [WebScraping JavaScript-Rendered Content using Selenium in Python](https://stackoverflow.com/questions/59144599/webscraping-javascript-rendered-content-using-selenium-in-python/59156403#59156403)
* [StaleElementReferenceException even after adding the wait while collecting the data from the wikipedia using web-scraping](https://stackoverflow.com/questions/65623799/staleelementreferenceexception-even-after-adding-the-wait-while-collecting-the-d/65631425#65631425)
* [Unable to access the remaining elements by xpaths in a loop after accessing the first element- Webscraping Selenium Python](https://stackoverflow.com/questions/59706039/unable-to-access-the-remaining-elements-by-xpaths-in-a-loop-after-accessing-the/59712944#59712944)
* [How to open each product within a website in a new tab for scraping using Selenium through Python](https://stackoverflow.com/questions/57640584/how-to-open-each-product-within-a-website-in-a-new-tab-for-scraping-using-seleni/57641549#57641549)
* [How to open multiple hrefs within a webtable to scrape through selenium](https://stackoverflow.com/questions/52277877/how-to-open-multiple-hrefs-within-a-webtable-to-scrape-through-selenium/52281843#52281843)
|
What you can do is the following:
```
import selenium
from selenium.webdriver.common.keys import Keys
from selenium import Webdriver
import time
url = "url"
browser = Webdriver.Chrome() #or whatever driver you use
browser.find_element_by_class_name("views-field views-field-title").click()
# or use this browser.find_element_by_xpath("xpath")
#Note you will need to change the class name to click a different item in the table
time.sleep(5) # not the best way to do this but its simple. Just to make sure things load
#it is here that you will be able to scrape the new url I will not post that as you can scrape what you want.
# When you are done scraping you can return to the previous page with this
driver.execute_script("window.history.go(-1)")
```
hope this is what you are looking for.
|
52,277,877
|
I'm trying to scrape this website using python and selenium. However all the information I need is not on the main page, so how would I click the links in the 'Application number' column one by one go to that page scrape the information then return to original page?
Ive tried:
```
def getData():
data = []
select = Select(driver.find_elements_by_xpath('//*[@id="node-41"]/div/div/div/div/div/div[1]/table/tbody/tr/td/a/@href'))
list_options = select.options
for item in range(len(list_options)):
item.click()
driver.get(url)
```
URL: <http://www.scilly.gov.uk/planning-development/planning-applications>
Screenshot of the site:
[](https://i.stack.imgur.com/oDOMT.png)
|
2018/09/11
|
[
"https://Stackoverflow.com/questions/52277877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10347887/"
] |
To open multiple hrefs within a webtable to scrape through selenium you can use the following solution:
* Code Block:
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
hrefs = []
options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
driver.get('http://www.scilly.gov.uk/planning-development/planning-applications')
windows_before = driver.current_window_handle # Store the parent_window_handle for future use
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "td.views-field.views-field-title>a"))) # Induce WebDriverWait for the visibility of the desired elements
for element in elements:
hrefs.append(element.get_attribute("href")) # Collect the required href attributes and store in a list
for href in hrefs:
driver.execute_script("window.open('" + href +"');") # Open the hrefs one by one through execute_script method in a new tab
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) # Induce WebDriverWait for the number_of_windows_to_be 2
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0] # Identify the newly opened window
# driver.switch_to_window(new_window) <!---deprecated>
driver.switch_to.window(new_window) # switch_to the new window
# perform your webscraping here
print(driver.title) # print the page title or your perform your webscraping
driver.close() # close the window
# driver.switch_to_window(windows_before) <!---deprecated>
driver.switch_to.window(windows_before) # switch_to the parent_window_handle
driver.quit() #Quit your program
```
* Console Output:
```
Planning application: P/18/064 | Council of the ISLES OF SCILLY
Planning application: P/18/063 | Council of the ISLES OF SCILLY
Planning application: P/18/062 | Council of the ISLES OF SCILLY
Planning application: P/18/061 | Council of the ISLES OF SCILLY
Planning application: p/18/059 | Council of the ISLES OF SCILLY
Planning application: P/18/058 | Council of the ISLES OF SCILLY
Planning application: P/18/057 | Council of the ISLES OF SCILLY
Planning application: P/18/056 | Council of the ISLES OF SCILLY
Planning application: P/18/055 | Council of the ISLES OF SCILLY
Planning application: P/18/054 | Council of the ISLES OF SCILLY
```
---
References
----------
You can find a couple of relevant detailed discussions in:
* [WebScraping JavaScript-Rendered Content using Selenium in Python](https://stackoverflow.com/questions/59144599/webscraping-javascript-rendered-content-using-selenium-in-python/59156403#59156403)
* [StaleElementReferenceException even after adding the wait while collecting the data from the wikipedia using web-scraping](https://stackoverflow.com/questions/65623799/staleelementreferenceexception-even-after-adding-the-wait-while-collecting-the-d/65631425#65631425)
* [Unable to access the remaining elements by xpaths in a loop after accessing the first element- Webscraping Selenium Python](https://stackoverflow.com/questions/59706039/unable-to-access-the-remaining-elements-by-xpaths-in-a-loop-after-accessing-the/59712944#59712944)
* [How to open each product within a website in a new tab for scraping using Selenium through Python](https://stackoverflow.com/questions/57640584/how-to-open-each-product-within-a-website-in-a-new-tab-for-scraping-using-seleni/57641549#57641549)
* [How to open multiple hrefs within a webtable to scrape through selenium](https://stackoverflow.com/questions/52277877/how-to-open-multiple-hrefs-within-a-webtable-to-scrape-through-selenium/52281843#52281843)
|
When you navigate to new page DOM is refreshed and you cannot use list method here. Here is my approach for this action (I don't code much in python so syntax and indendation may be broken)
```
count = driver.find_elements_by_xpath("//table[@class='views-table cols-6']/tbody/tr") # to count total number of links
len(count)
j = 1
if j<=len:
driver.find_element_by_xpath("//table[@class='views-table cols-6']/tbody/tr["+str(j)+"]/td/a").click()
#add wait here
#do your scrape action here
driver.find_element_by_xpath("//a[text()='Back to planning applications']").click()#to go back to main page
#add wait here for main page to load.
j+=1
```
|
20,952,629
|
I am trying to install Python Cassandra Driver and constantly getting error "vcvarsall.bat not found"
I tried using lots of solutions posted already in stackoverflow but non of them are working.
here is what i tried-
1. Using mingw gcc compiler.I followed every step, setting the path variable etc.
and then tried using "setup.py install --compiler=mingw32" but again got same error.
2. i have VS08 installed. and also path variable "VS80COMNTOOLS=C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\" is set. This is also not working.
3. Installed mingw- base tools,make tool,gcc compiler and then again followed step one but no help.
-edit
operating system windows enterprise N x64.
python version-2.7
I tried to install it on my windows server machine using first step and it worked fine but not working on my laptop.
|
2014/01/06
|
[
"https://Stackoverflow.com/questions/20952629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640953/"
] |
You will need to shorten the `memo` field to be able to use it in this manner. Try:
```
CAST(Desc AS NVARCHAR(2000))
```
|
Use Having clause instead of where condition in query.
```
Select count(*) as NBoccurrence,descr
From tbl_nm
Group by descr
Having your condition
```
|
25,996,880
|
This should be easy, but as ever Python's wildly overcomplicated datetime mess is making simple things complicated...
So I've got a time string in HH:MM format (eg. '09:30'), which I'd like to turn into a datetime with today's date. Unfortunately the default date is Jan 1 1900:
```
>>> datetime.datetime.strptime(time_str, "%H:%M")
datetime.datetime(1900, 1, 1, 9, 50)
```
[datetime.combine](https://docs.python.org/2/library/datetime.html#datetime.datetime.combine) looks like it's meant exactly for this, but I'll be darned if I can figure out how to get the time parsed so it'll accept it:
```
now = datetime.datetime.now()
>>> datetime.datetime.combine(now, time.strptime('09:30', '%H:%M'))
TypeError: combine() argument 2 must be datetime.time, not time.struct_time
>>> datetime.datetime.combine(now, datetime.datetime.strptime('09:30', '%H:%M'))
TypeError: combine() argument 2 must be datetime.time, not datetime.datetime
>>> datetime.datetime.combine(now, datetime.time.strptime('09:30', '%H:%M'))
AttributeError: type object 'datetime.time' has no attribute 'strptime'
```
This monstrosity works...
```
>>> datetime.datetime.combine(now,
datetime.time(*(time.strptime('09:30', '%H:%M')[3:6])))
datetime.datetime(2014, 9, 23, 9, 30)
```
...but there **must** be a better way to do that...!?
|
2014/09/23
|
[
"https://Stackoverflow.com/questions/25996880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218340/"
] |
The [function signature](https://docs.python.org/3/library/datetime.html#datetime.datetime.combine) says:
```
datetime.combine(date, time)
```
so pass a `datetime.date` object as the first argument, and a `datetime.time` object as the second argument:
```
>>> import datetime as dt
>>> today = dt.date.today()
>>> time = dt.datetime.strptime('09:30', '%H:%M').time()
>>> dt.datetime.combine(today, time)
datetime.datetime(2014, 9, 23, 9, 30)
```
|
`pip install python-dateutil`
```
>>> from dateutil import parser as dt_parser
>>> dt_parser.parse('07:20')
datetime.datetime(2016, 11, 25, 7, 20)
```
<https://dateutil.readthedocs.io/en/stable/parser.html>
|
56,893,578
|
I am trying to make a python program(python 3.6) that writes commands to terminal to download a specific youtube video(using youtube-dl).
If I go on terminal and execute the following command:
```
cd; cd Desktop; youtube-dl "https://www.youtube.com/watch?v=b91ovTKCZGU"
```
It will download the video to my desktop. However, if I execute the below code, which should be doing the same command on terminal, it does not throw an error but also does not download that video.
```py
import subprocess
cmd = ["cd;", "cd", "Desktop;", "youtube-dl", "\"https://www.youtube.com/watch?v=b91ovTKCZGU\""]
print(subprocess.call(cmd, stderr=subprocess.STDOUT,shell=True))
```
It seems that this just outputs 0. I do not think there is any kind of error 0 that exists(there are error 126 and 127). So if it is not throwing an error, why does it also not download the video?
Update:
I have fixed the above code by passing in a string, and have checked that youtube-dl is installed in my default python and is also in the folder where I want to download the videos, but its still throwing error 127, meaning command "youtube-dl" is not found.
|
2019/07/04
|
[
"https://Stackoverflow.com/questions/56893578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11303221/"
] |
Binary pattern matching can dissect the string:
```
data = ["AM00", "CC11", "CB11"]
for <<key::binary-size(2), value::binary>> <- data, into: %{} do
{key, value}
end
```
output:
```
%{"AM" => "00", "CB" => "11", "CC" => "11"}
```
That only works for single byte characters.
To handle `UTF-8` characters as well as `ASCII` characters:
```
data = ["èü00", "C€11", "€ä11"]
for <<char1::utf8, char2::utf8, rest::binary>> <- data, into: %{} do
{<<char1::utf8, char2::utf8>>, rest}
end
```
output:
```
%{"C€" => "11", "èü" => "00", "€ä" => "11"}
```
|
>
> I need to transform this list [into a] map...I tried with `Enum.map`.
>
>
>
You can also use [Enum.reduce](https://hexdocs.pm/elixir/Enum.html#reduce/3) instead of `Enum.map` when you want the result to be a map. The following example uses `Enum.reduce` and it can handle single byte `ASCII` characters as well as `UTF-8` (multi-byte) characters:
```
["AM00", "CC11", "CB11"]
initial value for acc variable
|
V
|> Enum.reduce(%{},
fn str, acc ->
{first_two, last_two} = String.split_at(str, 2)
Map.put(acc, first_two, last_two) # return the new value for acc
end
)
```
output:
```
%{"AM" => "00", "CB" => "11", "CC" => "11"}
```
And:
```
["èü00", "C€11", "€ä11"]
|> Enum.reduce(%{},
fn str, acc ->
{first_two, last_two} = String.split_at(str, 2)
Map.put(acc, first_two, last_two)
end
)
```
output:
```
%{"C€" => "11", "èü" => "00", "€ä" => "11"}
```
|
56,893,578
|
I am trying to make a python program(python 3.6) that writes commands to terminal to download a specific youtube video(using youtube-dl).
If I go on terminal and execute the following command:
```
cd; cd Desktop; youtube-dl "https://www.youtube.com/watch?v=b91ovTKCZGU"
```
It will download the video to my desktop. However, if I execute the below code, which should be doing the same command on terminal, it does not throw an error but also does not download that video.
```py
import subprocess
cmd = ["cd;", "cd", "Desktop;", "youtube-dl", "\"https://www.youtube.com/watch?v=b91ovTKCZGU\""]
print(subprocess.call(cmd, stderr=subprocess.STDOUT,shell=True))
```
It seems that this just outputs 0. I do not think there is any kind of error 0 that exists(there are error 126 and 127). So if it is not throwing an error, why does it also not download the video?
Update:
I have fixed the above code by passing in a string, and have checked that youtube-dl is installed in my default python and is also in the folder where I want to download the videos, but its still throwing error 127, meaning command "youtube-dl" is not found.
|
2019/07/04
|
[
"https://Stackoverflow.com/questions/56893578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11303221/"
] |
Binary pattern matching can dissect the string:
```
data = ["AM00", "CC11", "CB11"]
for <<key::binary-size(2), value::binary>> <- data, into: %{} do
{key, value}
end
```
output:
```
%{"AM" => "00", "CB" => "11", "CC" => "11"}
```
That only works for single byte characters.
To handle `UTF-8` characters as well as `ASCII` characters:
```
data = ["èü00", "C€11", "€ä11"]
for <<char1::utf8, char2::utf8, rest::binary>> <- data, into: %{} do
{<<char1::utf8, char2::utf8>>, rest}
end
```
output:
```
%{"C€" => "11", "èü" => "00", "€ä" => "11"}
```
|
I would do it with [`Map.new/2`](https://hexdocs.pm/elixir/Map.html#new/2) and [`String.split_at/2`](https://hexdocs.pm/elixir/String.html#split_at/2):
```elixir
Map.new(["AM00", "CC11", "CB11"], &String.split_at(&1, 2))
```
|
9,227,859
|
I'm using the code below (Python 2.7 and Python 3.2) to show an Open Files dialog that supports multiple-selection. On Linux filenames is a python list, but on Windows filenames is returned as `{C:/Documents and Settings/IE User/My Documents/VPC_EULA.txt} {C:/Documents and Settings/IE User/My Documents/VPC_ReadMe.txt}`, i.e. a raw TCL list.
Is this a python bug, and does anyone here know a good way to convert the raw TCL list into a python list?
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
else:
import tkFileDialog as filedialog
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
```
|
2012/02/10
|
[
"https://Stackoverflow.com/questions/9227859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94078/"
] |
The problem is an “interesting” interaction between Tcl, Tk and Python, each of which is doing something sensible on its own but where the combination isn't behaving correctly. The deep issue is that Tcl and Python have *very* different ideas about what types mean, and this is manifesting itself as a value that Tcl sees as a list but Python sees as a string (with the code in Tk assuming that it doesn't need to be careful to be clean for Python). Arguably the Python interface should use the fact that it can know that a Tcl list will be coming back from a multiple selection and hide this, but it doesn't so you're stuck.
I can (and should!) fix this in Tk, but I don't know how long it would take for the fix to find its way back to you that way.
---
[EDIT]: This is now fixed (with [this](https://core.tcl.tk/tk/vpatch?from=dfb108b671df7455&to=c309fddc73beb7b6) patch) in the Tk 8.5 maintenance branch and on the main development branch. I can't predict when you'll be able to get a fixed version unless you grab the source out of our fossil repository and build it yourself.
|
This fix works for me:
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
string_type = str
else:
import tkFileDialog as filedialog
string_type = basestring
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
if isinstance(filenames, string_type):
# tkinter is not converting the TCL list into a python list...
# see http://stackoverflow.com/questions/9227859/
#
# based on suggestion by Cameron Laird in http://bytes.com/topic/python/answers/536853-tcl-list-python-list
if sys.hexversion >= 0x030000F0:
import tkinter
else:
import Tkinter as tkinter
tk_eval = tkinter.Tk().tk.eval
tcl_list_length = int(tk_eval("set tcl_list {%s}; llength $tcl_list" % filenames))
filenames = [] # change to a list
for i in range(tcl_list_length):
filenames.append(tk_eval("lindex $tcl_list %d" % i))
return filenames
```
|
9,227,859
|
I'm using the code below (Python 2.7 and Python 3.2) to show an Open Files dialog that supports multiple-selection. On Linux filenames is a python list, but on Windows filenames is returned as `{C:/Documents and Settings/IE User/My Documents/VPC_EULA.txt} {C:/Documents and Settings/IE User/My Documents/VPC_ReadMe.txt}`, i.e. a raw TCL list.
Is this a python bug, and does anyone here know a good way to convert the raw TCL list into a python list?
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
else:
import tkFileDialog as filedialog
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
```
|
2012/02/10
|
[
"https://Stackoverflow.com/questions/9227859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94078/"
] |
The problem is an “interesting” interaction between Tcl, Tk and Python, each of which is doing something sensible on its own but where the combination isn't behaving correctly. The deep issue is that Tcl and Python have *very* different ideas about what types mean, and this is manifesting itself as a value that Tcl sees as a list but Python sees as a string (with the code in Tk assuming that it doesn't need to be careful to be clean for Python). Arguably the Python interface should use the fact that it can know that a Tcl list will be coming back from a multiple selection and hide this, but it doesn't so you're stuck.
I can (and should!) fix this in Tk, but I don't know how long it would take for the fix to find its way back to you that way.
---
[EDIT]: This is now fixed (with [this](https://core.tcl.tk/tk/vpatch?from=dfb108b671df7455&to=c309fddc73beb7b6) patch) in the Tk 8.5 maintenance branch and on the main development branch. I can't predict when you'll be able to get a fixed version unless you grab the source out of our fossil repository and build it yourself.
|
For some reason the tk\_eval based fix doesn't work for me. The filenames in the string returned by tkFileDialog are only wrapped in {} brackets if they contain whitespace, whereas the tcl docs seem to imply that all list items should be delimited by those brackets.
Anyway, here's a fix that seems to work for me (python 2.7.3 on windows 7):
```
def fixlist(filenames):
#do nothing if already a python list
if isinstance(filenames,list): return filenames
#http://docs.python.org/library/re.html
#the re should match: {text and white space in brackets} AND anynonwhitespacetokens
#*? is a non-greedy match for any character sequence
#\S is non white space
#split filenames string up into a proper python list
result = re.findall("{.*?}|\S+",filenames)
#remove any {} characters from the start and end of the file names
result = [ re.sub("^{|}$","",i) for i in result ]
return result
```
|
9,227,859
|
I'm using the code below (Python 2.7 and Python 3.2) to show an Open Files dialog that supports multiple-selection. On Linux filenames is a python list, but on Windows filenames is returned as `{C:/Documents and Settings/IE User/My Documents/VPC_EULA.txt} {C:/Documents and Settings/IE User/My Documents/VPC_ReadMe.txt}`, i.e. a raw TCL list.
Is this a python bug, and does anyone here know a good way to convert the raw TCL list into a python list?
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
else:
import tkFileDialog as filedialog
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
```
|
2012/02/10
|
[
"https://Stackoverflow.com/questions/9227859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94078/"
] |
The problem is an “interesting” interaction between Tcl, Tk and Python, each of which is doing something sensible on its own but where the combination isn't behaving correctly. The deep issue is that Tcl and Python have *very* different ideas about what types mean, and this is manifesting itself as a value that Tcl sees as a list but Python sees as a string (with the code in Tk assuming that it doesn't need to be careful to be clean for Python). Arguably the Python interface should use the fact that it can know that a Tcl list will be coming back from a multiple selection and hide this, but it doesn't so you're stuck.
I can (and should!) fix this in Tk, but I don't know how long it would take for the fix to find its way back to you that way.
---
[EDIT]: This is now fixed (with [this](https://core.tcl.tk/tk/vpatch?from=dfb108b671df7455&to=c309fddc73beb7b6) patch) in the Tk 8.5 maintenance branch and on the main development branch. I can't predict when you'll be able to get a fixed version unless you grab the source out of our fossil repository and build it yourself.
|
A quick way that I've used:
```
filenames = filenames.strip('{}').split('} {')
```
|
9,227,859
|
I'm using the code below (Python 2.7 and Python 3.2) to show an Open Files dialog that supports multiple-selection. On Linux filenames is a python list, but on Windows filenames is returned as `{C:/Documents and Settings/IE User/My Documents/VPC_EULA.txt} {C:/Documents and Settings/IE User/My Documents/VPC_ReadMe.txt}`, i.e. a raw TCL list.
Is this a python bug, and does anyone here know a good way to convert the raw TCL list into a python list?
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
else:
import tkFileDialog as filedialog
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
```
|
2012/02/10
|
[
"https://Stackoverflow.com/questions/9227859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94078/"
] |
For some reason the tk\_eval based fix doesn't work for me. The filenames in the string returned by tkFileDialog are only wrapped in {} brackets if they contain whitespace, whereas the tcl docs seem to imply that all list items should be delimited by those brackets.
Anyway, here's a fix that seems to work for me (python 2.7.3 on windows 7):
```
def fixlist(filenames):
#do nothing if already a python list
if isinstance(filenames,list): return filenames
#http://docs.python.org/library/re.html
#the re should match: {text and white space in brackets} AND anynonwhitespacetokens
#*? is a non-greedy match for any character sequence
#\S is non white space
#split filenames string up into a proper python list
result = re.findall("{.*?}|\S+",filenames)
#remove any {} characters from the start and end of the file names
result = [ re.sub("^{|}$","",i) for i in result ]
return result
```
|
This fix works for me:
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
string_type = str
else:
import tkFileDialog as filedialog
string_type = basestring
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
if isinstance(filenames, string_type):
# tkinter is not converting the TCL list into a python list...
# see http://stackoverflow.com/questions/9227859/
#
# based on suggestion by Cameron Laird in http://bytes.com/topic/python/answers/536853-tcl-list-python-list
if sys.hexversion >= 0x030000F0:
import tkinter
else:
import Tkinter as tkinter
tk_eval = tkinter.Tk().tk.eval
tcl_list_length = int(tk_eval("set tcl_list {%s}; llength $tcl_list" % filenames))
filenames = [] # change to a list
for i in range(tcl_list_length):
filenames.append(tk_eval("lindex $tcl_list %d" % i))
return filenames
```
|
9,227,859
|
I'm using the code below (Python 2.7 and Python 3.2) to show an Open Files dialog that supports multiple-selection. On Linux filenames is a python list, but on Windows filenames is returned as `{C:/Documents and Settings/IE User/My Documents/VPC_EULA.txt} {C:/Documents and Settings/IE User/My Documents/VPC_ReadMe.txt}`, i.e. a raw TCL list.
Is this a python bug, and does anyone here know a good way to convert the raw TCL list into a python list?
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
else:
import tkFileDialog as filedialog
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = filedialog.askopenfilename(**options)
```
|
2012/02/10
|
[
"https://Stackoverflow.com/questions/9227859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94078/"
] |
For some reason the tk\_eval based fix doesn't work for me. The filenames in the string returned by tkFileDialog are only wrapped in {} brackets if they contain whitespace, whereas the tcl docs seem to imply that all list items should be delimited by those brackets.
Anyway, here's a fix that seems to work for me (python 2.7.3 on windows 7):
```
def fixlist(filenames):
#do nothing if already a python list
if isinstance(filenames,list): return filenames
#http://docs.python.org/library/re.html
#the re should match: {text and white space in brackets} AND anynonwhitespacetokens
#*? is a non-greedy match for any character sequence
#\S is non white space
#split filenames string up into a proper python list
result = re.findall("{.*?}|\S+",filenames)
#remove any {} characters from the start and end of the file names
result = [ re.sub("^{|}$","",i) for i in result ]
return result
```
|
A quick way that I've used:
```
filenames = filenames.strip('{}').split('} {')
```
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
Here's a fix that worked for me on El Capitan that doesn't require restarting to work around the OS X El Capitan System Integrity Protection (SIP):
```
brew unlink postgresql && brew link postgresql
brew link --overwrite postgresql
```
[H/T Farhan Ahmad](http://www.thebitguru.com/blog/view/432-psycopg2%20on%20El%20Capitan)
|
well, I'd like to give my solution, the problem is related with the version of c. So, I just typed:
```
CFLAGS='-std=c99' pip install psycopg2==2.6.1
```
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
You need to replace the /usr/lib/libpq.5.dylib library because its version is too old.
Here's my solution to this problem:
```
$ sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
$ sudo ln -s /Library/PostgreSQL/9.4/lib/libpq.5.dylib /usr/lib
```
|
Here's a fix that worked for me on El Capitan that doesn't require restarting to work around the OS X El Capitan System Integrity Protection (SIP):
```
brew unlink postgresql && brew link postgresql
brew link --overwrite postgresql
```
[H/T Farhan Ahmad](http://www.thebitguru.com/blog/view/432-psycopg2%20on%20El%20Capitan)
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
You need to replace the /usr/lib/libpq.5.dylib library because its version is too old.
Here's my solution to this problem:
```
$ sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
$ sudo ln -s /Library/PostgreSQL/9.4/lib/libpq.5.dylib /usr/lib
```
|
In El Capitan, I used the same solution as @Forbze but 2 more commands as follows.
```
sudo install_name_tool -change libpq.5.dylib /Library/PostgreSQL/9.3/lib/libpq.5.dylib /Library/Python/2.7/site-packages/psycopg2/_psycopg.so
sudo install_name_tool -change libssl.1.0.0.dylib /Library/PostgreSQL/9.3/lib/libssl.1.0.0.dylib /Library/Python/2.7/site-packages/psycopg2/_psycopg.so
sudo install_name_tool -change libcrypto.1.0.0.dylib /Library/PostgreSQL/9.3/lib/libcrypto.1.0.0.dylib /Library/Python/2.7/site-packages/psycopg2/_psycopg.so
```
It works perfectly!
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
If you are using PostgresApp, you need to run the following two commands:
```
sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
sudo ln -s /Applications/Postgres.app/Contents/Versions/9.4/lib/libpq.5.dylib /usr/lib
```
|
well, I'd like to give my solution, the problem is related with the version of c. So, I just typed:
```
CFLAGS='-std=c99' pip install psycopg2==2.6.1
```
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
You need to replace the /usr/lib/libpq.5.dylib library because its version is too old.
Here's my solution to this problem:
```
$ sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
$ sudo ln -s /Library/PostgreSQL/9.4/lib/libpq.5.dylib /usr/lib
```
|
If you are using PostgresApp, you need to run the following two commands:
```
sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
sudo ln -s /Applications/Postgres.app/Contents/Versions/9.4/lib/libpq.5.dylib /usr/lib
```
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
I was able to fix this on my Mac (running Catalina, 10.15.3) by using psycopg2-binary rather than psycopg2.
`pip3 uninstall psycopg2
pip3 install psycopg2-binary`
|
Here's a fix that worked for me on El Capitan that doesn't require restarting to work around the OS X El Capitan System Integrity Protection (SIP):
```
brew unlink postgresql && brew link postgresql
brew link --overwrite postgresql
```
[H/T Farhan Ahmad](http://www.thebitguru.com/blog/view/432-psycopg2%20on%20El%20Capitan)
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
If you are using PostgresApp, you need to run the following two commands:
```
sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
sudo ln -s /Applications/Postgres.app/Contents/Versions/9.4/lib/libpq.5.dylib /usr/lib
```
|
Here's a fix that worked for me on El Capitan that doesn't require restarting to work around the OS X El Capitan System Integrity Protection (SIP):
```
brew unlink postgresql && brew link postgresql
brew link --overwrite postgresql
```
[H/T Farhan Ahmad](http://www.thebitguru.com/blog/view/432-psycopg2%20on%20El%20Capitan)
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
You need to replace the /usr/lib/libpq.5.dylib library because its version is too old.
Here's my solution to this problem:
```
$ sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
$ sudo ln -s /Library/PostgreSQL/9.4/lib/libpq.5.dylib /usr/lib
```
|
For those of you on El Capitan who can't use @KungFuLucky7's answer - I used the following to fix the issue (Adjust paths to match yours where required).
```
sudo install_name_tool -change libpq.5.dylib /Library/PostgreSQL/9.5/lib/libpq.5.dylib /usr/local/lib/python2.7/site-packages/psycopg2/_psycopg.so
```
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
I was able to fix this on my Mac (running Catalina, 10.15.3) by using psycopg2-binary rather than psycopg2.
`pip3 uninstall psycopg2
pip3 install psycopg2-binary`
|
For those of you on El Capitan who can't use @KungFuLucky7's answer - I used the following to fix the issue (Adjust paths to match yours where required).
```
sudo install_name_tool -change libpq.5.dylib /Library/PostgreSQL/9.5/lib/libpq.5.dylib /usr/local/lib/python2.7/site-packages/psycopg2/_psycopg.so
```
|
28,515,972
|
Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATH”`
2. When I import psycopg2 in my project i obtein:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Library libssl.1.0.0.dylib
> Library libcrypto.1.0.0.dylib
>
>
>
FIXED WITH:
`sudo ln -s /Library/PostgreSQL/9.4/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Library/PostgreSQL/9.4/lib/libcrypto.1.0.0.dylib /usr/lib`
3. Now I am obtaining:
>
> ImportError:
> dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so,
> 2): Symbol not found: \_lo\_lseek64 Referenced from:
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
> Expected in: /usr/lib/libpq.5.dylib in
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/psycopg2/\_psycopg.so
>
>
>
Can you help me?
|
2015/02/14
|
[
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] |
If you are using PostgresApp, you need to run the following two commands:
```
sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
sudo ln -s /Applications/Postgres.app/Contents/Versions/9.4/lib/libpq.5.dylib /usr/lib
```
|
For those of you on El Capitan who can't use @KungFuLucky7's answer - I used the following to fix the issue (Adjust paths to match yours where required).
```
sudo install_name_tool -change libpq.5.dylib /Library/PostgreSQL/9.5/lib/libpq.5.dylib /usr/local/lib/python2.7/site-packages/psycopg2/_psycopg.so
```
|
43,424,895
|
I have created a virtualenv using the following command:
`python3 -m venv --without-pip ./env_name`
I am now wondering if it is possible to add PIP to it manually.
|
2017/04/15
|
[
"https://Stackoverflow.com/questions/43424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] |
Once you opened the file, use this one-liner using `split` as you mentionned and nested list comprehension:
```
with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
```
* the inner listcomp splits & converts each line to integers (making an array of integers)
* the outer listcomp just iterates on the lines of the file
note that it will fail if there are something else than integers in your file.
(as a side note, `file` is a built-in in python 2, but not anymore in python 3, however I usually refrain from using it)
|
You can do like this,
```
[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
```
Line by line execution for more information
```
In [75]: print open('abc.txt').read()
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
```
`split` with newline.
```
In [76]: print open('abc.txt').read().split('\n')
['3 2 7 4', '', '1 8 9 3', '', '6 5 4 1', '', '1 0 8 7', '']
```
Remove the unnecessary null string.
```
In [77]: print filter(None,open('abc.txt').read().split('\n'))
['3 2 7 4', '1 8 9 3', '6 5 4 1', '1 0 8 7']
```
`split` with spaces
```
In [78]: print [i.split() for i in filter(None,open('abc.txt').read().split('\n'))]
[['3', '2', '7', '4'], ['1', '8', '9', '3'], ['6', '5', '4', '1'], ['1', '0', '8', '7']]
```
convert the element to `int`
```
In [79]: print [map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
[[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
```
|
43,424,895
|
I have created a virtualenv using the following command:
`python3 -m venv --without-pip ./env_name`
I am now wondering if it is possible to add PIP to it manually.
|
2017/04/15
|
[
"https://Stackoverflow.com/questions/43424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] |
Once you opened the file, use this one-liner using `split` as you mentionned and nested list comprehension:
```
with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
```
* the inner listcomp splits & converts each line to integers (making an array of integers)
* the outer listcomp just iterates on the lines of the file
note that it will fail if there are something else than integers in your file.
(as a side note, `file` is a built-in in python 2, but not anymore in python 3, however I usually refrain from using it)
|
The following uses a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) to create a list-of-lists. It reads each line from the file, splits it up using whitespace as a delimiter, uses the `map` function to create an iterator that returns the result of calling the `int` integer constructor on each of the string elements found in the line this way, and lastly creates a sub-list from that.
This process is repeated for each line in the file, each time resulting is a sub-list of the final list container object.
```
f = input("File name? ")
with open(f, encoding="UTF-8") as file:
data = [list(map(int, line.split())) for line in file]
print(data) # -> [[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
```
|
43,424,895
|
I have created a virtualenv using the following command:
`python3 -m venv --without-pip ./env_name`
I am now wondering if it is possible to add PIP to it manually.
|
2017/04/15
|
[
"https://Stackoverflow.com/questions/43424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] |
Once you opened the file, use this one-liner using `split` as you mentionned and nested list comprehension:
```
with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
```
* the inner listcomp splits & converts each line to integers (making an array of integers)
* the outer listcomp just iterates on the lines of the file
note that it will fail if there are something else than integers in your file.
(as a side note, `file` is a built-in in python 2, but not anymore in python 3, however I usually refrain from using it)
|
```
with open('intFile.txt') as f:
res = [[int(x) for x in line.split()] for line in f]
with open('intList.txt', 'w') as f:
f.write(str(res))
```
Adding to accepted answer. If you want to write that list to file, you need to open file and write as string as `write` only accepts string.
|
43,424,895
|
I have created a virtualenv using the following command:
`python3 -m venv --without-pip ./env_name`
I am now wondering if it is possible to add PIP to it manually.
|
2017/04/15
|
[
"https://Stackoverflow.com/questions/43424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] |
You can do like this,
```
[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
```
Line by line execution for more information
```
In [75]: print open('abc.txt').read()
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
```
`split` with newline.
```
In [76]: print open('abc.txt').read().split('\n')
['3 2 7 4', '', '1 8 9 3', '', '6 5 4 1', '', '1 0 8 7', '']
```
Remove the unnecessary null string.
```
In [77]: print filter(None,open('abc.txt').read().split('\n'))
['3 2 7 4', '1 8 9 3', '6 5 4 1', '1 0 8 7']
```
`split` with spaces
```
In [78]: print [i.split() for i in filter(None,open('abc.txt').read().split('\n'))]
[['3', '2', '7', '4'], ['1', '8', '9', '3'], ['6', '5', '4', '1'], ['1', '0', '8', '7']]
```
convert the element to `int`
```
In [79]: print [map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
[[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
```
|
```
with open('intFile.txt') as f:
res = [[int(x) for x in line.split()] for line in f]
with open('intList.txt', 'w') as f:
f.write(str(res))
```
Adding to accepted answer. If you want to write that list to file, you need to open file and write as string as `write` only accepts string.
|
43,424,895
|
I have created a virtualenv using the following command:
`python3 -m venv --without-pip ./env_name`
I am now wondering if it is possible to add PIP to it manually.
|
2017/04/15
|
[
"https://Stackoverflow.com/questions/43424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] |
The following uses a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) to create a list-of-lists. It reads each line from the file, splits it up using whitespace as a delimiter, uses the `map` function to create an iterator that returns the result of calling the `int` integer constructor on each of the string elements found in the line this way, and lastly creates a sub-list from that.
This process is repeated for each line in the file, each time resulting is a sub-list of the final list container object.
```
f = input("File name? ")
with open(f, encoding="UTF-8") as file:
data = [list(map(int, line.split())) for line in file]
print(data) # -> [[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
```
|
```
with open('intFile.txt') as f:
res = [[int(x) for x in line.split()] for line in f]
with open('intList.txt', 'w') as f:
f.write(str(res))
```
Adding to accepted answer. If you want to write that list to file, you need to open file and write as string as `write` only accepts string.
|
22,845,913
|
I am trying to implement a function to generate java hashCode equivalent in node.js and python to implement redis sharding. I am following the really good blog @below mentioned link to achieve this
<http://mechanics.flite.com/blog/2013/06/27/sharding-redis/>
But i am stuck at the difference in hashCode if string contains some characters which are not ascii as in below example. for regular strings i could get both node.js and python give me same hash code.
here is the code i am using to generate this:
--Python
```
def _java_hashcode(s):
hash_code = 0
for char in s:
hash_code = 31*h + ord(char)
return ctypes.c_int32(h).value
```
--Node as per above blog
```
String.prototype.hashCode = function() {
for(var ret = 0, i = 0, len = this.length; i < len; i++) {
ret = (31 * ret + this.charCodeAt(i)) << 0;
}
return ret;
};
```
--Python output
```
For string '者:s��2�*�=x�' hash is = 2014651066
For string '359196048149234' hash is = 1145341990
```
--Node output
```
For string '者:s��2�*�=x�' hash is = 150370768
For string '359196048149234' hash is = 1145341990
```
Please guide me, where am i mistaking.. do i need to set some type of encoding in python and node program, i tried a few but my program breaks in python.
|
2014/04/03
|
[
"https://Stackoverflow.com/questions/22845913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3230928/"
] |
```py
def java_string_hashcode(s):
"""Mimic Java's hashCode in python 2"""
try:
s = unicode(s)
except:
try:
s = unicode(s.decode('utf8'))
except:
raise Exception("Please enter a unicode type string or utf8 bytestring.")
h = 0
for c in s:
h = int((((31 * h + ord(c)) ^ 0x80000000) & 0xFFFFFFFF) - 0x80000000)
return h
```
This is how you should do it in python 2.
The problem is two fold:
* You should be using the unicode type, and make sure that it is so.
* After every step you need to prevent python from auto-converting to long type by using bitwise operations to get the correct int type for the following step. (swapping the sign bit, masking to 32 bit, then subtracting the amount of the sign bit will give us a negative int if the sign bit is present and a positive int when the sign bit is not present. This mimics the int behavior in Java.
Also, as in the other answer, for hard-coded non-ascii characters, please save your source file as utf8 and at the top of the file write:
```py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
```
And make sure if you receive user input that you handle them as unicode type and not string type. (not a problem for python 3)
|
Python 2 will assume ASCII encoding unless told otherwise. Since [PEP 0263](http://legacy.python.org/dev/peps/pep-0263/), you can specify utf-8 encoded strings with the following at the top of the file.
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
```
|
12,311,226
|
I am new to python and am having difficulties with an assignment for a class.
Here's my code:
```
print ('Plants for each semicircle garden: ',round(semiPlants,0))
```
Here's what gets printed:
```
('Plants for each semicircle garden:', 50.0)
```
As you see I am getting the parenthesis and apostrophes, which I do not want shown.
|
2012/09/07
|
[
"https://Stackoverflow.com/questions/12311226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1355158/"
] |
You're clearly using python2.x when you think you're using python3.x. In python 2.x, the stuff in the parenthesis is being interpreted as a `tuple`.
One fix is to use string formatting to do this:
```
print ( 'Plants for each semicircle garden: {0}'.format(round(semiPlants,0)))
```
which will work with python2.6 and onward (parenthesis around a single argument aren't interpreted as a `tuple`. To get a 1-tuple, you need to do `(some_object,)`)
|
You've tagged this question Python-3.x, but it looks like you are actually running your code with Python 2.
To see what version you're using, run, "python -V".
|
12,311,226
|
I am new to python and am having difficulties with an assignment for a class.
Here's my code:
```
print ('Plants for each semicircle garden: ',round(semiPlants,0))
```
Here's what gets printed:
```
('Plants for each semicircle garden:', 50.0)
```
As you see I am getting the parenthesis and apostrophes, which I do not want shown.
|
2012/09/07
|
[
"https://Stackoverflow.com/questions/12311226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1355158/"
] |
You're clearly using python2.x when you think you're using python3.x. In python 2.x, the stuff in the parenthesis is being interpreted as a `tuple`.
One fix is to use string formatting to do this:
```
print ( 'Plants for each semicircle garden: {0}'.format(round(semiPlants,0)))
```
which will work with python2.6 and onward (parenthesis around a single argument aren't interpreted as a `tuple`. To get a 1-tuple, you need to do `(some_object,)`)
|
Remove the parentheses as print is a statement, not a function in Python 2.x:
```
print 'Plants for each semicircle garden: ',round(semiPlants,0)
Plants for each simicircle garden: 50.0
```
|
57,169,454
|
My dataset is a set of 2 columns with Spanish and English sentences. I created a training dataset using the Dataset API using the below code:
```
train_examples = tf.data.experimental.CsvDataset("./Data/train.csv", [tf.string, tf.string])
val_examples = tf.data.experimental.CsvDataset("./Data/validation.csv", [tf.string, tf.string])
```
##Create a custom subwords tokenizer from the training dataset.
```
tokenizer_en = tfds.features.text.SubwordTextEncoder.build_from_corpus(
(en.numpy() for pt, en in train_examples), target_vocab_size=2**13)
tokenizer_pt = tfds.features.text.SubwordTextEncoder.build_from_corpus(
(pt.numpy() for pt, en in train_examples), target_vocab_size=2**13)
```
I am getting the following error:
```
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 30: invalid continuation byte
```
Traceback:
```
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-27-c90f5c60daf2> in <module>
1 tokenizer_en = tfds.features.text.SubwordTextEncoder.build_from_corpus(
----> 2 (en.numpy() for pt, en in train_examples), target_vocab_size=2**13)
3
4 tokenizer_pt = tfds.features.text.SubwordTextEncoder.build_from_corpus(
5 (pt.numpy() for pt, en in train_examples), target_vocab_size=2**13)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_datasets/core/features/text/subword_text_encoder.py in build_from_corpus(cls, corpus_generator, target_vocab_size, max_subword_length, max_corpus_chars, reserved_tokens)
291 generator=corpus_generator,
292 max_chars=max_corpus_chars,
--> 293 reserved_tokens=reserved_tokens)
294
295 # Binary search on the minimum token count to build a vocabulary with
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_datasets/core/features/text/subword_text_encoder.py in _token_counts_from_generator(generator, max_chars, reserved_tokens)
394 token_counts = collections.defaultdict(int)
395 for s in generator:
--> 396 s = tf.compat.as_text(s)
397 if max_chars and (num_chars + len(s)) >= max_chars:
398 s = s[:(max_chars - num_chars)]
~/venv/lib/python3.7/site-packages/tensorflow/python/util/compat.py in as_text(bytes_or_text, encoding)
85 return bytes_or_text
86 elif isinstance(bytes_or_text, bytes):
---> 87 return bytes_or_text.decode(encoding)
88 else:
89 raise TypeError('Expected binary or unicode string, got %r' % bytes_or_text)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 30: invalid continuation byte
```
|
2019/07/23
|
[
"https://Stackoverflow.com/questions/57169454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8382950/"
] |
You can perform ordering on the job\_set queryset, for example. Is something like this what you are looking for?
```
for worker in Worker.objects.all():
latest_job = worker.job_set.latest('start_date')
print(worker.name, latest_job.location, latest_job.start_date)
```
|
You can use the `last` method on the filtered and ordered (by `start_date`, in ascending order) queryset of a worker.
For example, if the name of the worker is `foobar`, you can do:
```
Job.objects.filter(worker__name='foobar').order_by('start_date').last()
```
this will give you the last `Job` (based on `start_date`) of the worker named `foobar`.
FWIW you can also get the `first` element if you're sorting in the descending order of `start_date`:
```
Job.objects.filter(worker__name='foobar').order_by('-start_date').first()
```
|
57,169,454
|
My dataset is a set of 2 columns with Spanish and English sentences. I created a training dataset using the Dataset API using the below code:
```
train_examples = tf.data.experimental.CsvDataset("./Data/train.csv", [tf.string, tf.string])
val_examples = tf.data.experimental.CsvDataset("./Data/validation.csv", [tf.string, tf.string])
```
##Create a custom subwords tokenizer from the training dataset.
```
tokenizer_en = tfds.features.text.SubwordTextEncoder.build_from_corpus(
(en.numpy() for pt, en in train_examples), target_vocab_size=2**13)
tokenizer_pt = tfds.features.text.SubwordTextEncoder.build_from_corpus(
(pt.numpy() for pt, en in train_examples), target_vocab_size=2**13)
```
I am getting the following error:
```
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 30: invalid continuation byte
```
Traceback:
```
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-27-c90f5c60daf2> in <module>
1 tokenizer_en = tfds.features.text.SubwordTextEncoder.build_from_corpus(
----> 2 (en.numpy() for pt, en in train_examples), target_vocab_size=2**13)
3
4 tokenizer_pt = tfds.features.text.SubwordTextEncoder.build_from_corpus(
5 (pt.numpy() for pt, en in train_examples), target_vocab_size=2**13)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_datasets/core/features/text/subword_text_encoder.py in build_from_corpus(cls, corpus_generator, target_vocab_size, max_subword_length, max_corpus_chars, reserved_tokens)
291 generator=corpus_generator,
292 max_chars=max_corpus_chars,
--> 293 reserved_tokens=reserved_tokens)
294
295 # Binary search on the minimum token count to build a vocabulary with
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_datasets/core/features/text/subword_text_encoder.py in _token_counts_from_generator(generator, max_chars, reserved_tokens)
394 token_counts = collections.defaultdict(int)
395 for s in generator:
--> 396 s = tf.compat.as_text(s)
397 if max_chars and (num_chars + len(s)) >= max_chars:
398 s = s[:(max_chars - num_chars)]
~/venv/lib/python3.7/site-packages/tensorflow/python/util/compat.py in as_text(bytes_or_text, encoding)
85 return bytes_or_text
86 elif isinstance(bytes_or_text, bytes):
---> 87 return bytes_or_text.decode(encoding)
88 else:
89 raise TypeError('Expected binary or unicode string, got %r' % bytes_or_text)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 30: invalid continuation byte
```
|
2019/07/23
|
[
"https://Stackoverflow.com/questions/57169454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8382950/"
] |
I think the other two answers are very simplistic. Both of them are tackling the problem you are trying to accomplish now, but these solutions will fail once you have more and more workers/jobs since all their solutions are O(N\*N). This solution is O(N).
```
subqry = models.Subquery(Job.objects.filter(worker_id=models.OuterRef('worker_id'))
.order_by('-start_date').values('id')[:1])
workers = Worker.objects.prefetch_related(models.Prefetch('job_set',
queryset=Job.objects.filter(id__in=subqry)))
for worker in workers:
# no matter what this will always have 1 // or nothing, depending on your logic; if nothing, fix this.
latest_job = list(worker.job_set.all())[0]
print(worker.name, latest_job.location, latest_job.start_date)
```
This will do a single query for `Worker` like the rest, BUT will only do a single query for the latest jobs, the other solutions will make a query PER worker, this is inefficient and slow.
See this example for more background as how i tested all this. <https://gist.github.com/kingbuzzman/ac2ada9c27196fc90c1b75f2d01a6271#file-django_prefetch_limit-py-L163>
|
You can use the `last` method on the filtered and ordered (by `start_date`, in ascending order) queryset of a worker.
For example, if the name of the worker is `foobar`, you can do:
```
Job.objects.filter(worker__name='foobar').order_by('start_date').last()
```
this will give you the last `Job` (based on `start_date`) of the worker named `foobar`.
FWIW you can also get the `first` element if you're sorting in the descending order of `start_date`:
```
Job.objects.filter(worker__name='foobar').order_by('-start_date').first()
```
|
1,043,735
|
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python?
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.
When giving someone a code, you can do the following to be *actually* secure.
(1) generate some random string.
(2) give them the string.
(3) save the hash of the string you generated.
Once.
If they "forget" the code, you have to (1) be sure they're authorized to be given the code, then (2) do the process again (generate a new code, give it to them, save the hash.)
|
If it's a web game, can't you store the codes server side and send them to the client when he completed a task? What's the architecture of your game?
As for encryption, maybe try something like [pyDes](http://twhiteman.netfirms.com/des.html)?
|
1,043,735
|
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python?
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
If it's a web game, can't you store the codes server side and send them to the client when he completed a task? What's the architecture of your game?
As for encryption, maybe try something like [pyDes](http://twhiteman.netfirms.com/des.html)?
|
Your question isn't quite clear. Where do you want the decryption to occur? One way or another, the plaintext has to surface since you need players to eventually know it.
Pick a [cipher](http://en.wikipedia.org/wiki/Stream_cipher) and be done with it.
|
1,043,735
|
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python?
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
If your script can decode the passwords, so can someone breaking in to your server. Encryption is only really useful when someone enters a password to unlock it - if it remains unlocked (or the script has the password to unlock it), the encryption is pointless
This is why hashing is more useful, since it is a one way process - even if someone knows your password hash, they don't know the plain-text they must enter to generate it (without lots of brute-force)
I wouldn't worry about keeping the game passwords as plain-text. If you are concerned about securing them, fix up possibly SQL injections/etc, make sure your web-server and other software is up to date and configured correctly and so on.
Perhaps think of a way to make it less appealing to steal the passwords than actually play the game? For example, there was a game (I don't recall what it was) which if you used the level skip cheat, you went to the next level but it didn't mark it as "complete", or you could skip the level but didn't get any points. Or look at Project Euler, you can do any level, but you only get points if you enter the answer (and working out the answer is the whole point of the game, so cheating defeats the playing of the game)
If you are really paranoid, you could *possibly* use asymmetric crypto, where you basically encrypt something with `key A`, and you can only read it with `key B`..
I came up with an similar concept for using GPG encryption (popular asymmetric crypto system, mainly used for email encryption or signing) [to secure website data](http://neverfear.org/blog/view/Secure_website_authentication_using_GPG_keys). I'm not quite sure how this would apply to securing game level passwords, and as I said, you'd need to be really paranoid to even consider this..
In short, I'd say store the passwords in plain-text, and concentrate your security-concerns elsewhere (the web applications code itself)
|
If it's a web game, can't you store the codes server side and send them to the client when he completed a task? What's the architecture of your game?
As for encryption, maybe try something like [pyDes](http://twhiteman.netfirms.com/des.html)?
|
1,043,735
|
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python?
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.
When giving someone a code, you can do the following to be *actually* secure.
(1) generate some random string.
(2) give them the string.
(3) save the hash of the string you generated.
Once.
If they "forget" the code, you have to (1) be sure they're authorized to be given the code, then (2) do the process again (generate a new code, give it to them, save the hash.)
|
Your question isn't quite clear. Where do you want the decryption to occur? One way or another, the plaintext has to surface since you need players to eventually know it.
Pick a [cipher](http://en.wikipedia.org/wiki/Stream_cipher) and be done with it.
|
1,043,735
|
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python?
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
If your script can decode the passwords, so can someone breaking in to your server. Encryption is only really useful when someone enters a password to unlock it - if it remains unlocked (or the script has the password to unlock it), the encryption is pointless
This is why hashing is more useful, since it is a one way process - even if someone knows your password hash, they don't know the plain-text they must enter to generate it (without lots of brute-force)
I wouldn't worry about keeping the game passwords as plain-text. If you are concerned about securing them, fix up possibly SQL injections/etc, make sure your web-server and other software is up to date and configured correctly and so on.
Perhaps think of a way to make it less appealing to steal the passwords than actually play the game? For example, there was a game (I don't recall what it was) which if you used the level skip cheat, you went to the next level but it didn't mark it as "complete", or you could skip the level but didn't get any points. Or look at Project Euler, you can do any level, but you only get points if you enter the answer (and working out the answer is the whole point of the game, so cheating defeats the playing of the game)
If you are really paranoid, you could *possibly* use asymmetric crypto, where you basically encrypt something with `key A`, and you can only read it with `key B`..
I came up with an similar concept for using GPG encryption (popular asymmetric crypto system, mainly used for email encryption or signing) [to secure website data](http://neverfear.org/blog/view/Secure_website_authentication_using_GPG_keys). I'm not quite sure how this would apply to securing game level passwords, and as I said, you'd need to be really paranoid to even consider this..
In short, I'd say store the passwords in plain-text, and concentrate your security-concerns elsewhere (the web applications code itself)
|
The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.
When giving someone a code, you can do the following to be *actually* secure.
(1) generate some random string.
(2) give them the string.
(3) save the hash of the string you generated.
Once.
If they "forget" the code, you have to (1) be sure they're authorized to be given the code, then (2) do the process again (generate a new code, give it to them, save the hash.)
|
1,043,735
|
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python?
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
If your script can decode the passwords, so can someone breaking in to your server. Encryption is only really useful when someone enters a password to unlock it - if it remains unlocked (or the script has the password to unlock it), the encryption is pointless
This is why hashing is more useful, since it is a one way process - even if someone knows your password hash, they don't know the plain-text they must enter to generate it (without lots of brute-force)
I wouldn't worry about keeping the game passwords as plain-text. If you are concerned about securing them, fix up possibly SQL injections/etc, make sure your web-server and other software is up to date and configured correctly and so on.
Perhaps think of a way to make it less appealing to steal the passwords than actually play the game? For example, there was a game (I don't recall what it was) which if you used the level skip cheat, you went to the next level but it didn't mark it as "complete", or you could skip the level but didn't get any points. Or look at Project Euler, you can do any level, but you only get points if you enter the answer (and working out the answer is the whole point of the game, so cheating defeats the playing of the game)
If you are really paranoid, you could *possibly* use asymmetric crypto, where you basically encrypt something with `key A`, and you can only read it with `key B`..
I came up with an similar concept for using GPG encryption (popular asymmetric crypto system, mainly used for email encryption or signing) [to secure website data](http://neverfear.org/blog/view/Secure_website_authentication_using_GPG_keys). I'm not quite sure how this would apply to securing game level passwords, and as I said, you'd need to be really paranoid to even consider this..
In short, I'd say store the passwords in plain-text, and concentrate your security-concerns elsewhere (the web applications code itself)
|
Your question isn't quite clear. Where do you want the decryption to occur? One way or another, the plaintext has to surface since you need players to eventually know it.
Pick a [cipher](http://en.wikipedia.org/wiki/Stream_cipher) and be done with it.
|
24,497,121
|
I ask because the examples in the Facebook Ads API (<https://developers.facebook.com/docs/reference/ads-api/adimage/#create>) for creating an Ad Image all use curl, but I want to do it with python requests. Or if someone can answer the more specific question of how to create an Ad Image on the Facebook Ads API from python, that'd be great as well. You can assume I have the location on disk of the image file to upload. Should be a simple POST request to the endpoint /act\_[account\_id]/adimages, right?
|
2014/06/30
|
[
"https://Stackoverflow.com/questions/24497121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3391108/"
] |
Try `Holders.grailsApplication.config`:
```
@TestMixin(GrailsUnitTestMixin)
class TicketRequestEmailInfoSpec extends Specification {
def setup() {
Holders.grailsApplication.config.acme.purchase.trsUrlBase = "http://localhost:8082/purchase/order/"
}
```
|
Didn't works injecting `grailsApplication` to test as `def grailsApplication` ?
Also you can import it as `import static grails.util.Holders.config as grailsConfig`.
And then use it as
```
@TestMixin(GrailsUnitTestMixin)
class TicketRequestEmailInfoSpec extends Specification {
def setup() {
grailsConfig.acme.purchase.trsUrlBase = "http://localhost:8082/purchase/order/"
}
```
|
55,582,117
|
GIMP has a convenient function that allows you to convert an arbitrary color to an alpha channel.
Essentially all pixels become transparent relative to how far away from the chosen color they are.
I want to replicate this functionality with opencv.
I tried iterating through the image:
```
for x in range(rows):
for y in range(cols):
mask_img[y, x][3] = cv2.norm(img[y, x] - (255, 255, 255, 255))
```
But this is prohibitively expensive, it takes about 10 times longer to do that iteration than it takes to simply set the field to 0 (6 minutes vs an hour)
This seems more a python problem than an algorithmic problem. I have done similar things in C++ and it's not as as bad in terms of performance.
Does anyone have suggestions on achieving this?
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55582117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6202327/"
] |
Here is my attempt only using `numpy` matrix operations.
My input image `colortrans.png` looks like this:
[](https://i.stack.imgur.com/l1ZPc.png)
I want to make the diagonal purple part `(128, 0, 128)` transparent with some tolerance `+/- (25, 0, 25)` to the left and right, resulting in some transparency gradient.
Here comes the code:
```py
import cv2
import numpy as np
# Input image
input = cv2.imread('images/colortrans.png', cv2.IMREAD_COLOR)
# Convert to RGB with alpha channel
output = cv2.cvtColor(input, cv2.COLOR_BGR2RGBA)
# Color to make transparent
col = (128, 0, 128)
# Color tolerance
tol = (25, 0, 25)
# Temporary array (subtract color)
temp = np.subtract(input, col)
# Tolerance mask
mask = (np.abs(temp) <= tol)
mask = (mask[:, :, 0] & mask[:, :, 1] & mask[:, :, 2])
# Generate alpha channel
temp[temp < 0] = 0 # Remove negative values
alpha = (temp[:, :, 0] + temp[:, :, 1] + temp[:, :, 2]) / 3 # Generate mean gradient over all channels
alpha[mask] = alpha[mask] / np.max(alpha[mask]) * 255 # Gradual transparency within tolerance mask
alpha[~mask] = 255 # No transparency outside tolerance mask
# Set alpha channel in output
output[:, :, 3] = alpha
# Output images
cv2.imwrite('images/colortrans_alpha.png', alpha)
cv2.imwrite('images/colortrans_output.png', output)
```
The resulting alpha channel `colortrans_alpha.png` looks like this:
[](https://i.stack.imgur.com/K4EHh.png)
And, the final output image `colortrans_output.png` looks like this:
[](https://i.stack.imgur.com/k9AAN.png)
Is that, what you wanted to achieve?
|
I've done a project that converted all pixels that are close to white into transparent pixels using the `PIL` (python image library) module. I'm not sure how to implement your algorithm for "relative to how far away from chosen color they are", but my code looks like:
```
from PIL import Image
planeIm = Image.open('InputImage.png')
planeIm = planeIm.convert('RGBA')
datas = planeIm.getdata()
newData = []
for item in datas:
if item[0] > 240 and item[1] > 240 and item[2] > 240:
newData.append((255, 255, 255, 0)) # transparent pixel
else:
newData.append(item) # unedited pixel
planeIm.putdata(newData)
planeIm.save('output.png', "PNG")
```
This goes through a 1920 X 1080 image for me in 1.605 seconds, so maybe if you implement your logic into this you will see the speed improvements you want?
It might be even faster if `newData` is initialized instead of being `.append()`ed every time too! Something like:
```
planeIm = Image.open('EGGW spider.png')
planeIm = planeIm.convert('RGBA')
datas = planeIm.getdata()
newData = [(255, 255, 255, 0)] * len(datas)
for i in range(len(datas)):
if datas[i][0] > 240 and datas[i][1] > 240 and datas[i][2] > 240:
pass # we already have (255, 255, 255, 0) there
else:
newData[i] = datas[i]
planeIm.putdata(newData)
planeIm.save('output.png', "PNG")
```
Although for me this second approach runs at 2.067 seconds...
multithreading
==============
An example of threading to calculate a different image would look like:
```
from PIL import Image
from threading import Thread
from queue import Queue
import time
start = time.time()
q = Queue()
planeIm = Image.open('InputImage.png')
planeIm = planeIm.convert('RGBA')
datas = planeIm.getdata()
new_data = [0] * len(datas)
print('putting image into queue')
for count, item in enumerate(datas):
q.put((count, item))
def worker_function():
while True:
# print("Items in queue: {}".format(q.qsize()))
index, pixel = q.get()
if pixel[0] > 240 and pixel[1] > 240 and pixel[2] > 240:
out_pixel = (0, 0, 0, 0)
else:
out_pixel = pixel
new_data[index] = out_pixel
q.task_done()
print('starting workers')
worker_count = 100
for i in range(worker_count):
t = Thread(target=worker_function)
t.daemon = True
t.start()
print('main thread waiting')
q.join()
print('Queue has been joined')
planeIm.putdata(new_data)
planeIm.save('output.png', "PNG")
end = time.time()
elapsed = end - start
print('{:3.3} seconds elapsed'.format(elapsed))
```
Which for me now takes 58.1 seconds! A terrible speed difference! I would attribute this to:
* Having to iterate each pixel twice, once to put it into a queue and once to process it and write it to the `new_data` list.
* The overhead needed to create threads. Each new thread will take a few ms to create, so making a large amount (100 in this case) can add up.
* A simple algorithm was used to modify the pixels, threading would shine when large amounts of computation are required on each input (more like your case)
* Threading doesn't utilize multiple cores, you need multi*processing* to get that -> my task manager says I was only using 10% of my CPU and it idles at 1-2% already...
|
55,582,117
|
GIMP has a convenient function that allows you to convert an arbitrary color to an alpha channel.
Essentially all pixels become transparent relative to how far away from the chosen color they are.
I want to replicate this functionality with opencv.
I tried iterating through the image:
```
for x in range(rows):
for y in range(cols):
mask_img[y, x][3] = cv2.norm(img[y, x] - (255, 255, 255, 255))
```
But this is prohibitively expensive, it takes about 10 times longer to do that iteration than it takes to simply set the field to 0 (6 minutes vs an hour)
This seems more a python problem than an algorithmic problem. I have done similar things in C++ and it's not as as bad in terms of performance.
Does anyone have suggestions on achieving this?
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55582117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6202327/"
] |
I've done a project that converted all pixels that are close to white into transparent pixels using the `PIL` (python image library) module. I'm not sure how to implement your algorithm for "relative to how far away from chosen color they are", but my code looks like:
```
from PIL import Image
planeIm = Image.open('InputImage.png')
planeIm = planeIm.convert('RGBA')
datas = planeIm.getdata()
newData = []
for item in datas:
if item[0] > 240 and item[1] > 240 and item[2] > 240:
newData.append((255, 255, 255, 0)) # transparent pixel
else:
newData.append(item) # unedited pixel
planeIm.putdata(newData)
planeIm.save('output.png', "PNG")
```
This goes through a 1920 X 1080 image for me in 1.605 seconds, so maybe if you implement your logic into this you will see the speed improvements you want?
It might be even faster if `newData` is initialized instead of being `.append()`ed every time too! Something like:
```
planeIm = Image.open('EGGW spider.png')
planeIm = planeIm.convert('RGBA')
datas = planeIm.getdata()
newData = [(255, 255, 255, 0)] * len(datas)
for i in range(len(datas)):
if datas[i][0] > 240 and datas[i][1] > 240 and datas[i][2] > 240:
pass # we already have (255, 255, 255, 0) there
else:
newData[i] = datas[i]
planeIm.putdata(newData)
planeIm.save('output.png', "PNG")
```
Although for me this second approach runs at 2.067 seconds...
multithreading
==============
An example of threading to calculate a different image would look like:
```
from PIL import Image
from threading import Thread
from queue import Queue
import time
start = time.time()
q = Queue()
planeIm = Image.open('InputImage.png')
planeIm = planeIm.convert('RGBA')
datas = planeIm.getdata()
new_data = [0] * len(datas)
print('putting image into queue')
for count, item in enumerate(datas):
q.put((count, item))
def worker_function():
while True:
# print("Items in queue: {}".format(q.qsize()))
index, pixel = q.get()
if pixel[0] > 240 and pixel[1] > 240 and pixel[2] > 240:
out_pixel = (0, 0, 0, 0)
else:
out_pixel = pixel
new_data[index] = out_pixel
q.task_done()
print('starting workers')
worker_count = 100
for i in range(worker_count):
t = Thread(target=worker_function)
t.daemon = True
t.start()
print('main thread waiting')
q.join()
print('Queue has been joined')
planeIm.putdata(new_data)
planeIm.save('output.png', "PNG")
end = time.time()
elapsed = end - start
print('{:3.3} seconds elapsed'.format(elapsed))
```
Which for me now takes 58.1 seconds! A terrible speed difference! I would attribute this to:
* Having to iterate each pixel twice, once to put it into a queue and once to process it and write it to the `new_data` list.
* The overhead needed to create threads. Each new thread will take a few ms to create, so making a large amount (100 in this case) can add up.
* A simple algorithm was used to modify the pixels, threading would shine when large amounts of computation are required on each input (more like your case)
* Threading doesn't utilize multiple cores, you need multi*processing* to get that -> my task manager says I was only using 10% of my CPU and it idles at 1-2% already...
|
Remove white background
=======================
Here is an efficent way to remove white background. You can change the `np.argwhere` condition to select a specific color.
```
image = Image.open(in_pth)
# convert image to numpy array
transparent_img = np.ones((480,640,4),dtype=np.uint8) * 255
transparent_img[:,:,:3] = np.asarray(image)
white_idx = np.argwhere(np.sum(transparent_img, axis=-1) > 1000)
transparent_img[white_idx[:,0],white_idx[:,1],-1] = 0
```
|
55,582,117
|
GIMP has a convenient function that allows you to convert an arbitrary color to an alpha channel.
Essentially all pixels become transparent relative to how far away from the chosen color they are.
I want to replicate this functionality with opencv.
I tried iterating through the image:
```
for x in range(rows):
for y in range(cols):
mask_img[y, x][3] = cv2.norm(img[y, x] - (255, 255, 255, 255))
```
But this is prohibitively expensive, it takes about 10 times longer to do that iteration than it takes to simply set the field to 0 (6 minutes vs an hour)
This seems more a python problem than an algorithmic problem. I have done similar things in C++ and it's not as as bad in terms of performance.
Does anyone have suggestions on achieving this?
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55582117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6202327/"
] |
Here is my attempt only using `numpy` matrix operations.
My input image `colortrans.png` looks like this:
[](https://i.stack.imgur.com/l1ZPc.png)
I want to make the diagonal purple part `(128, 0, 128)` transparent with some tolerance `+/- (25, 0, 25)` to the left and right, resulting in some transparency gradient.
Here comes the code:
```py
import cv2
import numpy as np
# Input image
input = cv2.imread('images/colortrans.png', cv2.IMREAD_COLOR)
# Convert to RGB with alpha channel
output = cv2.cvtColor(input, cv2.COLOR_BGR2RGBA)
# Color to make transparent
col = (128, 0, 128)
# Color tolerance
tol = (25, 0, 25)
# Temporary array (subtract color)
temp = np.subtract(input, col)
# Tolerance mask
mask = (np.abs(temp) <= tol)
mask = (mask[:, :, 0] & mask[:, :, 1] & mask[:, :, 2])
# Generate alpha channel
temp[temp < 0] = 0 # Remove negative values
alpha = (temp[:, :, 0] + temp[:, :, 1] + temp[:, :, 2]) / 3 # Generate mean gradient over all channels
alpha[mask] = alpha[mask] / np.max(alpha[mask]) * 255 # Gradual transparency within tolerance mask
alpha[~mask] = 255 # No transparency outside tolerance mask
# Set alpha channel in output
output[:, :, 3] = alpha
# Output images
cv2.imwrite('images/colortrans_alpha.png', alpha)
cv2.imwrite('images/colortrans_output.png', output)
```
The resulting alpha channel `colortrans_alpha.png` looks like this:
[](https://i.stack.imgur.com/K4EHh.png)
And, the final output image `colortrans_output.png` looks like this:
[](https://i.stack.imgur.com/k9AAN.png)
Is that, what you wanted to achieve?
|
I had a go using [pyvips](https://pypi.org/project/pyvips/).
This version calculates the pythagorean distance between each RGB pixel in your file and the target colour, then makes an alpha by scaling that distance metric by a tolerance.
```
import sys
import pyvips
image = pyvips.Image.new_from_file(sys.argv[1], access='sequential')
# Color to make transparent
col = [128, 0, 128]
# Tolerance ... ie., how close to target before we become solid
tol = 25
# for each pixel, pythagorean distance from target colour
d = sum(((image - col) ** 2).bandsplit()) ** 0.5
# scale d so that distances > tol become 255
alpha = 255 * d / tol
# attach the alpha and save
image.bandjoin(alpha).write_to_file(sys.argv[2])
```
On @HansHirse's nice test image:
[](https://i.stack.imgur.com/11zQI.png)
I can run it like this:
```
$ ./mktrans.py ~/pics/colortrans.png x.png
```
To make:
[](https://i.stack.imgur.com/Pjfst.png)
To test speed, I tried on a 1920x1080 pixel jpg:
```
$ time ./mktrans.py ~/pics/horse1920x1080.jpg x.png
real 0m0.708s
user 0m1.020s
sys 0m0.029s
```
So 0.7s on this two-core 2015 laptop.
|
55,582,117
|
GIMP has a convenient function that allows you to convert an arbitrary color to an alpha channel.
Essentially all pixels become transparent relative to how far away from the chosen color they are.
I want to replicate this functionality with opencv.
I tried iterating through the image:
```
for x in range(rows):
for y in range(cols):
mask_img[y, x][3] = cv2.norm(img[y, x] - (255, 255, 255, 255))
```
But this is prohibitively expensive, it takes about 10 times longer to do that iteration than it takes to simply set the field to 0 (6 minutes vs an hour)
This seems more a python problem than an algorithmic problem. I have done similar things in C++ and it's not as as bad in terms of performance.
Does anyone have suggestions on achieving this?
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55582117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6202327/"
] |
Here is my attempt only using `numpy` matrix operations.
My input image `colortrans.png` looks like this:
[](https://i.stack.imgur.com/l1ZPc.png)
I want to make the diagonal purple part `(128, 0, 128)` transparent with some tolerance `+/- (25, 0, 25)` to the left and right, resulting in some transparency gradient.
Here comes the code:
```py
import cv2
import numpy as np
# Input image
input = cv2.imread('images/colortrans.png', cv2.IMREAD_COLOR)
# Convert to RGB with alpha channel
output = cv2.cvtColor(input, cv2.COLOR_BGR2RGBA)
# Color to make transparent
col = (128, 0, 128)
# Color tolerance
tol = (25, 0, 25)
# Temporary array (subtract color)
temp = np.subtract(input, col)
# Tolerance mask
mask = (np.abs(temp) <= tol)
mask = (mask[:, :, 0] & mask[:, :, 1] & mask[:, :, 2])
# Generate alpha channel
temp[temp < 0] = 0 # Remove negative values
alpha = (temp[:, :, 0] + temp[:, :, 1] + temp[:, :, 2]) / 3 # Generate mean gradient over all channels
alpha[mask] = alpha[mask] / np.max(alpha[mask]) * 255 # Gradual transparency within tolerance mask
alpha[~mask] = 255 # No transparency outside tolerance mask
# Set alpha channel in output
output[:, :, 3] = alpha
# Output images
cv2.imwrite('images/colortrans_alpha.png', alpha)
cv2.imwrite('images/colortrans_output.png', output)
```
The resulting alpha channel `colortrans_alpha.png` looks like this:
[](https://i.stack.imgur.com/K4EHh.png)
And, the final output image `colortrans_output.png` looks like this:
[](https://i.stack.imgur.com/k9AAN.png)
Is that, what you wanted to achieve?
|
Remove white background
=======================
Here is an efficent way to remove white background. You can change the `np.argwhere` condition to select a specific color.
```
image = Image.open(in_pth)
# convert image to numpy array
transparent_img = np.ones((480,640,4),dtype=np.uint8) * 255
transparent_img[:,:,:3] = np.asarray(image)
white_idx = np.argwhere(np.sum(transparent_img, axis=-1) > 1000)
transparent_img[white_idx[:,0],white_idx[:,1],-1] = 0
```
|
55,582,117
|
GIMP has a convenient function that allows you to convert an arbitrary color to an alpha channel.
Essentially all pixels become transparent relative to how far away from the chosen color they are.
I want to replicate this functionality with opencv.
I tried iterating through the image:
```
for x in range(rows):
for y in range(cols):
mask_img[y, x][3] = cv2.norm(img[y, x] - (255, 255, 255, 255))
```
But this is prohibitively expensive, it takes about 10 times longer to do that iteration than it takes to simply set the field to 0 (6 minutes vs an hour)
This seems more a python problem than an algorithmic problem. I have done similar things in C++ and it's not as as bad in terms of performance.
Does anyone have suggestions on achieving this?
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55582117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6202327/"
] |
I had a go using [pyvips](https://pypi.org/project/pyvips/).
This version calculates the pythagorean distance between each RGB pixel in your file and the target colour, then makes an alpha by scaling that distance metric by a tolerance.
```
import sys
import pyvips
image = pyvips.Image.new_from_file(sys.argv[1], access='sequential')
# Color to make transparent
col = [128, 0, 128]
# Tolerance ... ie., how close to target before we become solid
tol = 25
# for each pixel, pythagorean distance from target colour
d = sum(((image - col) ** 2).bandsplit()) ** 0.5
# scale d so that distances > tol become 255
alpha = 255 * d / tol
# attach the alpha and save
image.bandjoin(alpha).write_to_file(sys.argv[2])
```
On @HansHirse's nice test image:
[](https://i.stack.imgur.com/11zQI.png)
I can run it like this:
```
$ ./mktrans.py ~/pics/colortrans.png x.png
```
To make:
[](https://i.stack.imgur.com/Pjfst.png)
To test speed, I tried on a 1920x1080 pixel jpg:
```
$ time ./mktrans.py ~/pics/horse1920x1080.jpg x.png
real 0m0.708s
user 0m1.020s
sys 0m0.029s
```
So 0.7s on this two-core 2015 laptop.
|
Remove white background
=======================
Here is an efficent way to remove white background. You can change the `np.argwhere` condition to select a specific color.
```
image = Image.open(in_pth)
# convert image to numpy array
transparent_img = np.ones((480,640,4),dtype=np.uint8) * 255
transparent_img[:,:,:3] = np.asarray(image)
white_idx = np.argwhere(np.sum(transparent_img, axis=-1) > 1000)
transparent_img[white_idx[:,0],white_idx[:,1],-1] = 0
```
|
11,483,366
|
>
> **Possible Duplicate:**
>
> [Making a method private in a python subclass](https://stackoverflow.com/questions/451963/making-a-method-private-in-a-python-subclass)
>
> [Private Variables and Methods in Python](https://stackoverflow.com/questions/3385317/private-variables-and-methods-in-python)
>
>
>
How can I define a method in a python class that is protected and only subclasses can see it?
This is my code:
```
class BaseType(Model):
def __init__(self):
Model.__init__(self, self.__defaults())
def __defaults(self):
return {'name': {},
'readonly': {},
'constraints': {'value': UniqueMap()},
'cType': {}
}
cType = property(lambda self: self.getAttribute("cType"), lambda self, data: self.setAttribute('cType', data))
name = property(lambda self: self.getAttribute("name"), lambda self, data: self.setAttribute('name', data))
readonly = property(lambda self: self.getAttribute("readonly"),
lambda self, data: self.setAttribute('readonly', data))
constraints = property(lambda self: self.getAttribute("constraints"))
def getJsCode(self):
pass
def getCsCode(self):
pass
def generateCsCode(self, template=None, constraintMap=None, **kwargs):
if not template:
template = self.csTemplate
if not constraintMap: constraintMap = {}
atts = ""
constraintMap.update(constraintMap)
for element in self.getNoneEmptyAttributes():
if not AbstractType.constraintMap.has_key(element[0].lower()):
continue
attTemplate = Template(AbstractType.constraintMap[element[0].lower()]['cs'])
attValue = str(element[1]['value'])
atts += "%s " % attTemplate.substitute({'value': attValue})
kwargs.update(dict(attributes=atts))
return template.substitute(kwargs)
class MainClass(BaseType, Model):
def __init__(self):
#Only Model will initialize
Model.__init__(self, self.__defaults())
BaseType.__init__(self)
def __defaults(self):
return {'name': {},
'fields': {'value': UniqueMap()},
'innerClass': {'value': UniqueMap()},
'types': {}
}
fields = property(lambda self: self.getAttribute("fields"))
innerClass = property(lambda self: self.getAttribute("innerClass"))
types = property(lambda self: self.getAttribute("types"))
@staticmethod
def isType(iType):
# return type(widget) in WidgetSelector.widgets.itervalues()
return isinstance(iType, AbstractType)
def addType(self, type):
if not MainClass.isType(type):
raise Exception, "Unknown widget type %s" % type
self.types[type.name] = type
```
I want that just subclasses of `BaseType` see the `generateCsCode` method of `BaseType`.
|
2012/07/14
|
[
"https://Stackoverflow.com/questions/11483366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254709/"
] |
Python does not support access protection as C++/Java/C# does. Everything is public. The motto is, "We're all adults here." Document your classes, and insist that your collaborators read and follow the documentation.
The culture in Python is that names starting with underscores mean, "don't use these unless you really know you should." You might choose to begin your "protected" methods with underscores. But keep in mind, this is just a convention, it doesn't change how the method can be accessed.
Names beginning with double underscores (`__name`) are mangled, so that inheritance hierarchies can be built without fear of name collisions. Some people use these for "private" methods, but again, it doesn't change how the method can be accessed.
The best strategy is to get used to a model where all the code in a single process has to be written to get along.
|
You can't. Python intentionally does not support access control. By convention, methods starting with an underscore are private, and you should clearly state in the documentation who is supposed to use the method.
|
30,061,620
|
I am calculating Euclidean Distance with python code below:
```
def getNeighbors(trainingSet, testInstance, k, labels):
distances = []
for x in range(len(trainingSet)):
dist = math.sqrt(((testInstance[0] - trainingSet[x][0]) ** 2) + ((testInstance[1] - trainingSet[x][1]) ** 2))
distances.append([dist, labels[x]])
distances = np.array(distances)
return distances
```
For calculating distance of a given point with 10 other points, it's good. But when I calculate distance of a point with 18563 other points, then the computer gets hanged and don't response for around 3 Hrs.
**How can I make calculation for** 18563 **points faster?**
|
2015/05/05
|
[
"https://Stackoverflow.com/questions/30061620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831683/"
] |
You can speed this up by converting to NumPy first, then using vector operations, instead of doing the work in a loop, then converting to NumPy. Something like this:
```
trainingArray = np.array(trainingSet)
distances = ((testInstance[0] - trainingArray[:, 0]) ** 2 +
(testInstance[1] - trainingArray[:, 1]) ** 2).sqrt()
```
(That's obviously untested, because without enough context to know what's actually in those variables I had to guess, but it will be something close to that.)
There are other things you can do to squeeze out a few extra %—try replacing the `** 2` with self-multiplication or the `sqrt` with `** .5`, or (probably best) replacing the whole thing with `np.hypot`. (If you don't know how to use [`timeit`](https://docs.python.org/3/library/timeit.html)—or, even better, IPython and it's `%timeit` magic—now is a great time to learn.)
But ultimately, this is just going to give you a constant-multiplier speedup of about an order of magnitude. Maybe it takes 15 minutes instead of 3 hours. That's nice, but… why is it taking 3 hours in the first place? What you're doing here should be taking on the order of seconds, or even less. There's clearly something much bigger wrong here, like maybe you're calling this function N\*\*2 times when you think you're only calling it once. And you really need to fix that part.
Of course it's still worth doing this. First, element-wise operations are simpler and more readable than loops, and harder to get wrong. Second, even if you reduce the whole program to 3.8 seconds, you'll be happy for the order-of-magnitude speedup to 0.38 seconds, right?
|
Writing own sqrt calculator has its own risks, hypot is very safe for resistance to overflow and underflow
```py
x_y = np.array(trainingSet)
x = x_y[0]
y = x_y[1]
distances = np.hypot(
np.subtract.outer(x, x),
np.subtract.outer(y, y)
)
```
Speed wise they are same
```
%%timeit
np.hypot(i, j)
# 1.29 µs ± 13.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
```
```
%%timeit
np.sqrt(i**2+j**2)
# 1.3 µs ± 9.87 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
```
Underflow
---------
```py
i, j = 1e-200, 1e-200
np.sqrt(i**2+j**2)
# 0.0
```
Overflow
--------
```py
i, j = 1e+200, 1e+200
np.sqrt(i**2+j**2)
# inf
```
No Underflow
------------
```py
i, j = 1e-200, 1e-200
np.hypot(i, j)
# 1.414213562373095e-200
```
No Overflow
-----------
```py
i, j = 1e+200, 1e+200
np.hypot(i, j)
# 1.414213562373095e+200
```
[Refer](https://stackoverflow.com/a/69233365/7035448)
|
45,495,753
|
After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not found
Trying another install method found on SO
`pip install --upgrade notebook`
Seems to install correctly
jupyter is still not found
`where pip` `/usr/local/bin/pip`
What can I do to get the command line `jupyter notebook` command working as in the first step here: <https://jupyter.readthedocs.io/en/latest/running.html#running>
|
2017/08/03
|
[
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
Short answer: Use `python -m notebook`
After updating to OS Catalina, I installed a brewed python: `brew install python`.
It symlinks the Python3, but not the `python` command, so I added to my `$PATH` variable the following:
```
/usr/local/opt/python/libexec/bin
```
to make the brew python the default python command (don't use system python, and now python2.7 is deprecated). `python -m pip install jupyter` works, and I can find the jupyter files in `~/Library/Python/3.7/bin/`, but the tutorial command of `jupyter notebook` doesn't work. Instead I just run `python -m notebook`.
|
You need to add the local python install directory to your path. Apparently this is not done by default on MacOS.
Try:
```
export PATH="$HOME/Library/Python/<version number>/bin:$PATH"
```
and/or add it to your `~/.bashrc`.
|
45,495,753
|
After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not found
Trying another install method found on SO
`pip install --upgrade notebook`
Seems to install correctly
jupyter is still not found
`where pip` `/usr/local/bin/pip`
What can I do to get the command line `jupyter notebook` command working as in the first step here: <https://jupyter.readthedocs.io/en/latest/running.html#running>
|
2017/08/03
|
[
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
My MacOS has python 2.7, I installed python3 with **brew**, then the following commands work for me
```
brew install python3
brew link --overwrite python
```
```
pip3 install ipython
python3 -m pip install jupyter
```
|
You need to add the local python install directory to your path. Apparently this is not done by default on MacOS.
Try:
```
export PATH="$HOME/Library/Python/<version number>/bin:$PATH"
```
and/or add it to your `~/.bashrc`.
|
45,495,753
|
After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not found
Trying another install method found on SO
`pip install --upgrade notebook`
Seems to install correctly
jupyter is still not found
`where pip` `/usr/local/bin/pip`
What can I do to get the command line `jupyter notebook` command working as in the first step here: <https://jupyter.readthedocs.io/en/latest/running.html#running>
|
2017/08/03
|
[
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
You need to add the local python install directory to your path. Apparently this is not done by default on MacOS.
Try:
```
export PATH="$HOME/Library/Python/<version number>/bin:$PATH"
```
and/or add it to your `~/.bashrc`.
|
Try solving this with [Conda](https://docs.conda.io/en/latest/) or Poetry.
[Poetry](https://python-poetry.org/) makes it a lot easier to manage Python dependencies (including Jupyter) and build a virtual environment.
Here are the steps to adding Jupyter to a project:
* Run `poetry add pandas jupyter ipykernel` to add the dependency
* Run `poetry shell` to create a shell within the virtual environment
* Run `jupyter notebook` to to fire up a notebook with access to all the virtual environment dependencies
The other suggested solutions are just band-aids. Conda / Poetry can give you a sustainable solution that's easy to maintain and will shield you from constant Python dependency hell.
|
45,495,753
|
After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not found
Trying another install method found on SO
`pip install --upgrade notebook`
Seems to install correctly
jupyter is still not found
`where pip` `/usr/local/bin/pip`
What can I do to get the command line `jupyter notebook` command working as in the first step here: <https://jupyter.readthedocs.io/en/latest/running.html#running>
|
2017/08/03
|
[
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
Short answer: Use `python -m notebook`
After updating to OS Catalina, I installed a brewed python: `brew install python`.
It symlinks the Python3, but not the `python` command, so I added to my `$PATH` variable the following:
```
/usr/local/opt/python/libexec/bin
```
to make the brew python the default python command (don't use system python, and now python2.7 is deprecated). `python -m pip install jupyter` works, and I can find the jupyter files in `~/Library/Python/3.7/bin/`, but the tutorial command of `jupyter notebook` doesn't work. Instead I just run `python -m notebook`.
|
My MacOS has python 2.7, I installed python3 with **brew**, then the following commands work for me
```
brew install python3
brew link --overwrite python
```
```
pip3 install ipython
python3 -m pip install jupyter
```
|
45,495,753
|
After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not found
Trying another install method found on SO
`pip install --upgrade notebook`
Seems to install correctly
jupyter is still not found
`where pip` `/usr/local/bin/pip`
What can I do to get the command line `jupyter notebook` command working as in the first step here: <https://jupyter.readthedocs.io/en/latest/running.html#running>
|
2017/08/03
|
[
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
Short answer: Use `python -m notebook`
After updating to OS Catalina, I installed a brewed python: `brew install python`.
It symlinks the Python3, but not the `python` command, so I added to my `$PATH` variable the following:
```
/usr/local/opt/python/libexec/bin
```
to make the brew python the default python command (don't use system python, and now python2.7 is deprecated). `python -m pip install jupyter` works, and I can find the jupyter files in `~/Library/Python/3.7/bin/`, but the tutorial command of `jupyter notebook` doesn't work. Instead I just run `python -m notebook`.
|
Try solving this with [Conda](https://docs.conda.io/en/latest/) or Poetry.
[Poetry](https://python-poetry.org/) makes it a lot easier to manage Python dependencies (including Jupyter) and build a virtual environment.
Here are the steps to adding Jupyter to a project:
* Run `poetry add pandas jupyter ipykernel` to add the dependency
* Run `poetry shell` to create a shell within the virtual environment
* Run `jupyter notebook` to to fire up a notebook with access to all the virtual environment dependencies
The other suggested solutions are just band-aids. Conda / Poetry can give you a sustainable solution that's easy to maintain and will shield you from constant Python dependency hell.
|
45,495,753
|
After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not found
Trying another install method found on SO
`pip install --upgrade notebook`
Seems to install correctly
jupyter is still not found
`where pip` `/usr/local/bin/pip`
What can I do to get the command line `jupyter notebook` command working as in the first step here: <https://jupyter.readthedocs.io/en/latest/running.html#running>
|
2017/08/03
|
[
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
My MacOS has python 2.7, I installed python3 with **brew**, then the following commands work for me
```
brew install python3
brew link --overwrite python
```
```
pip3 install ipython
python3 -m pip install jupyter
```
|
Try solving this with [Conda](https://docs.conda.io/en/latest/) or Poetry.
[Poetry](https://python-poetry.org/) makes it a lot easier to manage Python dependencies (including Jupyter) and build a virtual environment.
Here are the steps to adding Jupyter to a project:
* Run `poetry add pandas jupyter ipykernel` to add the dependency
* Run `poetry shell` to create a shell within the virtual environment
* Run `jupyter notebook` to to fire up a notebook with access to all the virtual environment dependencies
The other suggested solutions are just band-aids. Conda / Poetry can give you a sustainable solution that's easy to maintain and will shield you from constant Python dependency hell.
|
4,710,037
|
I'm having trouble with SWIG, shared pointers, and inheritance.
I am creating various c++ classes which inherit from one another, using
Boost shared pointers to refer to them, and then wrapping these shared
pointers with SWIG to create the python classes.
My problem is the following:
* B is a subclass of A
* sA is a shared pointer to A
* sB is a shared pointer to B
* f(sA) is a function expecting a shared pointer to A
* If I pass sB to f() then an error is raised.
* This error only occurs at the python level.
* At the C++ level I can pass sB to f() without a problem.
I have boost 1.40 and swig 1.3.40.
Below are the contents of 5 files which will reproduce the problem
with:
```
python setup.py build_ext --inplace
python test.py
```
**swig\_shared\_ptr.h**
```
#ifndef INCLUDED_SWIG_SHARED_PTR_H
#define INCLUDED_SWIG_SHARED_PTR_H
#include <boost/shared_ptr.hpp>
class Base {};
class Derived : public Base {};
typedef boost::shared_ptr<Base> base_sptr;
typedef boost::shared_ptr<Derived> derived_sptr;
void do_something (base_sptr bs);
base_sptr make_base();
derived_sptr make_derived();
#endif
```
**swig\_shared\_ptr.cc**
```
#include <iostream>
#include "swig_shared_ptr.h"
void do_something (base_sptr bs)
{
std::cout << "Doing something." << std::endl;
}
base_sptr make_base() { return base_sptr(new Base ()); };
derived_sptr make_derived() { return derived_sptr(new Derived ()); };
```
**swig\_shared\_ptr.i**
```
%module(docstring="
Example module showing problems I am having with SWIG, shared pointers
and inheritance.
") swig_shared_ptr
%{
#include "swig_shared_ptr.h"
%}
%include <swig_shared_ptr.h>
%include <boost_shared_ptr.i>
%template(base_sptr) boost::shared_ptr<Base>;
%template(derived_sptr) boost::shared_ptr<Derived>;
```
**setup.py**
```
"""
setup.py file for swig_shared_ptr
"""
from distutils.core import setup, Extension
swig_shared_ptr_module = Extension('_swig_shared_ptr',
include_dirs = ['/usr/include/boost'],
sources=['swig_shared_ptr.i', 'swig_shared_ptr.cc'],
)
setup (name = 'swig_shared_ptr',
version = '0.1',
author = "Ben",
description = """Example showing problems I am having with SWIG, shared
pointers and inheritance.""",
ext_modules = [swig_shared_ptr_module],
py_modules = ["swig_shared_ptr"],
)
```
**test.py**
```
import swig_shared_ptr as ssp
bs = ssp.make_base()
dr = ssp.make_derived()
# Works fine.
ssp.do_something(bs)
# Fails with "TypeError: in method 'do_something', argument 1 of type 'base_sptr'"
ssp.do_something(dr)
```
|
2011/01/17
|
[
"https://Stackoverflow.com/questions/4710037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1229275/"
] |
The following change appears to solve the problem.
In **swig\_shared\_ptr.i** the two lines:
```
%template(base_sptr) boost::shared_ptr<Base>;
%template(derived_sptr) boost::shared_ptr<Derived>;
```
are moved so that they are above the line
```
%include <swig_shared_ptr.h>
```
and are then replaced (in SWIG 1.3) by:
```
SWIG_SHARED_PTR(Base, Base)
SWIG_SHARED_PTR_DERIVED(Derived, Base, Derived)
```
or (in SWIG 2.0) by:
```
%shared_ptr(Base)
%shared_ptr(Derived)
```
|
SWIG doesn't know anything about the `boost::shared_ptr<T>` class. It therefore can't tell that `derived_sptr` can be "cast" (which is, I believe, implemented with some crazy constructors and template metaprogramming) to `derived_sptr`. Because SWIG requires fairly simple class definitions (or inclusion of simple files with `%include`), you won't be able to accurately declare the `shared_ptr` class, because Boost is *incredibly* non-simple with its compiler compensation and template tricks.
As to a solution: is it absolutely necessary to hand out shared pointers? SWIG's C++ wrappers basically function as shared pointers. Boost and SWIG are very, very difficult to get to work together.
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
PHP is the best to start, but as experienced programmer you may want to look at Python, because PHP is a C style language. Python would be easier after Pascal, I think.
Take a look at examples:
On PHP: <http://en.wikipedia.org/wiki/Php#Syntax>
On Python: <http://en.wikipedia.org/wiki/Python_(programming_language)#Syntax_and_semantics>
Note, that Ruby and Python are rarely used by them selves in web-development. Usually **Django** and **Ruby on railes** frameworks are used. In PHP there are several variants. You can code from the scratch, or also use some framework.
I used to code on PHP for about five years and now started to learn Django (python based framework) and I think it's the best thing there is. Take a look: <http://djangoproject.com/>
|
Only good answer - C# ;) Seriously ;)
Why? Anders Hejlsberg. He made it. It is the direct continuation of his work that started with Turbo Pascal and went over to Delphi... then Microsoft hired him and he moved from Pascal to C (core langauge) and made C#.
Read it up on <http://en.wikipedia.org/wiki/Anders_Hejlsberg>
If you come from Delphi, you will love it ;)
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
PHP is the best to start, but as experienced programmer you may want to look at Python, because PHP is a C style language. Python would be easier after Pascal, I think.
Take a look at examples:
On PHP: <http://en.wikipedia.org/wiki/Php#Syntax>
On Python: <http://en.wikipedia.org/wiki/Python_(programming_language)#Syntax_and_semantics>
Note, that Ruby and Python are rarely used by them selves in web-development. Usually **Django** and **Ruby on railes** frameworks are used. In PHP there are several variants. You can code from the scratch, or also use some framework.
I used to code on PHP for about five years and now started to learn Django (python based framework) and I think it's the best thing there is. Take a look: <http://djangoproject.com/>
|
I have done a fairly large (4-5 FTE) project based on webhub (www.href.com). I can certainly advise this if it is a webapp for internal use.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.