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 |
|---|---|---|---|---|---|
39,303,710 | I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next\_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.
```
last_date = df.iloc[1,0]
last_u... | 2016/09/03 | [
"https://Stackoverflow.com/questions/39303710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770803/"
] | If my understanding is correct then you can get desired result with the following:
```
SELECT i.*,
CASE WHEN prop1.PROPERTY_ID = 1 THEN prop1.VALUE ELSE '' END AS PROPERTY_ONE,
CASE WHEN prop1.PROPERTY_ID = 2 THEN prop1.VALUE ELSE '' END AS PROPERTY_TWO
FROM ITEM i
LEFT JOIN ITEM_PROPERTY prop1 on i.ITEM_I... | ```
Select i.*, prop1.VALUE as PROPERTY_ONE, prop2.VALUE as PROPERTY_TWO
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D and prop.PROPERTY_ID in (1,2)
``` |
39,303,710 | I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next\_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.
```
last_date = df.iloc[1,0]
last_u... | 2016/09/03 | [
"https://Stackoverflow.com/questions/39303710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770803/"
] | Old style:
```
Select i.*,
max(decode(prop.PROPERTY_ID,1,prop.VALUE,NULL)) as PROPERTY_ONE,
max(decode(prop.PROPERTY_ID,2,prop.VALUE,NULL)) as PROPERTY_TWO
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D and prop.PROPERTY_ID in(1,2)
group by there_will_have_to_list_all_the_fields... | ```
Select i.*, prop1.VALUE as PROPERTY_ONE, prop2.VALUE as PROPERTY_TWO
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D and prop.PROPERTY_ID in (1,2)
``` |
50,693,966 | I have a directory containing many images(\*.jpg). Each image has a name. In the same directory i have a file containing python code(below).
```
import numpy as np
import pandas as pd
import glob
fd = open('melanoma.csv', 'a')
for img in glob.glob('*.jpg'):
dataFrame = pd.read_csv('allcsv.csv')
name = dataFra... | 2018/06/05 | [
"https://Stackoverflow.com/questions/50693966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6612871/"
] | First, your code reads the .csv file once for every image. Second, you have a nested `for`-loop. Both is not ideal. I recommend the following approach:
**Step 1 - Create list of image file names**
```
import glob
image_names = [f.replace('.jpg', '') for f in glob.glob("*.jpg")]
```
**Step 2 - Create dataframe with... | This is just a solution for storing the matched values to a new file melanoma.csv.
Your code can be further improved and optimized.
```
import numpy as np
import pandas as pd
import glob
# Create a dictionary object
d={}
for img in glob.glob('*.jpg'):
dataFrame = pd.read_csv('allcsv.csv')
name = dataFrame[... |
39,771,366 | I am a beginner in python. However, I have some problems when I try to use the readline() method.
```
f=raw_input("filename> ")
a=open(f)
print a.read()
print a.readline()
print a.readline()
print a.readline()
```
and my txt file is
```
aaaaaaaaa
bbbbbbbbb
ccccccccc
```
However, when I tried to run it on a Mac t... | 2016/09/29 | [
"https://Stackoverflow.com/questions/39771366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899656/"
] | When you open a file you get a pointer to some place of the file (by default: the begining). Now whenever you run `.read()` or `.readline()` this pointer moves:
1. `.read()` reads until the end of the file and moves the pointer to the end (thus further calls to any reading gives nothing)
2. `.readline()` reads until n... | You need to understand the concept of file pointers. When you read the file, it is fully consumed, and the pointer is at the end of the file.
>
> It seems that the readline() is not working at all.
>
>
>
It is working as expected. There are no lines to read.
>
> when I disable print a.read(), the readline() ... |
39,771,366 | I am a beginner in python. However, I have some problems when I try to use the readline() method.
```
f=raw_input("filename> ")
a=open(f)
print a.read()
print a.readline()
print a.readline()
print a.readline()
```
and my txt file is
```
aaaaaaaaa
bbbbbbbbb
ccccccccc
```
However, when I tried to run it on a Mac t... | 2016/09/29 | [
"https://Stackoverflow.com/questions/39771366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899656/"
] | When you open a file you get a pointer to some place of the file (by default: the begining). Now whenever you run `.read()` or `.readline()` this pointer moves:
1. `.read()` reads until the end of the file and moves the pointer to the end (thus further calls to any reading gives nothing)
2. `.readline()` reads until n... | The file object `a` remembers it's position in the file.
* `a.read()` reads from the current position to end of the file (moving the position to the end of the file)
* `a.readline()` reads from the current position to the end of the line (moving the position to the next line)
* `a.seek(n)` moves to position n in the f... |
39,771,366 | I am a beginner in python. However, I have some problems when I try to use the readline() method.
```
f=raw_input("filename> ")
a=open(f)
print a.read()
print a.readline()
print a.readline()
print a.readline()
```
and my txt file is
```
aaaaaaaaa
bbbbbbbbb
ccccccccc
```
However, when I tried to run it on a Mac t... | 2016/09/29 | [
"https://Stackoverflow.com/questions/39771366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899656/"
] | You need to understand the concept of file pointers. When you read the file, it is fully consumed, and the pointer is at the end of the file.
>
> It seems that the readline() is not working at all.
>
>
>
It is working as expected. There are no lines to read.
>
> when I disable print a.read(), the readline() ... | The file object `a` remembers it's position in the file.
* `a.read()` reads from the current position to end of the file (moving the position to the end of the file)
* `a.readline()` reads from the current position to the end of the line (moving the position to the next line)
* `a.seek(n)` moves to position n in the f... |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | You can save your XLS file to a [StringIO](http://docs.python.org/library/stringio.html) object, which is file-like.
You can return the StringIO object's `getvalue()` in the response. Be sure to add headers to mark it as a downloadable spreadsheet. | If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | You can save your XLS file to a [StringIO](http://docs.python.org/library/stringio.html) object, which is file-like.
You can return the StringIO object's `getvalue()` in the response. Be sure to add headers to mark it as a downloadable spreadsheet. | Use <https://bitbucket.org/kmike/django-excel-response> |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | neat package! i didn't know about this
According to the doc, the `save(filename_or_stream)` method takes either a filename to save on, or a file-like stream to write on.
And a Django response object happens to be a file-like stream! so just do `xls.save(response)`. Look the Django docs about [generating PDFs](http://... | Use <https://bitbucket.org/kmike/django-excel-response> |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | neat package! i didn't know about this
According to the doc, the `save(filename_or_stream)` method takes either a filename to save on, or a file-like stream to write on.
And a Django response object happens to be a file-like stream! so just do `xls.save(response)`. Look the Django docs about [generating PDFs](http://... | If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | \*\*\*UPDATE: django-excel-templates no longer being maintained, instead try Marmir <http://brianray.github.com/mm/>
Still in development as I type this but <http://code.google.com/p/django-excel-templates/> Django excel templates project aims to do what your asking.
Specifically look at the tests. Here is a simple c... | You can save your XLS file to a [StringIO](http://docs.python.org/library/stringio.html) object, which is file-like.
You can return the StringIO object's `getvalue()` in the response. Be sure to add headers to mark it as a downloadable spreadsheet. |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | neat package! i didn't know about this
According to the doc, the `save(filename_or_stream)` method takes either a filename to save on, or a file-like stream to write on.
And a Django response object happens to be a file-like stream! so just do `xls.save(response)`. Look the Django docs about [generating PDFs](http://... | \*\*\*UPDATE: django-excel-templates no longer being maintained, instead try Marmir <http://brianray.github.com/mm/>
Still in development as I type this but <http://code.google.com/p/django-excel-templates/> Django excel templates project aims to do what your asking.
Specifically look at the tests. Here is a simple c... |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | \*\*\*UPDATE: django-excel-templates no longer being maintained, instead try Marmir <http://brianray.github.com/mm/>
Still in development as I type this but <http://code.google.com/p/django-excel-templates/> Django excel templates project aims to do what your asking.
Specifically look at the tests. Here is a simple c... | You might want to check [huDjango](https://cybernetics.hudora.biz/projects/wiki/huDjango) which comes fith a function called `serializers.queryset_to_xls()` do convert a queryset into an downloadable Excel Sheet. |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | \*\*\*UPDATE: django-excel-templates no longer being maintained, instead try Marmir <http://brianray.github.com/mm/>
Still in development as I type this but <http://code.google.com/p/django-excel-templates/> Django excel templates project aims to do what your asking.
Specifically look at the tests. Here is a simple c... | Use <https://bitbucket.org/kmike/django-excel-response> |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | \*\*\*UPDATE: django-excel-templates no longer being maintained, instead try Marmir <http://brianray.github.com/mm/>
Still in development as I type this but <http://code.google.com/p/django-excel-templates/> Django excel templates project aims to do what your asking.
Specifically look at the tests. Here is a simple c... | If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it |
883,313 | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this [snip... | 2009/05/19 | [
"https://Stackoverflow.com/questions/883313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92763/"
] | Use <https://bitbucket.org/kmike/django-excel-response> | If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it |
14,484,386 | I'm interrogating a nested dictionary using the dict.get('keyword') method. Currently my syntax is...
```
M = cursor_object_results_of_db_query
for m in M:
X = m.get("gparents").get("parent").get("child")
for x in X:
y = x.get("key")
```
However, sometimes one of the "parent" or "child" tags doesn't... | 2013/01/23 | [
"https://Stackoverflow.com/questions/14484386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | Since these are all python `dict`s and you are calling the `dict.get()` method on them, you can use an empty `dict` to chain:
```
[m.get("gparents", {}).get("parent", {}).get("child") for m in M]
```
By leaving off the default for the last `.get()` you fall back to `None`. Now, if any of the intermediary keys is not... | Another approach is to recognize that if the key isn't found, `dict.get` returns `None`. However, `None` doesn't have an attribute `.get`, so it will throw an `AttributeError`:
```
for m in M:
try:
X = m.get("gparents").get("parent").get("child")
except AttributeError:
continue
for x in X:
... |
14,484,386 | I'm interrogating a nested dictionary using the dict.get('keyword') method. Currently my syntax is...
```
M = cursor_object_results_of_db_query
for m in M:
X = m.get("gparents").get("parent").get("child")
for x in X:
y = x.get("key")
```
However, sometimes one of the "parent" or "child" tags doesn't... | 2013/01/23 | [
"https://Stackoverflow.com/questions/14484386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | Since these are all python `dict`s and you are calling the `dict.get()` method on them, you can use an empty `dict` to chain:
```
[m.get("gparents", {}).get("parent", {}).get("child") for m in M]
```
By leaving off the default for the last `.get()` you fall back to `None`. Now, if any of the intermediary keys is not... | How about using a small helper function?
```
def getn(d, path):
for p in path:
if p not in d:
return None
d = d[p]
return d
```
and then
```
[getn(m, ["gparents", "parent", "child"]) for m in M]
``` |
14,484,386 | I'm interrogating a nested dictionary using the dict.get('keyword') method. Currently my syntax is...
```
M = cursor_object_results_of_db_query
for m in M:
X = m.get("gparents").get("parent").get("child")
for x in X:
y = x.get("key")
```
However, sometimes one of the "parent" or "child" tags doesn't... | 2013/01/23 | [
"https://Stackoverflow.com/questions/14484386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | Since these are all python `dict`s and you are calling the `dict.get()` method on them, you can use an empty `dict` to chain:
```
[m.get("gparents", {}).get("parent", {}).get("child") for m in M]
```
By leaving off the default for the last `.get()` you fall back to `None`. Now, if any of the intermediary keys is not... | I realise I'm a bit late for the part but here's the solution I came up with when faced with a similar problem:
```
def get_nested(dict_, *keys, default=None):
if not isinstance(dict_, dict):
return default
elem = dict_.get(keys[0], default)
if len(keys) == 1:
return elem
return get_nes... |
20,375,954 | I have a large collection of images which I'm trying to sort according to quality by crowd-sourcing. Images can be assigned 1, 2, 3, 4, or 5 stars according to how much the user likes them. A 5-star image would be very visually appealing, a 1-star image might be blurry and out of focus.
At first I created a page showi... | 2013/12/04 | [
"https://Stackoverflow.com/questions/20375954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216605/"
] | Sounds like you need a ranking algorithm similar to what is used in sport to rank players. Think of the comparison of two images as a match and the one the user selects as the better one is the winner of the match. After some time, many players have played many matches and sometimes against the same person. They win so... | Let each image start with a ranking of 3 (the mean of 1 … 5), then for each comparison (which wasn't equal) lower the rank of the loser image and increase the rank of the winner image. I propose to simply *count* the +1s and the -1s, so that you have a number of wins and a number of losses for each image.
Then the val... |
20,375,954 | I have a large collection of images which I'm trying to sort according to quality by crowd-sourcing. Images can be assigned 1, 2, 3, 4, or 5 stars according to how much the user likes them. A 5-star image would be very visually appealing, a 1-star image might be blurry and out of focus.
At first I created a page showi... | 2013/12/04 | [
"https://Stackoverflow.com/questions/20375954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216605/"
] | Sounds like you need a ranking algorithm similar to what is used in sport to rank players. Think of the comparison of two images as a match and the one the user selects as the better one is the winner of the match. After some time, many players have played many matches and sometimes against the same person. They win so... | If you don't want to deal with a complex statistical model like the Elo rating system suggested by @VincentRamdhanie (which will yield optimal results), you can always model this as a simple [optimization problem](http://en.wikipedia.org/wiki/Optimization_%28mathematics%29).
You have datapoints of the type `a>b`. If y... |
20,375,954 | I have a large collection of images which I'm trying to sort according to quality by crowd-sourcing. Images can be assigned 1, 2, 3, 4, or 5 stars according to how much the user likes them. A 5-star image would be very visually appealing, a 1-star image might be blurry and out of focus.
At first I created a page showi... | 2013/12/04 | [
"https://Stackoverflow.com/questions/20375954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216605/"
] | Let each image start with a ranking of 3 (the mean of 1 … 5), then for each comparison (which wasn't equal) lower the rank of the loser image and increase the rank of the winner image. I propose to simply *count* the +1s and the -1s, so that you have a number of wins and a number of losses for each image.
Then the val... | If you don't want to deal with a complex statistical model like the Elo rating system suggested by @VincentRamdhanie (which will yield optimal results), you can always model this as a simple [optimization problem](http://en.wikipedia.org/wiki/Optimization_%28mathematics%29).
You have datapoints of the type `a>b`. If y... |
51,865,923 | I have been trying out DroneKit Python and have been working with some of the examples provided. Having got to a point of some knowledge of working with DroneKit I have started writing some python code to perform a single mission. My only problem is that the start location for my missions are always defaulting to `Lat ... | 2018/08/15 | [
"https://Stackoverflow.com/questions/51865923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10231182/"
] | If you really don't want to wrap you can use `@media` queries to change `flex-direction` of your quizlist class to `column`.
```css
input[type="radio"] {
display: none;
}
input[type="radio"]:checked+.quizlabel {
border: 2px solid #0052e7;
transition: .1s;
background-color: #0052e... | I think this is what you're aiming for?
The boxes weren't getting smaller because of the text inside of them, so you needed to add `flex-wrap:wrap;` to the `.quizlist` so that way they would go onto the next row. You also needed to add a `flex` and `flex-grow` to specify the widths you want them to flex to. If you don... |
71,949,010 | After I install Google cloud sdk in my computer, I open the terminal and type "gcloud --version" but it says "python was not found"
note:
I unchecked the box saying "Install python bundle" when I install Google cloud sdk because I already have python 3.10.2 installed.
so, how do fix this?
Thanks in advance. | 2022/04/21 | [
"https://Stackoverflow.com/questions/71949010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17138122/"
] | As mentioned in the [document](https://cloud.google.com/sdk/docs/install-sdk#windows):
>
> Cloud SDK requires Python; supported versions are Python 3 (preferred,
> 3.5 to 3.8) and Python 2 (2.7.9 or later). By default, the Windows version of Cloud SDK comes bundled with Python 3 and Python 2. To use
> Cloud SDK, your... | On ubuntu Linux, you can define this variable in the `.bashrc` file:
```bash
export CLOUDSDK_PYTHON=/usr/bin/python3
``` |
15,866,765 | What is the recommended library for web client programming which involves HTTP requests.
I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ?
I expect a library with functionality something like [this](http://docs.python-re... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15866765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | [`Network.HTTP.Conduit`](http://hackage.haskell.org/package/http-conduit) has a clean API (it uses [`Network.HTTP.Types`](http://hackage.haskell.org/package/http-types)) and is quite simple to use if you know a bit about conduits. Example:
```hs
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Conduit... | In addition to `Network.HTTP.Conduit` there [`Network.Http.Client`](http://hackage.haskell.org/package/http-streams) which exposes an [`io-streams`](http://hackage.haskell.org/package/io-streams-1.0.1.0) interface. |
15,866,765 | What is the recommended library for web client programming which involves HTTP requests.
I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ?
I expect a library with functionality something like [this](http://docs.python-re... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15866765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | A library named [wreq](https://hackage.haskell.org/package/wreq) has been released by Bryan O'Sullivan which is great and easy to use for HTTP communication.
A related tutorial for that by the same author is [here.](http://www.serpentine.com/wreq/tutorial.html)
There is also another library named [req](https://github... | [`Network.HTTP.Conduit`](http://hackage.haskell.org/package/http-conduit) has a clean API (it uses [`Network.HTTP.Types`](http://hackage.haskell.org/package/http-types)) and is quite simple to use if you know a bit about conduits. Example:
```hs
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Conduit... |
15,866,765 | What is the recommended library for web client programming which involves HTTP requests.
I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ?
I expect a library with functionality something like [this](http://docs.python-re... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15866765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | [`Network.HTTP.Conduit`](http://hackage.haskell.org/package/http-conduit) has a clean API (it uses [`Network.HTTP.Types`](http://hackage.haskell.org/package/http-types)) and is quite simple to use if you know a bit about conduits. Example:
```hs
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Conduit... | [Servant](https://hackage.haskell.org/package/servant) is easy to use (albeit hard to understand) and magical. It lets you specify the API as an uninhabited type, and generates request and response behaviors based on it. You'll never have to worry about serialization or deserialization, or even JSON -- it converts JSON... |
15,866,765 | What is the recommended library for web client programming which involves HTTP requests.
I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ?
I expect a library with functionality something like [this](http://docs.python-re... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15866765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | A library named [wreq](https://hackage.haskell.org/package/wreq) has been released by Bryan O'Sullivan which is great and easy to use for HTTP communication.
A related tutorial for that by the same author is [here.](http://www.serpentine.com/wreq/tutorial.html)
There is also another library named [req](https://github... | In addition to `Network.HTTP.Conduit` there [`Network.Http.Client`](http://hackage.haskell.org/package/http-streams) which exposes an [`io-streams`](http://hackage.haskell.org/package/io-streams-1.0.1.0) interface. |
15,866,765 | What is the recommended library for web client programming which involves HTTP requests.
I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ?
I expect a library with functionality something like [this](http://docs.python-re... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15866765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | In addition to `Network.HTTP.Conduit` there [`Network.Http.Client`](http://hackage.haskell.org/package/http-streams) which exposes an [`io-streams`](http://hackage.haskell.org/package/io-streams-1.0.1.0) interface. | [Servant](https://hackage.haskell.org/package/servant) is easy to use (albeit hard to understand) and magical. It lets you specify the API as an uninhabited type, and generates request and response behaviors based on it. You'll never have to worry about serialization or deserialization, or even JSON -- it converts JSON... |
15,866,765 | What is the recommended library for web client programming which involves HTTP requests.
I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ?
I expect a library with functionality something like [this](http://docs.python-re... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15866765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | A library named [wreq](https://hackage.haskell.org/package/wreq) has been released by Bryan O'Sullivan which is great and easy to use for HTTP communication.
A related tutorial for that by the same author is [here.](http://www.serpentine.com/wreq/tutorial.html)
There is also another library named [req](https://github... | [Servant](https://hackage.haskell.org/package/servant) is easy to use (albeit hard to understand) and magical. It lets you specify the API as an uninhabited type, and generates request and response behaviors based on it. You'll never have to worry about serialization or deserialization, or even JSON -- it converts JSON... |
11,923,645 | Lets say i have this code:
```
def dosomething(thing1, thing2=hello, thing3=world):
print thing1
print thing2
print thing3
```
I would like to be able to specify what thing3 is, but wihout having to say what thing2 is. (The code below is how i thought it might work...)
```
dosomething("This says 'hello ... | 2012/08/12 | [
"https://Stackoverflow.com/questions/11923645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1542540/"
] | Use keyword arguments
```
dosomething("This says 'hello fail!'", thing3='fail!')
``` | Yes, you can:
```
dosomething("This says 'hello fail!'", thing3 = 'fail!')
``` |
32,550,447 | If I have a set of integers which denote the values that a list element can take and a python list of a given length.
I want to fill the list with all possible combinations.
**example**
>
> list `length=3` and the `my_set ={1,-1}`
>
>
>
**Possible combinations**
```
[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],
[-1,1... | 2015/09/13 | [
"https://Stackoverflow.com/questions/32550447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4355529/"
] | That's what `itertools.product` is for :
```
>>> from itertools import product
>>> list(product({1,-1},repeat=3))
[(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
>>>
```
And if you want the result as list you can use `map` to convert the iterator of tuples to lis... | Use the [`itertools.product()` function](https://docs.python.org/3/library/itertools.html#itertools.combinations):
```
from itertools import product
result = [list(combo) for combo in product(my_set, repeat=length)]
```
The `list()` call is optional; if tuples instead of lists are fine to, then `result = list(produ... |
32,550,447 | If I have a set of integers which denote the values that a list element can take and a python list of a given length.
I want to fill the list with all possible combinations.
**example**
>
> list `length=3` and the `my_set ={1,-1}`
>
>
>
**Possible combinations**
```
[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],
[-1,1... | 2015/09/13 | [
"https://Stackoverflow.com/questions/32550447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4355529/"
] | That's what `itertools.product` is for :
```
>>> from itertools import product
>>> list(product({1,-1},repeat=3))
[(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
>>>
```
And if you want the result as list you can use `map` to convert the iterator of tuples to lis... | ```
lst_length = 3
my_set = {1,-1}
result = [[x] for x in my_set]
for i in range(1,lst_length):
temp = []
for candidate in my_set:
for item in result:
new_item = [candidate]
new_item += item
temp.append(new_item)
result = temp
print result
```
If the list length... |
32,550,447 | If I have a set of integers which denote the values that a list element can take and a python list of a given length.
I want to fill the list with all possible combinations.
**example**
>
> list `length=3` and the `my_set ={1,-1}`
>
>
>
**Possible combinations**
```
[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],
[-1,1... | 2015/09/13 | [
"https://Stackoverflow.com/questions/32550447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4355529/"
] | Use the [`itertools.product()` function](https://docs.python.org/3/library/itertools.html#itertools.combinations):
```
from itertools import product
result = [list(combo) for combo in product(my_set, repeat=length)]
```
The `list()` call is optional; if tuples instead of lists are fine to, then `result = list(produ... | ```
lst_length = 3
my_set = {1,-1}
result = [[x] for x in my_set]
for i in range(1,lst_length):
temp = []
for candidate in my_set:
for item in result:
new_item = [candidate]
new_item += item
temp.append(new_item)
result = temp
print result
```
If the list length... |
64,087,848 | I'm trying to check how much times does some value repeat in a row but I ran in a problem where my code is leaving the last number without checking it.
```
Ai = input()
arr = [int(x) for x in Ai.split()]
c = 0
frozen_num = arr[0]
for i in range(0,len(arr)):
print(arr)
if frozen_num == arr[0]:
arr.rem... | 2020/09/27 | [
"https://Stackoverflow.com/questions/64087848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12733326/"
] | You could use the `Counter` of the `Collections` module to measure all the occurrences of different numbers.
```
from collections import Counter
arr = list(Counter(input().split()).values())
print(arr)
```
Output with an input of `1 1 1 1 5 5`:
```
1 1 1 1 5 5
[4, 2]
``` | If you want to stick with your method and not use external libraries, you can add an if statement that detects when you reach the last element of your array and process it differently from the others:
```
Ai=input()
arr = [int(x) for x in Ai.split()]
L=[]
c = 0
frozen_num = arr[0]
for i in range(0, len(arr)+1):
pr... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | I don't know if this is the "proper" way of doing things, but I usually wrap my function in a class, so that I can access parameters from `self`. Your example would then look like:
```
class fitClass:
def __init__(self):
pass
def fitfun(self, x, a):
return np.exp(a*(x - self.b))
inst = fitCl... | You can define `b` as a global variable inside the fit function.
```
from scipy.optimize import curve_fit
def fitfun(x, a):
global b
return np.exp(a*(x - b))
xdata = np.arange(10)
#first sample data set
ydata = np.exp(2 * (xdata - 10))
b = 10
coeffs, coeffs_cov = curve_fit(fitfun, xdata, ydata)
print(coef... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | I don't know if this is the "proper" way of doing things, but I usually wrap my function in a class, so that I can access parameters from `self`. Your example would then look like:
```
class fitClass:
def __init__(self):
pass
def fitfun(self, x, a):
return np.exp(a*(x - self.b))
inst = fitCl... | UPDATE:
Apologies for posting the untested code. As pointed out by @mr-t , the code indeed throws an error. It seems , the kwargs argument of the curve\_fit function is to set the keywords arguments of `leastsq` and `least_squares` functions and not the keyword arguments of fit function itself.
In this case, in additi... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | I don't know if this is the "proper" way of doing things, but I usually wrap my function in a class, so that I can access parameters from `self`. Your example would then look like:
```
class fitClass:
def __init__(self):
pass
def fitfun(self, x, a):
return np.exp(a*(x - self.b))
inst = fitCl... | One really easy way to do this would be to use the `partial` function from functools. In this case all you would have to do is the following. In this case `b` be would have to defined otherwise I believe `scipy.optimize.curvefit` would try to optimize b in addition to a
```
from functools import partial
def fitfun(x,... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | Let me also recommend lmfit (<http://lmfit.github.io/lmfit-py/>) and its Model class for this type of problem. Lmfit provides a higher-level abstraction for curve fitting and optimization problems.
With lmfit, each parameter in the model becomes an object that can be fixed, varied freely, or given upper and lower boun... | You can define `b` as a global variable inside the fit function.
```
from scipy.optimize import curve_fit
def fitfun(x, a):
global b
return np.exp(a*(x - b))
xdata = np.arange(10)
#first sample data set
ydata = np.exp(2 * (xdata - 10))
b = 10
coeffs, coeffs_cov = curve_fit(fitfun, xdata, ydata)
print(coef... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | One really easy way to do this would be to use the `partial` function from functools. In this case all you would have to do is the following. In this case `b` be would have to defined otherwise I believe `scipy.optimize.curvefit` would try to optimize b in addition to a
```
from functools import partial
def fitfun(x,... | You can define `b` as a global variable inside the fit function.
```
from scipy.optimize import curve_fit
def fitfun(x, a):
global b
return np.exp(a*(x - b))
xdata = np.arange(10)
#first sample data set
ydata = np.exp(2 * (xdata - 10))
b = 10
coeffs, coeffs_cov = curve_fit(fitfun, xdata, ydata)
print(coef... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | Let me also recommend lmfit (<http://lmfit.github.io/lmfit-py/>) and its Model class for this type of problem. Lmfit provides a higher-level abstraction for curve fitting and optimization problems.
With lmfit, each parameter in the model becomes an object that can be fixed, varied freely, or given upper and lower boun... | UPDATE:
Apologies for posting the untested code. As pointed out by @mr-t , the code indeed throws an error. It seems , the kwargs argument of the curve\_fit function is to set the keywords arguments of `leastsq` and `least_squares` functions and not the keyword arguments of fit function itself.
In this case, in additi... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | One really easy way to do this would be to use the `partial` function from functools. In this case all you would have to do is the following. In this case `b` be would have to defined otherwise I believe `scipy.optimize.curvefit` would try to optimize b in addition to a
```
from functools import partial
def fitfun(x,... | UPDATE:
Apologies for posting the untested code. As pointed out by @mr-t , the code indeed throws an error. It seems , the kwargs argument of the curve\_fit function is to set the keywords arguments of `leastsq` and `least_squares` functions and not the keyword arguments of fit function itself.
In this case, in additi... |
49,813,481 | I am trying to fit some data that I have using scipy.optimize.curve\_fit.
My fit function is:
```
def fitfun(x, a):
return np.exp(a*(x - b))
```
What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49813481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654219/"
] | Let me also recommend lmfit (<http://lmfit.github.io/lmfit-py/>) and its Model class for this type of problem. Lmfit provides a higher-level abstraction for curve fitting and optimization problems.
With lmfit, each parameter in the model becomes an object that can be fixed, varied freely, or given upper and lower boun... | One really easy way to do this would be to use the `partial` function from functools. In this case all you would have to do is the following. In this case `b` be would have to defined otherwise I believe `scipy.optimize.curvefit` would try to optimize b in addition to a
```
from functools import partial
def fitfun(x,... |
63,153,688 | I edited this post so that i could give more info about the goal I am trying to achieve.
basically I want to be able to open VSCode in a directory that I can input inside a python file I am running trhough a shell command i created.
So what I need is for the python file to ask me for the name of the folder I want to op... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63153688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12288571/"
] | Store dataValue in some variable and use expectation to wait for your closure to execute and then test. Note: This example was written in swift 4
```
let yourExpectationName = expectation(description: "xyz")
var dataToAssert = [String]() //replace with you data type
sut.apiSuccessClouser = { dataValue in
dataToA... | apiSuccessClouser in MockApiService is a property of type closure `(()->Void?)?`.
In line `sut.apiSuccessClouser = { ... }` you assign the the property apiSuccessClouser a closure but you never access this closure so that the `print("apiSuccessClouser")` to be executed.
to execute the print("apiSuccessClouser") you n... |
63,153,688 | I edited this post so that i could give more info about the goal I am trying to achieve.
basically I want to be able to open VSCode in a directory that I can input inside a python file I am running trhough a shell command i created.
So what I need is for the python file to ask me for the name of the folder I want to op... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63153688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12288571/"
] | Store dataValue in some variable and use expectation to wait for your closure to execute and then test. Note: This example was written in swift 4
```
let yourExpectationName = expectation(description: "xyz")
var dataToAssert = [String]() //replace with you data type
sut.apiSuccessClouser = { dataValue in
dataToA... | To test that kind of asynchronous code with vanilla XCTest, you'll need to use an [`XCTestExpectation`](https://developer.apple.com/documentation/xctest/xctestexpectation).
```
func test_fetch_photo() {
let expectation = XCTestExpectation(description: "photo is fetched")
sut.apiSuccessClouser = { dataValue in
... |
54,060,243 | Hi ultimately I'm trying to install django on my computer, but I'm unable to do this as the when I run pip in the command line I get the following error message:
`''pip' is not recognized as an internal or external command,
operable program or batch file.'`
I've added the following locations to my path environment:
... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54060243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9815902/"
] | You can put a conditional expression on a single item update to make the update fail if the condition is not met. However it will not fail an entire batch, just the single update. The batch update response would contain information on which updates succeeded and which failed | It's possible to do it, by using conditional expression for filter expression. But please don't do it.
DynamoDB is a key-value NoSQL. It means that you can get the right data by keys only. If you do the filter, it will loop through a lot of records and slow down you app.
You can check this article:
[5 things that you... |
54,060,243 | Hi ultimately I'm trying to install django on my computer, but I'm unable to do this as the when I run pip in the command line I get the following error message:
`''pip' is not recognized as an internal or external command,
operable program or batch file.'`
I've added the following locations to my path environment:
... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54060243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9815902/"
] | You should look at the [DynamoDB transactions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transactions.html). It has the conditional expressions you are looking for and all or nothing batch updates. | It's possible to do it, by using conditional expression for filter expression. But please don't do it.
DynamoDB is a key-value NoSQL. It means that you can get the right data by keys only. If you do the filter, it will loop through a lot of records and slow down you app.
You can check this article:
[5 things that you... |
54,060,243 | Hi ultimately I'm trying to install django on my computer, but I'm unable to do this as the when I run pip in the command line I get the following error message:
`''pip' is not recognized as an internal or external command,
operable program or batch file.'`
I've added the following locations to my path environment:
... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54060243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9815902/"
] | I guess you're looking for conditional expressions, check this [link](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html).
You should use UpdateItem, which edits an existing item's attributes, or adds a new item to the table if it does not already exist.
e.g. copied... | It's possible to do it, by using conditional expression for filter expression. But please don't do it.
DynamoDB is a key-value NoSQL. It means that you can get the right data by keys only. If you do the filter, it will loop through a lot of records and slow down you app.
You can check this article:
[5 things that you... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.
It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ... | i did it for opensearch so you can refer it.
```
from opensearchpy import OpenSearch
def get_connection():
connection = None
try:
connection = OpenSearch(
hosts=[{'host': settings.OPEN_SEARCH_HOST, 'port': settings.OPE... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.
It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ... | Wrap your connection class.
Set a limit on how many connections you make.
Return an unused connection.
Intercept close to free the connection.
Update:
I put something like this in dbpool.py:
```
import sqlalchemy.pool as pool
import MySQLdb as mysql
mysql = pool.manage(mysql)
``` |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.
It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ... | Old thread, but for general-purpose pooling (connections or any expensive object), I use something like:
```
def pool(ctor, limit=None):
local_pool = multiprocessing.Queue()
n = multiprocesing.Value('i', 0)
@contextlib.contextmanager
def pooled(ctor=ctor, lpool=local_pool, n=n):
# block iff at ... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | Old thread, but for general-purpose pooling (connections or any expensive object), I use something like:
```
def pool(ctor, limit=None):
local_pool = multiprocessing.Queue()
n = multiprocesing.Value('i', 0)
@contextlib.contextmanager
def pooled(ctor=ctor, lpool=local_pool, n=n):
# block iff at ... | Making your own connection pool is a BAD idea if your app ever decides to start using multi-threading. Making a connection pool for a multi-threaded application is much more complicated than one for a single-threaded application. You can use something like PySQLPool in that case.
It's also a BAD idea to use an ORM if ... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | I've just been looking for the same sort of thing.
I've found [pysqlpool](https://pythonhosted.org/PySQLPool/tutorial.html) and the [sqlalchemy pool module](https://docs.sqlalchemy.org/en/14/) | Making your own connection pool is a BAD idea if your app ever decides to start using multi-threading. Making a connection pool for a multi-threaded application is much more complicated than one for a single-threaded application. You can use something like PySQLPool in that case.
It's also a BAD idea to use an ORM if ... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.
It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ... | Use `DBUtils`, simple and reliable.
```
pip install DBUtils
``` |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.
It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ... | Making your own connection pool is a BAD idea if your app ever decides to start using multi-threading. Making a connection pool for a multi-threaded application is much more complicated than one for a single-threaded application. You can use something like PySQLPool in that case.
It's also a BAD idea to use an ORM if ... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | Wrap your connection class.
Set a limit on how many connections you make.
Return an unused connection.
Intercept close to free the connection.
Update:
I put something like this in dbpool.py:
```
import sqlalchemy.pool as pool
import MySQLdb as mysql
mysql = pool.manage(mysql)
``` | Old thread, but for general-purpose pooling (connections or any expensive object), I use something like:
```
def pool(ctor, limit=None):
local_pool = multiprocessing.Queue()
n = multiprocesing.Value('i', 0)
@contextlib.contextmanager
def pooled(ctor=ctor, lpool=local_pool, n=n):
# block iff at ... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | Wrap your connection class.
Set a limit on how many connections you make.
Return an unused connection.
Intercept close to free the connection.
Update:
I put something like this in dbpool.py:
```
import sqlalchemy.pool as pool
import MySQLdb as mysql
mysql = pool.manage(mysql)
``` | Replying to an old thread but the last time I checked, MySQL offers connection pooling as part of its drivers.
You can check them out at :
>
> <https://dev.mysql.com/doc/connector-python/en/connector-python-connection-pooling.html>
>
>
>
From TFA, Assuming you want to open a connection pool explicitly (as OP had... |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | In MySQL?
I'd say don't bother with the connection pooling. They're often a source of trouble and with MySQL they're not going to bring you the performance advantage you're hoping for. This road may be a lot of effort to follow--politically--because there's so much best practices hand waving and textbook verbiage in t... | i did it for opensearch so you can refer it.
```
from opensearchpy import OpenSearch
def get_connection():
connection = None
try:
connection = OpenSearch(
hosts=[{'host': settings.OPEN_SEARCH_HOST, 'port': settings.OPE... |
18,808,150 | I have two accounts on my system, an admin account and a user account.
I use the admin account to install macport and have set the default python using
```
sudo port select --set python python27
```
On the user account I can run all the python I need using
```
/opt/local/bin/python
```
but how do I select that... | 2013/09/15 | [
"https://Stackoverflow.com/questions/18808150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816807/"
] | This is really a shell question. `which python` returns the first python on your PATH environment variable. The PATH variable is a list of paths that the shell searches for executables. This is usually set in .profile, .bash\_profile or .bashrc. If you reorder your paths, such that `/opt/local/bin` comes before `/usr/b... | You can use `alias python=/opt/local/bin/python` in your .bashrc, or the equivalent rc file for your shell. |
57,903,358 | I am attempting to build an image for the jetson-nano using yocto poky-warrior and meta-tegra warrior-l4t-r32.2 layer.
I've been following [this thread](https://stackoverflow.com/questions/56481980/yocto-for-nvidia-jetson-fails-because-of-gcc-7-cannot-compute-suffix-of-object/56528785#56528785) because he had the same... | 2019/09/12 | [
"https://Stackoverflow.com/questions/57903358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5999131/"
] | When using Callable in dictConfig, the Callable you put into the value of dictConfig has to be a Callable which returns a Callable as discussed in the Python Bug Tracker:
* <https://bugs.python.org/issue41906>
E.g.
```py
def my_filter_wrapper():
# the returned Callable has to accept a single argument (the LogRec... | I suggest using [loguru](https://github.com/Delgan/loguru) as logging package.
you can easily add a handler for your logger. |
57,903,358 | I am attempting to build an image for the jetson-nano using yocto poky-warrior and meta-tegra warrior-l4t-r32.2 layer.
I've been following [this thread](https://stackoverflow.com/questions/56481980/yocto-for-nvidia-jetson-fails-because-of-gcc-7-cannot-compute-suffix-of-object/56528785#56528785) because he had the same... | 2019/09/12 | [
"https://Stackoverflow.com/questions/57903358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5999131/"
] | When using Callable in dictConfig, the Callable you put into the value of dictConfig has to be a Callable which returns a Callable as discussed in the Python Bug Tracker:
* <https://bugs.python.org/issue41906>
E.g.
```py
def my_filter_wrapper():
# the returned Callable has to accept a single argument (the LogRec... | This is not working because it is a bug or the docs are not correct.
In either case, I opened a ticket with the python folks here: <https://bugs.python.org/issue41906>
Workaround
----------
If you return a function that returns a function things will work fine.
For example:
```
def no_error_logs():
"""
:re... |
31,444,776 | I want to create a bunch of simple geometric shapes (colored rectangles, triangles, squares ...) using pygame and then later analyze their relations and features. I first tried [turtle](https://docs.python.org/2/library/turtle.html) but apparently that is only a graphing library and cannot keep track of the shapes it c... | 2015/07/16 | [
"https://Stackoverflow.com/questions/31444776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4321788/"
] | PyGame is a gaming library - it helps with making graphics and audio and controllers for games. It doesn't have support to detect objects in a preexisting image.
What you want is OpenCV (It has Python bindings) - this is made to "understand" things about an image.
One popular math algorithm used to detect shapes (or ... | Yes, It can, but pygame is also good for making games but unfortunately, you can't convert them to IOS or Android, in the past, there was a program called PGS4A which allowed you to convert pygame projects to android but sadly, the program has been discontinued and now, there is no way. On this case, my sggestion would... |
51,772,333 | I am new to python and would love to know this.
Suppose I want to scrape stock price data from a website to excel. Now the data keeps refreshing every second, how do I refresh the data on my excel sheet automatically using python.
I have read about win32 but couldn’t understand it’s use much.
Any help would be dearly... | 2018/08/09 | [
"https://Stackoverflow.com/questions/51772333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10041192/"
] | As stated in the documentation:
>
> Help on built-in function readlines:
>
>
> readlines(hint=-1, /) method of \_io.TextIOWrapper instance
> Return a list of lines from the stream.
>
>
>
> ```
> hint can be specified to control the number of lines read: no more
> lines will be read if the total size (in bytes/c... | The method `readlines()` reads all lines in a file until it hits the EOF (end of file).
The "cursor" is then at the end of the file and a subsequent call to `readlines()` will not yield anything, because EOF is directly found.
Hence, after `line_3 = fRead.readlines()[3]` you have consumed the whole file but only store... |
34,124,259 | I'm new here and fairly new to python and I have a question. I had a similar question during my midterm a while back and it has bugged me that I cannot seem to figure it out.
The overall idea was that I had to find the longest string in a nested list. So I came up with my own example to try and figure it out but for ... | 2015/12/06 | [
"https://Stackoverflow.com/questions/34124259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5647743/"
] | As Simon mentioned, you should be using `FindAllString` to find all matches. Also, you need to remove the ^ from the beginning of the RE (^ anchors the pattern to the beginning of the string). You should also move the regexp.Compile outside the loop for efficiency. | <https://play.golang.org/p/Q_yfub0k80>
As mentioned here, `FindAllString` returns a slice of all successive matches of the regular expression. But, `FindString` returns the leftmost match. |
49,147,937 | I am trying to get specific coordinates in an image. I have marked a red dot in the image at several locations to specify the coordinates I want to get. In GIMP I used the purist red I could find (HTML notation **ff000**). The idea was that I would iterate through the image until I found a pure shade of red and then pr... | 2018/03/07 | [
"https://Stackoverflow.com/questions/49147937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902160/"
] | You can do it with cv2 this way:
```
image = cv2.imread('image.jpg')
lower_red = np.array([0,0,220]) # BGR-code of your lowest red
upper_red = np.array([10,10,255]) # BGR-code of your highest red
mask = cv2.inRange(image, lower_red, upper_red)
#get all non zero values
coord=cv2.findNonZero(mask)
``` | You can do this with PIL and numpy. I'm sure there is a similar implementation with cv2.
```
from PIL import Image
import numpy as np
img = Image.open('image.png')
width, height = img.size[:2]
px = np.array(img)
for i in range(height):
for j in range(width):
if(px[i,j,0] == 255 & px[i,j,1] == 0 & px[i,j,2]... |
57,462,530 | I need to have a python GUI communicating with an mbed (LPC1768) board. I am able to send a string from the mbed board to python's IDLE but when I try to send a value back to the mbed board, it does not work as expected.
I have written a very basic program where I read a string from the mbed board and print it on Pyth... | 2019/08/12 | [
"https://Stackoverflow.com/questions/57462530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11671221/"
] | If using index labels between 2 and 4 use `loc`:
```
df.loc[2:4, 'number'].max()
```
Output:
```
10
```
If using index integer positions 2nd through the 4th labels, then use `iloc`:
```
df.iloc[2:5, df.columns.get_loc('number')].max()
```
*Note: you must use `get_loc` to get the integer position of the column ... | Even can be used:
```
>>> df.iloc[2:4,:].loc[:,'number'].max()
10
``` |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | First install python 3.6.5, then run
```
pip install mysqlclient==1.3.12
``` | For me, it was a mixture of an old setup tools and missing packages
```
pip install --upgrade setuptools
apt install gcc libssl-dev
``` |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | You may need to install the Python 3 and MySQL development headers and libraries like so:
**For UBUNTU or Debian**
```
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
```
**Red Hat / CentOS**
```
sudo yum install python3-devel mysql-devel
```
Then try
```
pip install mysqlclient
``` | [You can set ssl library path explicitly.](https://github.com/PyMySQL/mysqlclient-python/issues/131#issuecomment-338635251)
```py
LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysqlclient
``` |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | First install python 3.6.5, then run
```
pip install mysqlclient==1.3.12
``` | Better if you install python 64-bit. Then `pip install mysqlclient` will work sure otherwise you can follow these steps[steps to install using python extension packages](https://stackoverflow.com/a/58931018/12181656) |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | Try download and install from wheel instead. Take note of your python version and download the correct one.
[https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient](https://www.lfd.uci.edu/%7Egohlke/pythonlibs/#mysqlclient) | Try pip `install --only-binary :all: mysqlclient`
Worked for me |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | First install python 3.6.5, then run
```
pip install mysqlclient==1.3.12
``` | First try this command
>
> (keep space properly ie, pip space install space --only-binary
> space :all: space mysqlclient)
>
>
>
`pip install --only-binary :all: mysqlclient`
if still error then try this...
Go to this website [Python Extension package](https://www.lfd.uci.edu/~gohlke/pythonlibs/) and press ctrl... |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | [You can set ssl library path explicitly.](https://github.com/PyMySQL/mysqlclient-python/issues/131#issuecomment-338635251)
```py
LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysqlclient
``` | I had the same problem and I fixed in a really stupid way. I just uninstalled python and installed it through the Microsoft Store. |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | 1. Install `build-essential`
`sudo apt-get install build-essential`
2. Install `mysqlclient`
`pip install mysqlclient` | This happened to me when I installed python3.8 from deadsnakes/ppa repository and created virtualenv using it.
Above solutions didn't work for me and after installing `python3.8-dev` it is installed successfully.
`sudo apt install python3.8-dev`
After that
`python3.8 -m pip install mysqlclient==1.3.12` |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | I had look a like problem, on MacOs Catalina, solved with this:
```
ARCHFLAGS="-arch x86_64" pip3 install mysqlclient
``` | 1. Install `build-essential`
`sudo apt-get install build-essential`
2. Install `mysqlclient`
`pip install mysqlclient` |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | You may need to install the Python 3 and MySQL development headers and libraries like so:
**For UBUNTU or Debian**
```
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
```
**Red Hat / CentOS**
```
sudo yum install python3-devel mysql-devel
```
Then try
```
pip install mysqlclient
``` | 1. Install `build-essential`
`sudo apt-get install build-essential`
2. Install `mysqlclient`
`pip install mysqlclient` |
51,062,920 | i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command
`pip install mysqlclient` it return an error:
```
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
I... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51062920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9595624/"
] | [You can set ssl library path explicitly.](https://github.com/PyMySQL/mysqlclient-python/issues/131#issuecomment-338635251)
```py
LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysqlclient
``` | This happened to me when I installed python3.8 from deadsnakes/ppa repository and created virtualenv using it.
Above solutions didn't work for me and after installing `python3.8-dev` it is installed successfully.
`sudo apt install python3.8-dev`
After that
`python3.8 -m pip install mysqlclient==1.3.12` |
60,520,272 | I'm new to python and I've looked up a little bit of info and i cant't find the problem with my code, please help.
Code:
```
array = []
print ('Enter values in array: ')
for i in range(0,5):
n = input("value: ")
array.append(n)
a = input("Enter search term: ")
for i in range(len(array)):
found = False
... | 2020/03/04 | [
"https://Stackoverflow.com/questions/60520272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13003923/"
] | You don't?
>
> Should prettier not be installed locally with your project's dependencies or globally on the machine, the version of prettier that is bundled with the extension will be used.
>
>
>
<https://github.com/prettier/prettier-vscode#prettier-resolution> | It seems like you want Prettier to be your code formatter in VS Code for all of your projects.
In VS Code navigate to:
>
> File > Preferences > Settings
>
>
>
Search for "Default formatter"
And then select "esbenp.prettier-vscode" |
6,361,775 | I know there are quite a few solutions for this problem but mine was peculiar in the sense that, I might get truncated utf16 data and yet have to make the best effort of dealing with conversions where decode and encode will fail with UnicodeDecodeError. So came up with the following code in python.
Please let me know y... | 2011/06/15 | [
"https://Stackoverflow.com/questions/6361775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/684799/"
] | What about:
```
data = open(filename).read()
try:
data = data.decode("utf-16")
except UnicodeDecodeError:
data = data[:-1].decode("utf-16")
```
I.e. if it's truncated mid-way through a code unit, snip the last byte off, and do it again. That should get you back to a valid UTF-16 string, without having to try... | This just jumped out at me as a "best practice" improvement. File accesses should really be wrapped in `with` blocks. This will handle opening and cleaning up for you. |
6,361,775 | I know there are quite a few solutions for this problem but mine was peculiar in the sense that, I might get truncated utf16 data and yet have to make the best effort of dealing with conversions where decode and encode will fail with UnicodeDecodeError. So came up with the following code in python.
Please let me know y... | 2011/06/15 | [
"https://Stackoverflow.com/questions/6361775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/684799/"
] | To tolerate errors you could use the optional second argument to the byte-string's decode method. In this example the dangling third byte ('c') is replaced with the "replacement character" U+FFFD:
```
>>> 'abc'.decode('UTF-16', 'replace')
u'\u6261\ufffd'
```
There is also an 'ignore' option which will simply drop by... | What about:
```
data = open(filename).read()
try:
data = data.decode("utf-16")
except UnicodeDecodeError:
data = data[:-1].decode("utf-16")
```
I.e. if it's truncated mid-way through a code unit, snip the last byte off, and do it again. That should get you back to a valid UTF-16 string, without having to try... |
6,361,775 | I know there are quite a few solutions for this problem but mine was peculiar in the sense that, I might get truncated utf16 data and yet have to make the best effort of dealing with conversions where decode and encode will fail with UnicodeDecodeError. So came up with the following code in python.
Please let me know y... | 2011/06/15 | [
"https://Stackoverflow.com/questions/6361775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/684799/"
] | To tolerate errors you could use the optional second argument to the byte-string's decode method. In this example the dangling third byte ('c') is replaced with the "replacement character" U+FFFD:
```
>>> 'abc'.decode('UTF-16', 'replace')
u'\u6261\ufffd'
```
There is also an 'ignore' option which will simply drop by... | This just jumped out at me as a "best practice" improvement. File accesses should really be wrapped in `with` blocks. This will handle opening and cleaning up for you. |
52,372,489 | I am wanting to get the average brightness of a file in python. Having read a previous question [[Problem getting terminal output from ImageMagick's compare.exe ( Either by pipe or Python )](https://stackoverflow.com/questions/5145508/problem-getting-terminal-output-from-imagemagicks-compare-exe-either-by-pipe]) I have... | 2018/09/17 | [
"https://Stackoverflow.com/questions/52372489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7869335/"
] | This seems to works for me to return the mean as a variable that can be printed. **(This is a bit erroneous. See the correction near the bottom)**
```
#!/opt/local/bin/python3.6
import subprocess
cmd = '/usr/local/bin/convert lena.jpg -format "%[fx:100*mean]" info:'
mean=subprocess.call(cmd, shell=True)
print (mean... | You can probably improve the subprocess, and eliminate the temporary text file with `Popen` + `PIPE`.
```py
cmd=['/usr/bin/convert',
full,
'-format',
'%[fx:100*image.mean]',
'info:']
pid = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.... |
41,861,138 | I am trying to loop through subreddits, but want to ignore the sticky posts at the top. I am able to print the first 5 posts, unfortunately including the stickies. Various pythonic methods of trying to skip these have failed. Two different examples of my code below.
```
subreddit = reddit.subreddit(sub)
... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41861138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750577/"
] | [It looks like you can get the id of a stickied post based on docs](http://praw.readthedocs.io/en/latest/code_overview/models/subreddit.html?highlight=sticky). So perhaps you could get the id(s) of the stickied post(s) (note that with the 'number' parameter of the sticky method you can say give me the first, or second,... | As an addendum to @Al Avery's answer, you can do a complete search for the IDs of all stickies on a given subreddit by doing something like
```
def get_all_stickies(sub):
stickies = set()
for i in itertools.count(1):
try:
sid = sub.sticky(i)
except pawcore.NotFound:
brea... |
41,861,138 | I am trying to loop through subreddits, but want to ignore the sticky posts at the top. I am able to print the first 5 posts, unfortunately including the stickies. Various pythonic methods of trying to skip these have failed. Two different examples of my code below.
```
subreddit = reddit.subreddit(sub)
... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41861138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750577/"
] | [It looks like you can get the id of a stickied post based on docs](http://praw.readthedocs.io/en/latest/code_overview/models/subreddit.html?highlight=sticky). So perhaps you could get the id(s) of the stickied post(s) (note that with the 'number' parameter of the sticky method you can say give me the first, or second,... | Submissions which are stickied have a `sticked` attribute that evaluates to `True`. Add the following to your loop, and you should be good to go.
```
if submission.stickied:
continue
```
In general, I recommend checking the available attributes on the objects you are working with to see if there is something usa... |
41,861,138 | I am trying to loop through subreddits, but want to ignore the sticky posts at the top. I am able to print the first 5 posts, unfortunately including the stickies. Various pythonic methods of trying to skip these have failed. Two different examples of my code below.
```
subreddit = reddit.subreddit(sub)
... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41861138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750577/"
] | Submissions which are stickied have a `sticked` attribute that evaluates to `True`. Add the following to your loop, and you should be good to go.
```
if submission.stickied:
continue
```
In general, I recommend checking the available attributes on the objects you are working with to see if there is something usa... | As an addendum to @Al Avery's answer, you can do a complete search for the IDs of all stickies on a given subreddit by doing something like
```
def get_all_stickies(sub):
stickies = set()
for i in itertools.count(1):
try:
sid = sub.sticky(i)
except pawcore.NotFound:
brea... |
32,221,890 | I want a user to input a list with object in every new line. The user will copy and past a whole list to the program and not enter a new object every time.
For example, here is the users input:
>
> january
>
> february
>
> march
>
> april
>
> may
>
> june
>
>
>
and he gets a list just like th... | 2015/08/26 | [
"https://Stackoverflow.com/questions/32221890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4982967/"
] | You should use <http://eonasdan.github.io/bootstrap-datetimepicker/> datetimePicker, by setting the format of the `dateTimePicker` to `'hh:mm:ss'`
You have to use - `moment.js` - For more formats, you should check: <http://momentjs.com/docs/#/displaying/format/>
I have created a JSFiddle.
<http://jsfiddle.net/jagtx6... | [DEMO](http://jsfiddle.net/SantoshPandu/B4BzK/466/)
HTML
```
<div class="container">
<div class="row">
<div class="col-sm-6 form-group">
<label for="dd" class="sr-only">Time Pick</label>
<input type="text" id="dd" name="dd" data-format="MM/DD/YYYY" placeholder="date" class=... |
32,221,890 | I want a user to input a list with object in every new line. The user will copy and past a whole list to the program and not enter a new object every time.
For example, here is the users input:
>
> january
>
> february
>
> march
>
> april
>
> may
>
> june
>
>
>
and he gets a list just like th... | 2015/08/26 | [
"https://Stackoverflow.com/questions/32221890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4982967/"
] | You should use <http://eonasdan.github.io/bootstrap-datetimepicker/> datetimePicker, by setting the format of the `dateTimePicker` to `'hh:mm:ss'`
You have to use - `moment.js` - For more formats, you should check: <http://momentjs.com/docs/#/displaying/format/>
I have created a JSFiddle.
<http://jsfiddle.net/jagtx6... | Hi: Here's the part of the code that does the format parsing. As you can see `HH` and `H` are for 12 hour format and for seconds just use `ss` as in your example, but for **minutes** you **have to** use `i` or `ii`
```
setters_order = ['hh', 'h', 'ii', 'i', 'ss', 's', 'yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'D', 'DD', 'd'... |
32,221,890 | I want a user to input a list with object in every new line. The user will copy and past a whole list to the program and not enter a new object every time.
For example, here is the users input:
>
> january
>
> february
>
> march
>
> april
>
> may
>
> june
>
>
>
and he gets a list just like th... | 2015/08/26 | [
"https://Stackoverflow.com/questions/32221890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4982967/"
] | [DEMO](http://jsfiddle.net/SantoshPandu/B4BzK/466/)
HTML
```
<div class="container">
<div class="row">
<div class="col-sm-6 form-group">
<label for="dd" class="sr-only">Time Pick</label>
<input type="text" id="dd" name="dd" data-format="MM/DD/YYYY" placeholder="date" class=... | Hi: Here's the part of the code that does the format parsing. As you can see `HH` and `H` are for 12 hour format and for seconds just use `ss` as in your example, but for **minutes** you **have to** use `i` or `ii`
```
setters_order = ['hh', 'h', 'ii', 'i', 'ss', 's', 'yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'D', 'DD', 'd'... |
53,451,057 | I would like to display the following
```
$ env/bin/python
>>>import requests
>>> requests.get('http://dabapps.com')
<Response [200]>
```
as a code sample within a bullet paragraph for Github styled markdown. How do I do it? | 2018/11/23 | [
"https://Stackoverflow.com/questions/53451057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722359/"
] | >
> h:25:59: friend declaration delares a non template function.
>
>
>
You are missing to declare the function as a template that takes `Pairwise<K, V>`:
header.h:
```
#ifndef HEADER_H_INCLUDED /* or pragma once */
#define HEADER_H_INCLUDED /* if you like it */
#include <iostream> // or <ostream>
template<t... | As you write it, you define the operator as a member function, which is very likely not intended. Divide it like ...
```
template<typename K, typename V>
struct Pairwise{
K first;
V second;
Pairwise() = default;
Pairwise(K, V);
//print out as a string in main
friend ostream& operator<<(ostream ... |
53,451,057 | I would like to display the following
```
$ env/bin/python
>>>import requests
>>> requests.get('http://dabapps.com')
<Response [200]>
```
as a code sample within a bullet paragraph for Github styled markdown. How do I do it? | 2018/11/23 | [
"https://Stackoverflow.com/questions/53451057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722359/"
] | As you write it, you define the operator as a member function, which is very likely not intended. Divide it like ...
```
template<typename K, typename V>
struct Pairwise{
K first;
V second;
Pairwise() = default;
Pairwise(K, V);
//print out as a string in main
friend ostream& operator<<(ostream ... | In c++, less is often more...
```
#pragma once
#include<iostream>
#include<string>
// never do this in a header file:
// using std::ostream;
template<typename K, typename V>
struct Pairwise{
K first;
V second;
Pairwise() = default;
Pairwise(K, V);
//print out as a string in main
friend std:... |
53,451,057 | I would like to display the following
```
$ env/bin/python
>>>import requests
>>> requests.get('http://dabapps.com')
<Response [200]>
```
as a code sample within a bullet paragraph for Github styled markdown. How do I do it? | 2018/11/23 | [
"https://Stackoverflow.com/questions/53451057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722359/"
] | >
> h:25:59: friend declaration delares a non template function.
>
>
>
You are missing to declare the function as a template that takes `Pairwise<K, V>`:
header.h:
```
#ifndef HEADER_H_INCLUDED /* or pragma once */
#define HEADER_H_INCLUDED /* if you like it */
#include <iostream> // or <ostream>
template<t... | In c++, less is often more...
```
#pragma once
#include<iostream>
#include<string>
// never do this in a header file:
// using std::ostream;
template<typename K, typename V>
struct Pairwise{
K first;
V second;
Pairwise() = default;
Pairwise(K, V);
//print out as a string in main
friend std:... |
43,513,121 | As per my application requirement, I need to get the server IP and the server name from the python program. But my application is resides inside the specific docker container on top of the Ubuntu.
I have tried like the below
```
import os
os.system("hostname") # to get the hostname
os.system("hostname -i") # to get ... | 2017/04/20 | [
"https://Stackoverflow.com/questions/43513121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3666266/"
] | You won't be able to get the host system's name this way. To get it, you can either define an environment variable, either in your Dockerfile, or when running your container (-e option). Alternatively, you can mount your host `/etc/hostname` file into the container, or copy it...
This is an example run command I use t... | An alternative might be the following:
ENV:
```
NODENAME: '{{.Node.Hostname}}'
```
This will get you the Hostname of the Node, where the container is running as an environment variable (tested on Docker-Swarm / CoreOs Stable). |
43,513,121 | As per my application requirement, I need to get the server IP and the server name from the python program. But my application is resides inside the specific docker container on top of the Ubuntu.
I have tried like the below
```
import os
os.system("hostname") # to get the hostname
os.system("hostname -i") # to get ... | 2017/04/20 | [
"https://Stackoverflow.com/questions/43513121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3666266/"
] | You won't be able to get the host system's name this way. To get it, you can either define an environment variable, either in your Dockerfile, or when running your container (-e option). Alternatively, you can mount your host `/etc/hostname` file into the container, or copy it...
This is an example run command I use t... | you can go for something like this:
```
def determine_docker_host_ip_address():
cmd = "ip route show"
import subprocess
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
return str(output).split(' ')[2]
``` |
43,513,121 | As per my application requirement, I need to get the server IP and the server name from the python program. But my application is resides inside the specific docker container on top of the Ubuntu.
I have tried like the below
```
import os
os.system("hostname") # to get the hostname
os.system("hostname -i") # to get ... | 2017/04/20 | [
"https://Stackoverflow.com/questions/43513121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3666266/"
] | You won't be able to get the host system's name this way. To get it, you can either define an environment variable, either in your Dockerfile, or when running your container (-e option). Alternatively, you can mount your host `/etc/hostname` file into the container, or copy it...
This is an example run command I use t... | ```
import os
os.uname().nodename
``` |
7,052,874 | I had a custom script programmed and it is using the authors own module that is hosted on Google code in a Mercurial repo. I understand how to clone the repo but this will just stick the source into a folder on my computer. Is there a proper way to add the module into my python install to make it available for my proje... | 2011/08/13 | [
"https://Stackoverflow.com/questions/7052874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893341/"
] | In exactly the same way. Just pass the address of the repo to `pip install`, using the `-e` parameter:
```
pip install -e hg+http://code.google.com/path/to/repo
``` | If the module isn't on pypi, clone the repository with Hg and see if there's a setup.py file. If there is, open a command prompt, cd to that directory, and run:
```
python setup.py install
``` |
48,601,123 | Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge but once it's added it doesn't work.I was thinking when detaching the object with expunge it will work. and I can't find a sol... | 2018/02/03 | [
"https://Stackoverflow.com/questions/48601123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8551016/"
] | This error happens when you try to add an object to a session but it is already loaded.
The only line that I see you use .add function is at the end where you run:
`connection.connect.add(article)`
So my guess is that this Model is already loaded in the session and you don't need to add it again. You can add a try, e... | unloading all objects from session and then adding it again in session might help.
```py
db.session.expunge_all()
db.session.add()
``` |
48,601,123 | Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge but once it's added it doesn't work.I was thinking when detaching the object with expunge it will work. and I can't find a sol... | 2018/02/03 | [
"https://Stackoverflow.com/questions/48601123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8551016/"
] | Had the same issue, not sure you implemented the models as same as I did, but in my case at least, I had in the table's model - i.e:
```
product_items = relationship(...)
```
So later when I tried to do
```
products = session.query(Products).all()
one_of_the_products = products[0]
new_product = ProductItem(produc... | unloading all objects from session and then adding it again in session might help.
```py
db.session.expunge_all()
db.session.add()
``` |
10,732,812 | I'm trying to read some numbers from a text file and convert them to a list of floats, but nothing I try seems to work right.
Here's my code right now:
```
python_data = open('C:\Documents and Settings\redacted\Desktop\python_lengths.txt','r')
python_lengths = []
for line in python_data:
python_lengths.append(lin... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10732812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367212/"
] | That is happening because `.split()` always returns a list of items even if there was just 1 element present. If you change your `python_lengths.append(line.split())` to `python_lengths.extend(line.split())` you will get your flat list you expected. | @eumiro's answer is correct, but here is something else that can help:
```
numbers = []
with open('C:\Documents and Settings\redacted\Desktop\python_lengths.txt','r') as f:
for line in f.readlines():
numbers.extend(line.split())
numbers.sort()
print numbers
``` |
10,732,812 | I'm trying to read some numbers from a text file and convert them to a list of floats, but nothing I try seems to work right.
Here's my code right now:
```
python_data = open('C:\Documents and Settings\redacted\Desktop\python_lengths.txt','r')
python_lengths = []
for line in python_data:
python_lengths.append(lin... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10732812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367212/"
] | That is happening because `.split()` always returns a list of items even if there was just 1 element present. If you change your `python_lengths.append(line.split())` to `python_lengths.extend(line.split())` you will get your flat list you expected. | ```
def floats_from_file(f):
for line in f:
for word in line.split():
yield float(word)
with open('C:/Documents and Settings/redacted/Desktop/python_lengths.txt') as f:
python_lengths = list(floats_from_file(f))
python_lengths.sort()
print python_lengths
```
Note that you can use forwar... |
41,528,941 | I'm new to python and html. I am trying to retrieve the number of comments from a page using requests and BeautifulSoup.
In this example I am trying to get the number 226. Here is the code as I can see it when I inspect the page in Chrome:
```
<a title="Go to the comments page" class="article__comments-counts" href="... | 2017/01/08 | [
"https://Stackoverflow.com/questions/41528941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7389440/"
] | The page, and specifically the number of comments, does involve JavaScript to be loaded and shown. But, *you don't have to use Selenium*, make a request to the API behind it:
```
import requests
with requests.Session() as session:
session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) A... | This page use JavaScript to get the comment number, this is what the page look like when disable the JavaScript:
[](https://i.stack.imgur.com/V8mcE.png)
You can find the real url which contains the number in Chrome's Developer tools:
[![enter image de... |
26,575,303 | Hello people I hope you an help me out with this problem:
I am currently implementing an interpreter for a scripting language. The language needs a native call interface to C functions, like java has JNI. My problem is, that i want to call the original C functions without writing a wrapper function, which converts the... | 2014/10/26 | [
"https://Stackoverflow.com/questions/26575303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180673/"
] | Yes we can. No FFI library needed, no restriction to C calls, only pure C++11.
```
#include <iostream>
#include <list>
#include <iostream>
#include <boost/any.hpp>
template <typename T>
auto fetch_back(T& t) -> typename std::remove_reference<decltype(t.back())>::type
{
typename std::remove_reference<decltype(t.ba... | The way to do this is to use pointers to functions:
```
void (*native)(int a, int b) ;
```
The problem you will face is finding the address of the function to store in the pointer is system dependent.
On Windoze, you will probably be loading a DLL, finding the address of the function by name within the DLL, then st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.