qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
69,647,562 | Why does initializing the array `arr` work when it is done as a list comprehension (I think that is what the following example is --not sure), but not when each array location is initialized individually?
For example, this works:
(a)
```
arr=[]
arr=[0 for i in range(5)]
```
but (b),
```
arr=[]
arr[0]=0
arr[1]=0
... | 2021/10/20 | [
"https://Stackoverflow.com/questions/69647562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242713/"
] | Firstly, there is no point in declaring a variable if you rebind it later anyway:
```
arr = [] # <-- this line is entirely pointless
arr = [0 for i in range(5)]
```
Secondly, the two expressions
```
[0 for i in range(5)]
[0] * 5
```
**create** a new `list` object, whereas
```
arr[0] = 0
```
mutates an existin... | It doesn't pre-allocate. It's basically just appending in a loop, just in nice form (syntactic sugar).
Why it doesn't pre-allocate? Because to pre-allocate, we would need to know the length of the iterable, which may be a generator and it would use it up. And also, comprehension can have an if clause, limiting what ev... | 16,537 |
15,213,428 | Recently I was going through the "Using Python App Engine with Google Cloud SQL" tutorial on Google Developers Academy website. However, I stumbled upon on the first part of the exercise "Building an application with a local MySQL instance". I could not connect the sample code (main.py) to my local MySQL instance. Wond... | 2013/03/04 | [
"https://Stackoverflow.com/questions/15213428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2130139/"
] | The answer is to use `add_action('edit_link','save_data')` and `add_option('name_of_option')` instead of `add_post_meta` view full results here [MetaBox Links](https://gist.github.com/davidchase/df9adeb1e03b88691899) | After some experiments, I figured out how to save data from custom metabox in link manager into db as post meta key/value (wp\_postmeta).
If someone needs, here is a working example:
```
action( 'add_meta_boxes', 'add_link_date' );
function add_link_date()
{
add_meta_box( 'link-date-meta-box', 'Link Date', 'link_d... | 16,539 |
50,876,292 | Given its link, I'd like to capture an online video (say from YouTube) for further processing **without downloading it on the disk**. What I mean by this is that I'd like to load it directly to memory whenever possible. According to these links:
<http://answers.opencv.org/question/24012/reading-video-stream-from-ip-... | 2018/06/15 | [
"https://Stackoverflow.com/questions/50876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | You can achieve this by using `youtube-dl` and `ffmpeg`:
* Install the latest version of [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html).
* Then do `sudo pip install --upgrade youtube_dl`
* Build `ffmpeg` with HTTPS support. You can do this by [turning on the `--enable-gnutls` option](https://askubuntu.... | Using pafy you can have a more elegant solution:
```
import cv2
import pafy
url = "https://www.youtube.com/watch?v=NKpuX_yzdYs"
video = pafy.new(url)
best = video.getbest(preftype="mp4")
capture = cv2.VideoCapture()
capture.open(best.url)
success,image = capture.read()
while success:
cv2.imshow('frame', image)... | 16,540 |
27,321,523 | I have a Raspberry Pi that I use as a multi-purpose 24/7 device for DLNA, CIFS, VPN etc. Now I bought a TellStick, that is a USB device that can send 433MHz radio commands to wireless power switches, dimmers etc. The manufacturer offers sources and tools for linux, which is really great, btw.
Using a special command (... | 2014/12/05 | [
"https://Stackoverflow.com/questions/27321523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1901272/"
] | While your question is too "opinion-like", there's an almost instant solution:
[nginx - How to run a shell script on every request?](https://stackoverflow.com/questions/22891148/nginx-how-to-run-a-shell-script-on-every-request)
But since you're talking about R-Pi, maybe you will find Python builtin [CGIHTTPServer](ht... | Here a full & working RealLife™ perl's example
----------------------------------------------
...using [Dancer](https://metacpan.org/pod/Dancer)
```
# cpan Dancer
$ dancer -a MyApp
$ cd MyApp
$ cat ./lib/MyApp.pm # need to be edited, see bellow
$ bin/app.pl
```
Now you can call the URL
```
http://127.0.0.1:3000/sw... | 16,545 |
73,479,698 | I am trying to build a Docker image but when I build it, I get the error message : 'E: Unable to locate package libxcb-util1'.
Here is my Dockerfile :
```
`# $DEL_BEGIN`
FROM python:3.9.7-buster
WORKDIR /prod
COPY design_interface design_interface
COPY requirements.txt requirements.txt
COPY setup.py setup.py
RUN pip... | 2022/08/24 | [
"https://Stackoverflow.com/questions/73479698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19739078/"
] | Updating gradle solves the problem.
There are different ways to update the gradle, as explained in their official website: <https://gradle.org/install/>
*Assuming that you are a windows user*:
Downloading binary files of gradle and extracting the folder to the directory "c:/gradle" is enough.
* Download binary file... | To fix the issue, I've reverted to `cordova-android` version `9.1.0`. I've no idea, as of now, why `cordova-android` version `10` points to `gradle`, which as of now isn't possible to download... | 16,546 |
66,797,173 | I am using transformers pipeline to perform sentiment analysis on sample texts from 6 different languages. I tested the code in my local Jupyterhub and it worked fine. But when I wrap it in a flask application and create a docker image out of it, the execution is hanging at the pipeline inference line and its taking fo... | 2021/03/25 | [
"https://Stackoverflow.com/questions/66797173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10422855/"
] | I was having a similar issue. It seems that starting the app somehow polutes the memory of transformers models. Probably something to do with how Flask does threading but no idea why. What fixed it for me was doing the things that are causing trouble (loading the models) in a different thread.
```
import threading
de... | Flask uses port 5000. In creating a docker image, it's important to make sure that the port is set up this way. Replace the last line with the following:
```
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
```
Be also sure to `import os` at the top
Lastly, in `Dockerfile`, add
```
EXPOSE 5000
CMD [... | 16,547 |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Maybe you could try [Markdown](http://www.freewisdom.org/projects/python-markdown/) instead, and convert it to HTML on the fly? | You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:
<http://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py>
(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.) | 16,548 |
6,699,201 | What would I have to do to make a Python application I am writing open up a web page in the default browser? It doesn't need to be told what the webpage is or anything, it'll be opening one that I've already chosen.
I found some documentation [here](http://docs.python.org/library/webbrowser.html) but I always get a sy... | 2011/07/14 | [
"https://Stackoverflow.com/questions/6699201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841843/"
] | The URL needs to be in a string.
```
webbrowser.open('http://www.google.com/')
``` | Have a look at the `webbrowser` module. | 16,557 |
64,082,288 | I masked a *sorted* 1-D numpy array using the method below (which follows a solution proposed [here](https://stackoverflow.com/questions/64076440/accessing-a-large-numpy-array-while-preserving-its-order)):
```
def get_from_sorted(sorted,idx):
mask = np.zeros(sorted.shape, bool)
mask[idx] = True
return s... | 2020/09/26 | [
"https://Stackoverflow.com/questions/64082288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815653/"
] | I believe your goal as follows.
* Your question has the following 2 questions.
1. You want to know the method for creating new Google Document including the text data.
2. You want to know the method for adding more text data to the existing Google Document.
* You want to achieve this using Drive API with googleapis ... | From the [Media Uploads example](https://github.com/googleapis/google-api-nodejs-client#media-uploads) for `googleapis@60.0.1`, you can create a Google Document with a given title and content inside a given folder with
```
const drive = google.drive({ version: 'v3', auth });
const filename = '<filename>';
const paren... | 16,558 |
57,358,927 | I would like to use the twilight or twilight\_shifted colormap in my 2.7 python build, but it seems to be python 3 only? Is there some way to manually add it? | 2019/08/05 | [
"https://Stackoverflow.com/questions/57358927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1608765/"
] | `twilight` was added in matplotlib v3.0 which is python 3 only. But we can find where it was added in the source code are re-engineer it.
In the code below, you just need to grab the data used for `twilight` from the matplotlib source on github, by following this [link](https://github.com/matplotlib/matplotlib/blob/f2... | You can create a new custom colormap as shown in this [tutorial](https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipulation.html).
The data for the "twilight" and "twilight\_shifted" colormaps is [here](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_cm_listed.py). | 16,559 |
65,579,018 | **What I intend to do :**
I have an excel file with Voltage and Current data which I would like to extract from a specific sheet say 'IV\_RAW'. The values are only from 4th row and are in columns D and E.
Lets say the values look like this:
| V(voltage) | I(Current) |
| --- | --- |
| 47 | 1 |
| 46 | 2 |
| 45 | 3 |
| ... | 2021/01/05 | [
"https://Stackoverflow.com/questions/65579018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14944185/"
] | The following uses `pandas` which you should definitly take a look at. with `sheet_name` you set the sheet\_name, `header` is the row index of the header (starting at 0, so Row 4 -> 3), `usecols` defines the columns using A1 notation.
The last line filters the dataframe. If I understand correctly, then you want Voltag... | you can try this,
```
import openpyxl
tWorkbook = openpyxl.load_workbook("YOUR_FILEPATH")
tDataBase = tWorkbook.active
voltageVal= "D4"
currentVal= "E4"
V = tDataBase[voltageVal].value
I = tDataBase[currentVal].value
``` | 16,561 |
26,513,125 | I have some django view handler functions which are structured like this
```
def view1(request):
# Check for authorization
if not isAuthorized(request):
return HttpResponse('Foo error', status=401)
return HttpResponse('view1 data')
def view2(request):
# Check for authorization
if not isAuthorized(req... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26513125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20392/"
] | The line `int ans = tmp->next;` appears to be the source of the problem. This is attempting to take the `next` pointer in the node, convert it to an `int`, and return it. What you (almost certainly) want is to retrieve the data from the node and return that, with something like `int ans = tmp->num;`.
Of course, that's... | First, you are trying to delete `tmp` node, but top node still exist and value has to be returned as ans or top->next or in this situation top->num. Why do you initialize node `tmp` in the function when node `tmp` is a parameter? Why should node \* &top be in the function parameters instead of `tmp`.
value = top->num ... | 16,564 |
56,439,798 | I have a camera running on rtsp link. I want to write python code to check if the camera is live or dead. Similar to using curl to check http if url is working or not. What is a similar command can one use to check rtsp url status?
I have tried using openRTSP on terminal and I want to use it as python script
openRTSP... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56439798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6006820/"
] | You can call FFMPEG to extract a snapshot. If successful stream is accessible.
Test this functionality (exctracting snapshot from rtsp) with <https://videonow.live/broadcast-ip-camera-or-stream/> per tutorial at <https://broadcastlivevideo.com/publish-ip-camera-stream-to-website/>.
Command to extract should be someth... | You can use the `opencv_python` module to play rtsp stream.
Sample codes:
```
import cv2
cap=cv2.VideoCapture("rtsp://admin:admin123@test_url_here")
ret,frame = cap.read()
while ret:
ret,frame = cap.read()
cv2.imshow("frame",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindo... | 16,567 |
27,466,862 | There's something wrong with my OSX system and python that no amount of googling has fixed. I've uninstalled all traces of python except the system python package with OSX that I'm not supposed to uninstall, and then started afresh with a new python from python.org, and installed pip.
Now...not sure if this particula... | 2014/12/14 | [
"https://Stackoverflow.com/questions/27466862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119779/"
] | `sudo` overrides your `export`. It's the same Python (as you can easily tell from the version information it prints) but it runs with a different (system default) `PYTHONPATH`.
This is one of the jobs of `sudo`; it sanitizes the environment to safe defaults. You may be able to tweak this, but the real question is, wha... | What do you get when you compare the output of `which pip` and `sudo which pip`?
On my system I get different outputs. If you do, I'm not sure how to fix that, but you could try to force the sudo'd python to look in the correct directory:
```
import sys
sys.path.insert(0, '/lib/python2.7/site-packages/')
import pip
... | 16,568 |
21,783,840 | I have a CSV file that has numerous data points included in each row, despite belonging to the same column. Something similar to this:
```
A, B, C, X, Y, Z
```
Now, what I would like to do is to reformat the file such that the resulting CSV is:
```
A, B, C
X, Y, Z
```
I'm not too sure how to go about this / expre... | 2014/02/14 | [
"https://Stackoverflow.com/questions/21783840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179795/"
] | Just write two rows to an output [`csv.writer()` object](http://docs.python.org/2/library/csv.html#csv.writer):
```
with open(inputfilename, 'rb') as infh, open(outputfilename, 'wb') as outfh:
reader = csv.reader(infh)
writer = csv.writer(outfh)
for row in reader:
writer.writerows([row[:3], row[3:... | You could probably use python's [CSV module](http://docs.python.org/2/library/csv.html)
Example:
```
#!/usr/bin/env python
import csv
with open("input.csv", "r") as input_file, open("output.csv", "w+"):
input_csv, output_csv = csv.reader(input_file), csv.writer(output_file);
for row in input_csv:
out... | 16,569 |
74,304,917 | I'm having trouble trying to find the parameters of a gaussian curve fit.
The site <https://mycurvefit.com/> provides a good answer fairly quickly. However, my implementation with python's curve\_fit(), from the scipy.optimize library, is not providing good results (even when inputting the answers).
For instance, the... | 2022/11/03 | [
"https://Stackoverflow.com/questions/74304917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14703689/"
] | One way to do it is using window functions. The first one ([**`lag`**](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.lag.html#pyspark.sql.functions.lag)) marks the row if it is different than the previous. The second ([**`sum`**](https://spark.apache.org/docs/latest/api... | Use window functions. get ranks per group of blocks and through away any rows that rank higher than 1. Code below
```
(df.withColumn('index', row_number().over(Window.partitionBy().orderBy('ID','Block')))#create an index to reorder after comps
.withColumn('BlockRank', rank().over(Window.partitionBy('Block').orderBy('... | 16,572 |
63,574,704 | I have the following `Dockerfile`:
```
# beginning of the the docker ...
ARG SIGNAL_ID
CMD python ./my_repo/my_main.py --signal_id $SIGNAL_ID
```
I also have a `docker-compose.yml` with all the needed information for the service
```
version: '3'
services:
my_app:
build: .
# additional info ...
```
How would... | 2020/08/25 | [
"https://Stackoverflow.com/questions/63574704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9253013/"
] | You can convert an integral value to its decimal representation with [`std::to_string`](https://en.cppreference.com/w/cpp/string/basic_string/to_string):
```
std::string const dec = std::to_string(num);
```
If you have a character array, say `char a[4]`, you can copy the data there element-wise:
```
for (std::size_... | a way is decomposing the number in hundred, tens and units... modulo can help and log10 will be useful too:
this is going to be a nice work around if you arent allowed to convert to string
here an example:
```
int value = 256;
int myArray[3];
auto m = static_cast<int>(ceil(log10(value)));
for(int i =0; i < m; ++i)
{... | 16,573 |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | you can do this, but it works backwards. you implement `__float__()` in your new type and then `sin()` will work with your class.
in other words, you don't adapt sine to work on other types; you adapt those types so that they work with sine.
this is better because it forces consistency. if there is no obvious mapping... | Typically the answer to questions like this is "you don't" or "use duck typing". Can you provide a little more detail about what you want to do? Have you looked at the remainder of the protocol methods for numeric types?
<http://docs.python.org/reference/datamodel.html#emulating-numeric-types> | 16,575 |
66,583,626 | In plotly I can create a histogram as e.g. [in this example code from the documentation](https://plotly.com/python/histograms/):
```
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()
```
which results to:
[`, this:
[](https://i.stack.imgur.com/8ksQb.png)
And reading off the chart those values wo... | In the same Plotly Histogram documentation, there's a section called [Accessing the counts yaxis values](https://plotly.com/python/histograms/#accessing-the-counts-yaxis-values), and it explains that the y values are calculated by the JavaScript in the browser when the figure renders so you can't access it in the figur... | 16,584 |
14,251,877 | I worked out a code that make sense to me but not python since I'm new to python.
Check my code here:
```
checksum_algos = ['md5','sha1']
for filename in ["%smanifest-%s.txt" % (prefix for prefix in ['', 'tag'], a for a in checksum_algos)]:
f = os.path.join(self.path, filename)
if isfile(f):
yield f
```
... | 2013/01/10 | [
"https://Stackoverflow.com/questions/14251877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/921082/"
] | You're overthinking it.
```
for filename in ("%smanifest-%s.txt" % (prefix, a)
for prefix in ['', 'tag'] for a in checksum_algos):
``` | Or you need [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> [i for i in itertools.product(('', 'tag'), ('sha', 'md5'))]
[('', 'sha'), ('', 'md5'), ('tag', 'sha'), ('tag', 'md5')]
``` | 16,587 |
62,601,766 | I am trying to use SIFT for feature detection with Python, but it is no longer part of OpenCV **or** OpenCV contrib.
With OpenCV opencv-contrib-python (both versions 4.2.0.34, the latest as of this question), I get:
```
>>> import cv2
>>> cv2.SIFT_create()
Traceback (most recent call last):
File "<stdin>", line 1, ... | 2020/06/26 | [
"https://Stackoverflow.com/questions/62601766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8605685/"
] | The patent for SIFT expired this Mar 2020. But the opencv might not be updated by moving the SIFT to free open source collection.
See this issue: <https://github.com/skvark/opencv-python/issues/126>
To rebuild with the non-free components:
```
git clone --recursive https://github.com/skvark/opencv-python.git
cd open... | From [the issue](https://github.com/skvark/opencv-python/issues/126):
to rebuild with the non-free components:
```
git clone --recursive https://github.com/skvark/opencv-python.git
cd opencv-python
export CMAKE_ARGS="-DOPENCV_ENABLE_NONFREE=ON"
python setup.py bdist_wheel
``` | 16,589 |
46,016,131 | ```
I have a list of tuples `data`:
data =[(array([[2, 1, 3]]), array([1])),
(array([[2, 1, 2]]), array([1])),
(array([[4, 4, 4]]), array([0])),
(array([[4, 1, 1]]), array([0])),
(array([[4, 4, 3]]), array([0]))]
```
For simplicity's sake, this list here only has 5 tuples.
When I run the following code, it seem... | 2017/09/02 | [
"https://Stackoverflow.com/questions/46016131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6802252/"
] | In the first two cases you're looping through `list`, in the last one you're accessing `tuple`
Not sure what you want to achieve, but instead of `data[0]`, `data[:1]` would work. | If your data looks like this:
```
data =[([[2, 1, 3]], [1]),
([[2, 1, 2]], [1]),
([[4, 4, 4]]), [0]),
([[4, 1, 1]], [0]),
([[4, 4, 3]], [0])]
for [a], b in data:
print a, b
```
Output:
```
[2, 1, 3] [1]
[2, 1, 2] [1]
[4, 4, 4] [0]
[4, 1, 1] [0]
[4, 4, 3] [0]
``` | 16,590 |
1,239,538 | I've been trying to use [suds](https://fedorahosted.org/suds/wiki) for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through [the examples](https://fedoraho... | 2009/08/06 | [
"https://Stackoverflow.com/questions/1239538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54283/"
] | At this early stage in suds development, the easiest way to get to the raw XML content is not what one would expect.
The examples on the site show us with something like this:
```
client = Client(url)
result = client.service.Invoke(subm)
```
however, the result is a pre-parsed object that is great for access by Pyt... | You could take a look at a library such as [soaplib](http://wiki.github.com/jkp/soaplib): its a really nice way to consume (and serve) SOAP webservices in Python. The latest version has some code to dynamically generate Python bindings either dynamically (at runtime) or statically (run a script against some WSDL).
[d... | 16,591 |
65,514,398 | I have a radar chart. Need to change the grid from circle-form to pentagon-form. Currently, I have this output:
[](https://i.stack.imgur.com/mDLeM.jpg)
Whereas I expect smth like this:
[. The working code for your example would be
```py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from ... | 16,592 |
6,259,623 | >
> **Possible Duplicate:**
>
> [How does Python compare string and int?](https://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int)
>
>
>
An intern was just asking me to help debug code that looked something like this:
```
widths = [image.width for image in images]
widths.append(374)... | 2011/06/07 | [
"https://Stackoverflow.com/questions/6259623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | Python 2.x compares *every* built-in type to every other. From the [docs](http://docs.python.org/library/stdtypes.html#comparisons):
>
> Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a ... | When comparing values of incompatible types in python 2.x, the ordering will be arbitrary but consistent. This is to allow you to put values of different types in a sorted collection.
In CPython 2.x any string will always be higher than any integer, but as I said that's arbitrary. The actual ordering does not matter, ... | 16,593 |
27,914,648 | I am using geopy to geocode some addresses and I want to catch the timeout errors and print them out so I can do some quality control on the input. I am putting the geocode request in a try/catch but it's not working. Any ideas on what I need to do?
Here is my code:
```
try:
location = geolocator.geocode(my_addres... | 2015/01/13 | [
"https://Stackoverflow.com/questions/27914648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860317/"
] | Try this:
```
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
my_address = '1600 Pennsylvania Avenue NW Washington, DC 20500'
geolocator = Nominatim()
try:
location = geolocator.geocode(my_address)
print(location.latitude, location.longitude)
except GeocoderTimedOut as e:
pri... | You may be experiencing this problem because you tried to request this address multiple times and they temporarily blocked you or slowed you down because of their [usage policy](https://operations.osmfoundation.org/policies/nominatim/). It states no more requests than one per second and that you should cache your resul... | 16,596 |
51,963,377 | I am trying to write a discriminator that evaluates patches of an image.
Therefore I generate 32x32 non-overlapping patches from the input and then concatenate them on a new axis.
The reason I am using a time-distributed layer is that at the end, the discriminator should evaluate the whole image as true or fake. Thus,... | 2018/08/22 | [
"https://Stackoverflow.com/questions/51963377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880918/"
] | You need to put your cropping operations in a function and then use that function in a `Lambda` layer:
```
def my_cropping(a):
cropping_list = []
n_patches = 256/32
for x in range(256//32):
for y in range(256//32):
cropping_list += [
K.expand_dims(
Croppin... | I ran into the same issue and it solved indeed by wrapping a Lambda layer around the tensor as @today proposed.
Thanks for that hint, it pointed me in the right direction. I wanted to turn a vector into a diagonal matrix to
I wanted to concatenate a vector with a square image and by turning the vector in a diag matr... | 16,598 |
820,671 | I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:
```
class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?... | 2009/05/04 | [
"https://Stackoverflow.com/questions/820671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69882/"
] | When you declare instance variables using `__slots__`, Python creates a [descriptor object](https://docs.python.org/2/howto/descriptor.html) as a class variable with the same name. In your case, this descriptor is overwritten by the class variable `m` that you are defining at the following line:
```
m = None # my at... | `__slots__` works with instance variables, whereas what you have there is a class variable. This is how you should be doing it:
```
class MyClass( object ) :
__slots__ = ( "m", )
def __init__(self):
self.m = None
a = MyClass()
a.m = "?" # No error
``` | 16,599 |
30,252,726 | I am generating pdf using html template with python `pisa.CreatePDF` API,
It works well with small html, but in case of huge html it takes lot of time. Is there any alternative ? | 2015/05/15 | [
"https://Stackoverflow.com/questions/30252726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2373367/"
] | I did few changes in html which results pisa.createPDF works fast for me.
I am using html of almost **2 MB**, contains single table with almost more than **10,000 rows**. So I break them into multiple tables and tried again. Its surprised me, initially with single table it took almost **40 minutes (2590 seconds)** to g... | You can try [pdfkit](https://pypi.python.org/pypi/pdfkit):
```
import pdfkit
pdfkit.from_file('test.html', 'out.pdf')
```
Also see [this question](https://stackoverflow.com/q/23359083/3489230) which describes solutions using PyQt. | 16,606 |
51,271,225 | header
output:
```
array(['Subject_ID', 'tube_label', 'sample_#', 'Relabel',
'sample_ID','cortisol_value', 'Group'], dtype='<U14')
```
body
output:
```
array([['STM002', '170714_STM002_1', 1, 1, 1, 1.98, 'HC'],
['STM002', '170714_STM002_2', 2, 2, 2, 2.44, 'HC'],], dtype=object)
testing = np.concaten... | 2018/07/10 | [
"https://Stackoverflow.com/questions/51271225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029062/"
] | You need to align array dimensions first. You are currently trying to combine 1-dimensional and 2-dimensional arrays. After alignment, you can use [`numpy.vstack`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html).
Note `np.array([A]).shape` returns `(1, 7)`, while `B.shape` returns `(2, 7)`. A m... | Look at numpy.vstack and hstack, as well as the axis argument in np.append. Here it looks like you want vstack (i.e. the output array will have 3 columns, each with the same number of rows). You can also look into numpy.reshape, to change the shape of the input arrays so you can concatenate them. | 16,607 |
67,044,398 | to import the absolute path from my laptop I type:
==================================================
```
import os
print(os.getcwd())
```
he gives me the path no problem, but when I create a Document "ayoub.txt" in the path absolute, and I #call this document with:
================================================... | 2021/04/11 | [
"https://Stackoverflow.com/questions/67044398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14819475/"
] | I ran your code with some dummy data, the `cast<String>` for `categories` works for me. However, you have not added the cast to `skills` and `otherLanguages`. Have you checked the line number of the error? If the problem is definitely with `categories`, could you please add some sample data to the question. | Try to replace `List<String> categories, skills, otherLanguages;` to dynamic and remove the casting
`List<dynamic> categories, skills, otherLanguages;` | 16,610 |
43,716,699 | ```
python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x03BBC1F0>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "C:\Python27\lib\site-packages\d... | 2017/05/01 | [
"https://Stackoverflow.com/questions/43716699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7946534/"
] | You seem to have installed the JWT package, which is only compatible with Python 3.4+. The rest-framework-jwt app is trying to import that rather than PyJWT which is compatible with 2.7.
Remove that installation with `pip uninstall jwt`. Once removed you'll want to install PyJWT like so:
```
pip install PyJWT
``` | Not need to uninstall jwt. Just upgrade your PyJWT
```
pip install PyJWT --upgrade
``` | 16,611 |
1,507,091 | I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does no... | 2009/10/01 | [
"https://Stackoverflow.com/questions/1507091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678/"
] | [@nosklo's twisted-based solution](https://stackoverflow.com/a/1507370/8053001) is elegant and workable, but if you want to avoid the dependency on twisted, the task is still doable, e.g:
```
import multiprocessing
def query_with_timeout(dbc, timeout, query, *a, **k):
conn1, conn2 = multiprocessing.Pipe(False)
su... | Use [adbapi](http://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.html). It allows you to do a db call asynchronously.
```
from twisted.internet import reactor
from twisted.enterprise import adbapi
def bogusQuery():
return dbpool.runQuery("SELECT SLEEP(10)")
def printResult(l):
# function... | 16,612 |
17,213,455 | Im kind of new to python. Im trying to remove the first sentence from a string using the full stop as the delimiter. Is split the right method to be using in this instance? Im not getting the desired result...
```
def get_summary(self):
if self.description:
s2 = self.description.split('.', 1)[1]
r... | 2013/06/20 | [
"https://Stackoverflow.com/questions/17213455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2342568/"
] | You can use [`String.split`](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29):
```
String cmd = "command atr1 art22 atr333 art4444";
String[] parts = cmd.split(" ");
```
The split method permits using a regular expression. This is useful for example if the amount of whitesp... | Here a few options, sorted from easy/annoying-in-the-end to powerful/hard-to-learn
* "your command pattern".split( " " ) gives you an array of strings
* [`java.util.Scanner`](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html) lets you take out one token after the other, and it has some handy helpers ... | 16,622 |
44,486,483 | So I've begun working on this little translator program that translates English to German with an input. However, when I enter more than one word I get the words I've entered, followed by the correct translation.
This is what I have so far:
```
data = [input()]
dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'studen... | 2017/06/11 | [
"https://Stackoverflow.com/questions/44486483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8144709/"
] | Changing your code to this should provide a first step to what you're looking for.
```
data = raw_input()
dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'student':'schueler', 'of':'der', 'german':'deutschen', 'language': 'sprache'}
from itertools import takewhile
def find_suffix(s):
return ''.join(takewhile(str... | ```
data = [input()]
dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'student':'schueler', 'of the':'der', 'german':'deutschen', 'language': 'sprache'}
for word in data:
if word in dictionary:
print dictionary[word],
```
Explanation:
for every word in your input if that word in present in your dictiona... | 16,625 |
63,826,975 | I get the following error when I want to import matplotlib.pyplot on the Visual Studio's jupyter-notebook.
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in
----> 1 import matplotlib.pyplot as plt
~/minicond... | 2020/09/10 | [
"https://Stackoverflow.com/questions/63826975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12409079/"
] | If you want all Gold customers, then `Customers` should be the first table in the `LEFT JOIN`. There is also no need for a subquery on `customers`. However, MS Access does want one on `Transactions`:
```
SELECT c.CustId, NZ(SUM(t.Value)) AS Total
FROM Customers as c LEFT JOIN
(SELECT t.*
FROM Transactions a... | ***Edit:*** Simplified query
```
SELECT Customers.CustID, Sum(Transactions.tValue) AS Total
FROM Customers LEFT JOIN Transactions ON Customers.CustID = Transactions.CustID
WHERE (Transactions.xDate BETWEEN #2020/01/03# AND #2020/01/04#) AND (Customers.CustType='Gold')
GROUP BY Customers.CustID;
```
You can sum total... | 16,627 |
34,783,867 | I have two pandas series like following.
```
bulk_order_id
Out[283]:
3 523
Name: order_id, dtype: object
```
and
```
luster_6_loc
Out[285]:
3 Cluster 3
Name: Clusters, dtype: object
```
Now I want a new series which would look like this.
```
Cluster 3 523
```
I am doing following in python
```
cluste... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34783867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2927983/"
] | You could pass to `pd.Series` values of `luster_6_loc` as index and values of `bulk_order_id` as values:
```
bulk_order_id = pd.Series(523, index=[3])
cluster_6_loc= pd.Series('Cluster 3', index=[3])
cluster_final = pd.Series(bulk_order_id.values, cluster_6_loc.values)
In [149]: cluster_final
Out[149]:
Cluster 3 ... | Not sure whether I'm understanding your question correctly, but what's wrong with `pd.concat()` ([see docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html)):
```
s1 = pd.Series(data=['523'], index=[3])
3 523
dtype: object
s2 = pd.Series(data=['Cluster 3'], index=[3])
3 Cluster 3
dtyp... | 16,630 |
67,434,998 | I'm new to python / pandas. I've got multiple csv files in a directory. I want to remove duplicates in all the files and save new files to another directory.
Below is what I've tried:
```
import pandas as pd
import glob
list_files = (glob.glob("directory path/*.csv"))
for file in list_files:
df = pd.read_csv(file... | 2021/05/07 | [
"https://Stackoverflow.com/questions/67434998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15862144/"
] | The problem is because of the `{}` that are around your file, pandas thinks that the first level of the JSON are the columns and thus it uses just Browser History as a column. You can use this code to solve your problem:
```
import pandas as pd
df = pd.DataFrame(json.load(open('BrowserHistory.json', encoding='cp850'))... | Because your objects are in a list at the second level down of your JSON, you can't read it directly into a dataframe using `read_json`. Instead, you could read the json into a variable, and then create the dataframe from that:
```py
import pandas as pd
import json
f = open("BrowserHistory.json")
js = json.load(f)
df... | 16,633 |
52,949,128 | I'm doing a project that involves analyzing WhatsApp log data.
After preprocessing the log file I have a table that looks like this:
```
DD/MM/YY | hh:mm | name | text |
```
I could build a graph where, using a chat with a friend of mine, I plotted a graph of the number of text per month and the mean number of word... | 2018/10/23 | [
"https://Stackoverflow.com/questions/52949128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8425613/"
] | Suppose that the table you have is a .csv file that looks like this (call it msgs.csv):
```
date;time;name;text
22/10/2018;11:30;Maria;Hello how are you
23/10/2018;11:30;Justin;Check this
23/10/2018;11:31;Justin;link
22/11/2018;11:30;Maria;Hello how are you
23/11/2018;11:30;Justin;Check this
23/12/2018;11:31;Justin;li... | It's best to convert the strings into datetime objects
```
from datetime import datetime
datetime_object = datetime.strptime('22/10/18', '%d/%m/%y')
```
When converting from a string, remember to use the correct seperators, ie "-" or "/" to match the string, and the letters in the format template on the right hand ... | 16,634 |
6,324,412 | After answering a question here on SO about finding a city in a
user-supplied question, I started thinking about the *best* way to
search for a string in a text when you have a limited data-set as this one.
`in` and `find` matches against a substring, which is not wanted. Reqular
expressions using "word boundaries" wo... | 2011/06/12 | [
"https://Stackoverflow.com/questions/6324412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297323/"
] | In the **Language** menu select your corresponding language. For example **H** and then **html** | 1. Check, if you have saved the documents as .HTML and not as .txt
2. in the menu, choose Settings>Style configurator...
and in the list in the left pan select html, check if the colors for different tags are being shown in the color blocks. if yes, chosse a font and then save and exit.
3. Check only after you save the... | 16,636 |
63,781,794 | I got this error message when I was installing python-binance.
Error message is in the link below please check
<https://docs.google.com/document/d/1VE0Ux_ji9RoK0NIrPD3BSbs60sTaxThk3boxsvh051c/edit>
Anyone knows how to fix it? | 2020/09/07 | [
"https://Stackoverflow.com/questions/63781794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14236836/"
] | You're trying to install [`email` from PyPI](https://pypi.org/project/email/) which is a very old outdated Python2-only package.
`email` is now [a module in the stdlib](https://docs.python.org/3/library/email.html). You don't need to install it, it must always be available. Just import and use. | You might have outdated setuptools, try:
```
pip install --upgrade setuptools
```
Then continue trying to install the module you want.
Usually these kinds of problems can be solved by googling the error: in this case you should try searching with "python setup.py egg\_info".
Also, try to give a more descriptive ti... | 16,646 |
16,375,251 | This is part of a project I am working on for work.
I want to automate a Sharepoint site, specifically to pull data out of a database that I and my coworkers only have front-end access to.
I FINALLY managed to get mechanize (in python) to accomplish this using Python-NTLM, and by patching part of it's source code to ... | 2013/05/04 | [
"https://Stackoverflow.com/questions/16375251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629404/"
] | Well, in the end I came down to the following possible solutions:
* **Run Chrome headless** and collect the html output (thanks to koenp for the link!)
* **Run PhantomJS**, a headless browser with a javascript api
* **Run HTMLUnit**; same thing but for Java
* **Use Ghost.py**, a **python-based** headless browser (that... | Well you will need something that both understands the DOM and understand Javascript, so that comes down to a headless browser of some sort. Maybe you can take a look at the [selenium webdriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp), but I guess you already did that. I don't hink there is an easy way of doi... | 16,648 |
59,591,862 | Essentially I'm trying to do something that is stated here [Changing variables in multiple Python instances](https://stackoverflow.com/questions/9302789/changing-variables-in-multiple-python-instances)
but in java.
I want to reset a variable in all instances of a certain class so something like:
```
public class New... | 2020/01/04 | [
"https://Stackoverflow.com/questions/59591862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12652681/"
] | This is probably far from a Todo but it'll give you some clarification of what to do.
```js
const box = document.querySelector('.box');
let inputTodo = document.getElementById('inputTodo');
const inputTodoHandler = (event) => {
if(event.which == 13 || event.keyCode == 13) {
addTodo(event.target.value);
... | use the Database system in your Website using sql or any server that stores the info in cloud that store/edit/delete and acess the database in your right/desired location | 16,649 |
17,960,696 | I was trying to install a package using easy\_install, errors happened "processing dependencies", looks like it cannot locate a package, here's the error I got
---
```
Processing dependencies for python-pack==1.5.0beta2
Searching for python-pack==1.5.0beta2
Reading http://pypi.python.org/simple/python-pack/
Couldn't ... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17960696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2636377/"
] | It turned out that the jar files in ~/.m2/repository have been corrupted. This issue has been solved by deleting everything in the repository and do a:
>
> mvn clean install
>
>
>
All the classes can be resolved now. | The answer is more likely that you need to add the dependency to your pom.xml file:
```
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-hibernate</artifactId>
<version>${dropwizard.version}</version>
</dependency>
``` | 16,653 |
33,324,083 | I am having trouble learning to plot a function in python. For example I want to create a graph with these two functions:
```
y=10x
y=5x+20
```
The only way I found was to use the following code
```
import matplotlib.pyplot as plt
plt.plot([points go here], [points go here])
plt.plot([points go here], [points go he... | 2015/10/24 | [
"https://Stackoverflow.com/questions/33324083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5484597/"
] | There are quite a lot of answers here which exlain that, but let me give you another one.
A string is interned into the String literal pool only in two situations: when a class is loaded and the String was a literal or compile time constant. Otherwise only when you call `.intern()` on a String. Then a copy of this st... | One thing you have to know is, that Strings are Objects in Java. The variables s1 - s4 do not point directly to the text you stored. It is simply a pointer which says where to find the Text within your RAM.
1. It is false because you compare the Pointers, not the actual text. The text is the same, but these two String... | 16,654 |
46,132,556 | When I try to install python3-tk for python3.5 on ubuntu 16.04 I get the following error, what should I do?
python3-tk : Depends: python3 (< 3.5) but 3.5.1-3 is to be installed | 2017/09/09 | [
"https://Stackoverflow.com/questions/46132556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3604079/"
] | Activity transition is always expensive and we should switch from one activity to another only when we are switching the context. A `fragment` is a portion of UI in an activity. Same fragment can be used with multiple activities. Just like activity a fragment has its own lifecycle and `setContentView(int layoutResID)` ... | Please refer to :-
<https://github.com/waleedsarwar86/BottomNavigationDemo>
and complete explanation in
<http://waleedsarwar.com/posts/2016-05-21-three-tabs-bottom-navigation/>
You will get a running code with the explanation here. | 16,656 |
27,713,681 | ```
10:01:36 adcli
10:01:36 sshd[
10:01:37 adcli
10:01:37 adcli
10:01:37 sshd[
10:01:37 adcli
10:01:37 adcli
10:01:37 sshd[
10:01:37 sshd[
10:01:37 adcli
10:01:37 adcli
10:01:37 sshd[
10:01:37 sshd[
10:01:37 adcli
10:01:37 adcli
10:01:37 adcli
10:01:37 runma
10:01:37 runma
10:01:37 sshd[
10:01:37 adcli
10:01:37 adcli
1... | 2014/12/30 | [
"https://Stackoverflow.com/questions/27713681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406840/"
] | As Respawned alluded to, there is no easy answer that will work in all cases. That being said, here are two approaches which seem to work fairly well. Both having upsides and downsides.
Approach 1
==========
Internally, the `getTextContent` method uses whats called an `EvaluatorPreprocessor` to parse the PDF operator... | This question is actually extremely hard if you want to do it to perfection... or it can be relatively easy if you can live with solutions that work only some of the time.
First of all, realize that `getTextContent` is intended for searchable text extraction and that's all it's intended to do.
It's been suggested in ... | 16,661 |
55,482,197 | I start to learn Django framework so I need to install latest python, pip, virtualenv and django packets on my mac.
I try to do it with brew, but I got some strange behavior.
At first, python3 installed not in /usr/bin/ but in /Library/Frameworks/Python.framework directory:
```
$ which python
/usr/bin/python
$ which... | 2019/04/02 | [
"https://Stackoverflow.com/questions/55482197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11301741/"
] | Instead of using brew you can simply use "venv".
To create a virtual environment you can run -->
```
python3 -m venv environment_name
```
Example: If you want to create an virtual environment for django with name django\_env
```
python3 -m venv django_env
```
"-m" flag checks for sys.path and executes main modul... | ### Python3 Virtualenv Setup
Requirements:
* Python3
* Pip3
```sh
$ brew install python3 #upgrade
```
Pip3 is installed with Python3
**Installation**
To install virtualenv via pip run:
```sh
$ pip3 install virtualenv
```
**Usage**
Creation of virtualenv:
```sh
$ virtualenv -p python3 <desired-path>
```
Ac... | 16,664 |
71,020,555 | Like in other programing languages - python or JS, when we create a rest api specifically post for the request body we attract some JSON Object
EX:
url: .../employee (Post)
request body: {option: {filter: "suman"}}
In Python or JS we can just do request\_body.option.filter and get the data
How can I achieve the sa... | 2022/02/07 | [
"https://Stackoverflow.com/questions/71020555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9661967/"
] | What about this?
```
table1 %>%
left_join(cbind(table2, n = 1)) %>%
group_by(Col1, Col2, Col3) %>%
mutate(n = sum(n, na.rm = TRUE))
```
and we will see
```
Col1 Col2 Col3 n
<chr> <chr> <chr> <dbl>
1 Al F C 1
2 Al UF UC 1
3 Al P < 0
4 Cu F C ... | **1)** Append an n=1 column to table2 and an n=0 column to table 1 and then sum n by group.
```
table2 %>%
mutate(n = 1L) %>%
bind_rows(table1 %>% mutate(n = 0L)) %>%
group_by(Col1, Col2, Col3) %>%
summarize(n = sum(n), .groups = "drop")
```
giving:
```
# A tibble: 10 x 4
Col1 Col2 Col3 n
<chr... | 16,667 |
17,818,502 | Consider this sample python code. It reads from stdin and writes to a file.
```
import sys
arg1 = sys.argv[1]
f = open(arg1,'w')
f.write('<html><head><title></title></head><body>')
for line in sys.stdin:
f.write("<p>")
f.write(line)
f.write("</p>")
f.write("</body></html>")
f.close()
```
Suppose I ... | 2013/07/23 | [
"https://Stackoverflow.com/questions/17818502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199882/"
] | Just do
```
>>> import sys
>>> f = sys.stdout
>>> f.write('abc')
abc
```
Now you just need to do `f = sys.stdout` instead of `f = open(fileName)`. (And remove `f.close()`)
**Also**, Please consider using the following syntax for files.
```
with open(fileName, 'r') as f:
# Do Something
```
The file automatica... | Yes, in python, you can alias every class / function / method etc. Just assign the value you want to use to another variable:
```
import sys
f = sys.stdout
```
Now every method you call on `f` will get called on `sys.stdout`. You can do this with whatever you like, for example also with `i = sys.stdin` etc. | 16,669 |
18,263,733 | I am new to python and django i am creating first tutorial app.
I created app file using following command:
```
C:\Python27\Scripts\django-admin.py startproject mysite
```
After that successfully created a file in directory
But how to run python manage.py runserver i am getting error `not recognized as an internal... | 2013/08/15 | [
"https://Stackoverflow.com/questions/18263733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582761/"
] | You just need to `cd` into mysite from there.
Use `cd mysite` from the command line. Then run `python manage.py runserver` and the dev server will startup in the current (or a new if there inst a current) browser window.
To visualize this for you:
```
current_dir/ <-- your here now
mysite/ < -- use cd... | You need to go to the directory that the app you created resides in then run the command `manage.py runserver` on windows or `python manage.py runserver` in a Unix Terminal.
It is typical to create a separate directory for your Django projects. A typical directory would be:
```
C:\DjangoProjects\
```
You would then... | 16,675 |
27,692,051 | **Is there any way to disable the syntax highlighting in SublimeREPL-tabs when a script is running?**
Please see this question for context: [Red lines coming up after strings in SublimeREPL (python)?](https://stackoverflow.com/q/25693151/1426065)
For example, when python-scripts run in Sublime REPL, apostrophes (') i... | 2014/12/29 | [
"https://Stackoverflow.com/questions/27692051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183985/"
] | Go to
Sublime Text > Preferences > Package Settings > SublimeREPL > Settings - User
(If your 'Settings - User' is empty, first copy in the contents of 'Settings - Default')
under "repl\_view\_settings": add:
```
,
"syntax": "Packages/Text/Plain text.tmLanguage"
```
so mine is now:
```
// standard sublime view... | As @joe.dawley wrote in the comments to the original question there is a way to manually disable syntax highlighting in SublimeREPL by using the go to anything-command **(Ctrl + Shift + P)** and enter **"sspl"** to set the syntax to plain text. | 16,676 |
44,549,369 | I am trying to calculate the Kullback-Leibler divergence from Gaussian#1 to Gaussian#2
I have the mean and the standard deviation for both Gaussians
I tried this code from <http://www.cs.cmu.edu/~chanwook/MySoftware/rm1_Spk-by-Spk_MLLR/rm1_PNCC_MLLR_1/rm1/python/sphinx/divergence.py>
```
def gau_kl(pm, pv, qm, qv):
... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44549369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7879074/"
] | The following function computes the KL-Divergence between any two multivariate normal distributions (no need for the covariance matrices to be diagonal) (where numpy is imported as np)
```
def kl_mvn(m0, S0, m1, S1):
"""
Kullback-Liebler divergence from Gaussian pm,pv to Gaussian qm,qv.
Also computes KL di... | If you are still interested ...
That function expects diagonal entries of covariance matrix of multivariate Gaussians, not standard deviations as you mention. If your inputs are univariate Gaussians, then both `pv` and `qv` are vectors of length 1 for variances of corresponding Gaussians.
Besides, `len(pm)` correspo... | 16,677 |
55,537,213 | I'm following Adrian Rosebrock's tutorial on recognising digits on an RPi, so no tesseract or whatever:
<https://www.pyimagesearch.com/2017/02/13/recognizing-digits-with-opencv-and-python/>
But it doesn't recognise decimal points, so I've been trying really hard to create a part that would help to do that. I think I'v... | 2019/04/05 | [
"https://Stackoverflow.com/questions/55537213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2810806/"
] | If JSON is used to exchange data, it *must* use UTF-8 encoding (see [RFC8259](https://www.rfc-editor.org/rfc/rfc8259)). UTF-16 and UTF-32 encodings are no longer allowed. So it is not necessary to escape the degree character. And I strongly recommend against escaping unnecessarily.
*Correct and recommended*
```
{
"... | JSON uses unicode to be encoded, but it is specified that you can use `\uxxxx` escape codes to represent characters that don't map into your computer native environment, so it's perfectly valid to include such escape sequences and use only plain ascii encoding to transfer JSON serialized data. | 16,678 |
69,045,992 | So I am trying to install and import pynput in VSCode but its showing me an error every time I try to do it. I used VSCode's in-built terminal to install it using pip and typed the following :
`pip install pynput` but this error is shown : `Fatal error in launcher: Unable to create process using '"c:\users\vicks\appdat... | 2021/09/03 | [
"https://Stackoverflow.com/questions/69045992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16225182/"
] | you need to set a default lang in case there is no preferredLanguages or error occurred like this
```
static String lang ='';
List? languages = [];
languages = await Devicelocale.preferredLanguages;
if(languages?.isNotEmpty ==true){
lang = languages[0] ?? "en";
}else{
... | You should add the bang `!` at the end `languages[0]!` to remove the nullability. | 16,679 |
51,775,370 | I'm running Airflow on a clustered environment running on two AWS EC2-Instances. One for master and one for the worker. The worker node though periodically throws this error when running "$airflow worker":
```
[2018-08-09 16:15:43,553] {jobs.py:2574} WARNING - The recorded hostname ip-1.2.3.4 does not match this insta... | 2018/08/09 | [
"https://Stackoverflow.com/questions/51775370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3299397/"
] | The hostname is set when the task instance runs, and is set to `self.hostname = socket.getfqdn()`, where socket is the python package `import socket`.
The comparison that triggers this error is:
```
fqdn = socket.getfqdn()
if fqdn != ti.hostname:
logging.warning("The recorded hostname {ti.hostname} "
"doe... | I had a similar problem on my Mac. It fixed it setting `hostname_callable = socket:gethostname` in `airflow.cfg`. | 16,682 |
55,337,221 | I'm trying to connect another computer in local network via python (subprocesses module) with this commands from CMD.exe
* `net use \\\\ip\C$ password /user:username`
* `copy D:\file.txt \\ip\C$`
Then in python it look like below.
But when i try second command, I get:
>
> "FileNotFoundError: [WinError 2]"
>
>
>
... | 2019/03/25 | [
"https://Stackoverflow.com/questions/55337221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299639/"
] | The issue is that `copy` is a built-in, not a real command in Windows.
Those Windows messages are awful, but `"FileNotFoundError: [WinError 2]"` doesn't mean one of source & destination files can't be accessed (if `copy` failed, you'd get a normal Windows message with explicit file names).
Here, it means that the *co... | you need make sure you have right to add a file.
i have testted successfully after i corrected the shared dirctory's right. | 16,685 |
50,777,013 | I am just a beginner to a tensorflow and trying to install TensorFlow with CPU support only.
Initially, I downloaded and installed Python 3.5.2 version from <https://www.python.org/downloads/release/python-352/>
After successful installation, I ran the command `pip3 install --upgrade tensorflow` which installed tenso... | 2018/06/09 | [
"https://Stackoverflow.com/questions/50777013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8141116/"
] | I copied ***msvcp140.dll*** to path ***C:\Users\PCName\AppData\Local\Programs\Python\Python35***
and it worked for me.
I also switched back to tensorflow 1.8 from 1.5. | You can download the package from the url <https://www.microsoft.com/en-us/download/details.aspx?id=53587> and install it. This will solve the issue. | 16,686 |
57,473,982 | in vs code, for some reason, i cannot run any python code because vs code puts in python instead of py in cmd.
it shows this :
>
> [Running] python -u "c:\Users..."
>
>
>
but is supposed to show this :
>
> [Running] py -u "c:\Users\
>
>
>
i have tried searching online how to fix it, the error message:
**... | 2019/08/13 | [
"https://Stackoverflow.com/questions/57473982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11921290/"
] | Well you can change the interpreter that Code uses by pressing `Ctrl+Shift+P` and then searching for `Python: Select Interpreter`, this should help when it comes to running the code in the IDE. If that doesn't work you could just try and use the built in terminal in Code to run the code manually with the `py` command. | In VSCODE debug mode I have launch json as follows and then i can easily debug the code with breakpoints
```
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",... | 16,689 |
20,047,117 | I have my code as below.
```
def test():
print num1
print num
num += 10
if __name__ == '__main__':
num = 0
num1 = 3
test()
```
When executing the above python code I get the following output.
```
3
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "<stdin>", line 2, in ... | 2013/11/18 | [
"https://Stackoverflow.com/questions/20047117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1939389/"
] | If you do not want direct child selector, just add a parent reference for the nested elements.
This will make your thing work.
You can add the below.
```
.red .blue h1 {
color: blue;
}
```
**[WORKING DEMO](http://jsfiddle.net/N7FcB/1/)**
To enforce your div to render the color blue, you just need to add the re... | Or maybe like that:
```
.red > h1 {
color: red;
}
.blue h1 {
color: blue;
}
```
[fiddle](http://jsfiddle.net/sxVcL/3/).
This is 100%. | 16,690 |
42,742,519 | I am new to programming and was trying to create a program in python that creates a staircase with size based on the user input. The program should appear as shown below:

This is the code I have so far;
```
steps = int(input('How many steps? '))
print('__')
fo... | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7696748/"
] | To get the correct amount of steps, you have to change the for loop to:
```
for i in range(steps-1):
```
This is because you want to print the `|_`'s one less time than there are steps; your "top" step `__` already counts as one step.
The whole thing (changed some other things to make the formatting better):
```
s... | It is simpler to consider that `n` is the current step and given the step size (2) then you just need `2n` for your placement:
```
steps = 5
print('__')
for n in range(1, steps):
print(' '*n*2 + '|_')
print('_'*steps*2 + '|')
```
Output:
```
__
|_
|_
|_
|_
__________|
```
You can abstract ... | 16,700 |
22,814,973 | im working on python application that requiring database connections..I had developed my application with sqlite3 but it start showing the error(the database is locked).. so I decided to use MySQL database instead.. and it is pretty good with no error..
the only one problem is that I need to ask every user using my app... | 2014/04/02 | [
"https://Stackoverflow.com/questions/22814973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2980054/"
] | It depends (more "depends" in the answer).
If you need to share the data between the users of your application - you need a mysql database server somewhere setup, your application would need to have an access to it. And, the performance can really depend on the network - depends on how heavily would the application us... | If your application is a stand-alone system such that each user maintains their own private database then you have no alternative to install MySQL on each system that is running the application. ~~You cannot bundle MySQL into your application such that it does not require a separate installation.~~
There is an embedde... | 16,704 |
51,583,196 | I am learning python django i am developing one website but i am struggling with URL pattern
I am Sharing my code for URL pattern i don't understand where i am getting wrong
url.py
```
urlpatterns = [
url(r'^$',views.IndexView.as_view(),name='index'),
# /music/id/
url(r'^picture/(?P<pk>[0-9]+)$',views.De... | 2018/07/29 | [
"https://Stackoverflow.com/questions/51583196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6246189/"
] | [](https://i.stack.imgur.com/xtW0A.png)
You can try this way:
```
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.red,
elevation: 0,
child: Container(
decoration: BoxDecoration(
... | floatingActionButton: FloatingActionButton(
onPressed: (){},
backgroundColor: Color(0xf0004451),
elevation: 10,
```
child: Container(
padding: const EdgeInsets.all(14.0),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(
Radius.circular(60),
),
... | 16,705 |
15,832,700 | I am newbie in python and I am trying to launch python script with a module writen on C. I am getting Segmentation fault (core dumped) error when I am trying to launch python script.
Here is a C code:
```
// input_device.c
#include "Python.h"
#include "input.h"
static PyObject* input_device_open(PyObject* self, Py... | 2013/04/05 | [
"https://Stackoverflow.com/questions/15832700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904234/"
] | Is it legitimate to return `NULL` without setting an exception, or making sure that one has been set by a function you have called? I thought that `NULL` was a signal that Python could go look for an exception to raise for the user.
I am not sure that the `Py_INCREF(pyfd);` is necessary; doesn't the object already hav... | Your function receives a tuple of arguments. You need to extract the integer from the tuple:
```
static PyObject* input_device_open(PyObject* self, PyObject* args)
{
int fd, nr;
PyObject* pyfd;
if (!PyArg_ParseTuple(args, "i", &nr))
return NULL;
``` | 16,707 |
54,366,675 | i have a list like below:
```
[3,2,4,5]
```
and i want a list like below:
```
[['1','2','3'],['1','2'],['1','2','3','4'],['1','2','3','4','5']]
```
i mean i want to have a list that is created by the count of another list.
I want to iterate each with string.
how can i write it in python
i tried this code:
```
... | 2019/01/25 | [
"https://Stackoverflow.com/questions/54366675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6655937/"
] | You can use `range` with `list`, and list comprehension:
```
>>> a = [3, 2, 4, 5]
>>> [list(range(1, x+1)) for x in a]
[[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5]
```
And to make all strings, add `map` with `str`:
```
>>>[list(map(str, range(1, x+1))) for x in a]
[['1', '2', '3'], ['1', '2'], ['1', '2', '3', ... | try this code. I tried to make as easy as possible
```
lol=[3,2,4,5]
ans=[]
temp=[]
for i in lol:
for j in range(1,i+1):
temp.append(j)
ans.append(temp)
temp=[]
print(ans)
```
Hope it helps | 16,708 |
42,183,476 | Can someone please help me with the python equivalent of the curl command:
python equivalent of `curl -X POST -F "name=blahblah" -F "file=@blahblah.jpg"`
I would like to you python requests module, but I am not clear on the options to use. | 2017/02/12 | [
"https://Stackoverflow.com/questions/42183476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7552038/"
] | It depends on how you are going to use this reference.
1) There is no straight way to get component DOM reference within template:
```
import {Directive, Input, ElementRef, EventEmitter, Output, OnInit} from '@angular/core';
@Directive({selector: '[element]', exportAs: 'element'})
export class NgElementRef imple... | As of Angular 8, the following provides access to the ElementRef and native element.
```
/**
* Export the ElementRef of the selected element for use with template references.
*
* @example
* <button mat-button #button="appElementRef" appElementRef></button>
*/
@Directive({
selector: '[appElementRef]',
expo... | 16,709 |
43,192,626 | I'm new to pandas & numpy. I'm running a simple program
```
labels = ['a','b','c','d','e']
s = Series(randn(5),index=labels)
print(s)
```
getting the following error
```
s = Series(randn(5),index=labels) File "C:\Python27\lib\site-packages\pandas\core\series.py", line 243, in
__init__
raise_cast_failure=... | 2017/04/03 | [
"https://Stackoverflow.com/questions/43192626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385691/"
] | I suspect you have your imports wrong.
If you add this to your code:
```
from pandas import Series
from numpy.random import randn
labels = ['a','b','c','d','e']
s = Series(randn(5),index=labels)
print(s)
a 0.895322
b 0.949709
c -0.502680
d -0.511937
e -1.550810
dtype: float64
```
It runs fine.
That ... | It seems you need [`numpy.random.rand`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html) for random `floats` or [`numpy.random.randint`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html) for random `integers`:
```
import pandas as pd
import numpy as np
np.rand... | 16,710 |
21,729,196 | I've got the following dictionary:
```py
d = {
'A': {
'param': {
'1': {
'req': True,
},
'2': {
'req': True,
},
},
},
'B': {
'param': {
'3': {
'req': True,
},
... | 2014/02/12 | [
"https://Stackoverflow.com/questions/21729196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2047097/"
] | The generator expressions you assign to `req[key]` binds on the `key` variable. But `key` changes from 'A' to 'B' in the loop. When you iterate over the first generator expression, it will evaluate `key` to 'B' in its `if` condition, even though `key` was 'A' when you created it.
The conventional way to bind to a vari... | This is because upon execution of the generator, the *latest* value of `key` is used.
Suppose the `for key in d:` iterates over the keys in the order `'A', 'B'`, the 1st generator is supposed to work with `key = 'A'`, but due to closure issues, it uses the item with `'B'` as key. And this has no `'1'` sub-entry.
Even... | 16,711 |
30,871,488 | The familiar pythonic slicing conventions of `myList[-1:][0]` and `myList[-1]` are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?
Error verbiage for posterity:
>
> `IndexError: Cursor instances do not support negativ... | 2015/06/16 | [
"https://Stackoverflow.com/questions/30871488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2355364/"
] | You need to use [$location.path()](https://docs.angularjs.org/api/ng/service/$location)
```
// given url http://blo.c/news
var path = $location.path();
// => "/news"
```
If you are using HTML5 mode you must ensure [$locationProvider.html5Mode(true)](https://docs.angularjs.org/guide/$location#html5-mode) is set so `$... | Use the `$location.path` function to get the url. To get what's after the url, use `split`
```
$location.path.split(/\{1}/)[1]
``` | 16,712 |
54,701,639 | I have a python operator in my DAG. The python callable function is returning a bool value. But, when I run the DAG, I get the below error.
>
> TypeError: 'bool' object is not callable
>
>
>
I modified the function to return nothing but then again I keep getting the below error
>
> ERROR - 'NoneType' object is ... | 2019/02/15 | [
"https://Stackoverflow.com/questions/54701639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4017926/"
] | The argument name gives it away. You are passing the result of a call rather than a callable.
```
python_callable=check_poke(129600,600)
```
The second error states that the callable is called with 25 arguments. So a `lambda:` won't work. The following would work but ignoring 25 arguments is really questionable.
``... | Agree with **@Dan D.** for the issue; but it's perplexing why his solution didn't work (it certainly works in `python` *shell*)
See if this finds you any luck (its just verbose variant of **@Dan D.**'s solution)
```
from typing import Callable
# your original check_poke function
def check_poke(arg_1: int, arg_2: int... | 16,715 |
29,829,470 | I'm trying to get range-rings on my map, with the position of the image above the user's location, but the map doesn't appear when I test it and the user's location doesn't seem to show up on the map. I don't know what went wrong, I followed a tutorial on a website.
This is the code:
```html
<!DOCTYPE html>
<html>
... | 2015/04/23 | [
"https://Stackoverflow.com/questions/29829470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3832981/"
] | geolocation runs asynchronously.
You may either create the map/marker when it returns a result or define a default-coordinate and update map/marker when it returns a result.
The 2nd approach is preferable, because you wouldn't get a map at all when geolocation fails.
A simple implementation using a MVCObject, which ... | I think you should include your Google Api key.
Try to add the script below :
```
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>
``` | 16,717 |
53,405,006 | I am trying to set up a Dockerfile for my project and am unsure how to set a JAVA\_HOME within the container.
```
FROM python:3.6
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN... | 2018/11/21 | [
"https://Stackoverflow.com/questions/53405006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6465715/"
] | You need to actually install Java inside your container, but I would suggest rather finding a Pyspark docker image, or adding Python to the Openjdk images so that you don't need to mess with too many environment variables
More specifically, `JAVA_HOME=/Library/Java/JavaVirtualMachines` is a only available as a path to... | To set environment variables, you can declare them in your dockerfile like so:
```
ENV JAVA_HOME="foo"
```
or
```
ENV JAVA_HOME foo
```
In fact, you already set an environment variable in the example you posted.
See [documentation](https://docs.docker.com/engine/reference/builder/#env) for more details. | 16,718 |
49,564,238 | I have below piece of code in python which I am using to get the component name of the JIRA issue some of them are single value in component field and some of them are multiple values in component field. My issue is that component field could have values with different name e.g R ABC 1.1 , R Aiapara 2.3A1(Active) etc.I... | 2018/03/29 | [
"https://Stackoverflow.com/questions/49564238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513848/"
] | Using regex:
```
import re
s1 = "R ABC 4.4"
s2 = "R Ciapara 4.4A1(Active)"
print(re.findall(r"\d+\.\d+", s1))
print(re.findall(r"\d+\.\d+", s2))
```
**Output:**
```
['4.4']
['4.4']
``` | I feel like I am not quite understanding your question, so I will try to answer as best I can, but feel free to correct me if I get anything wrong.
This function will get all the numbers from the string in a list:
```
def getNumber(string):
numbers = ".0123456789"
result = []
isNumber = False
for i in... | 16,719 |
28,570,268 | My file contains this format [{"a":1, "c":4},{"b":2, "d":5}] and I want to read this file into a list in python. The list items should be {"a":1, "c":4} and {"b":2, "d":5}. I tried to read into a string and then typecasting into a list but that is not helping. It is reading character by character. | 2015/02/17 | [
"https://Stackoverflow.com/questions/28570268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4394027/"
] | You can "convert" a string that contains a list to an actual list like this
```
>>> import ast
>>> ast.literal_eval('[{"a":1, "c":4},{"b":2, "d":5}]')
[{'a': 1, 'c': 4}, {'b': 2, 'd': 5}]
```
You can of course sub out the literal string for the data you read from file | Another, more dirty option is this (it will produce list of strings):
```
a = str('[{"a":1, "c":4},{"b":2, "d":5}]')
b = list()
for i in a.replace('[','').replace(']','').split(sep='},'):
b.append(i+'}')
b[len(b)-1] = b[len(b)-1].replace('}}','}')
for i in b:
i
'{"a":1, "c":4}'
'{"b":2, "d":5}'
```
Since... | 16,720 |
3,172,236 | I am writing a piece of code which will extract words from running text. This text can contain delimiters like \r,\n etc. which might be there in text.
I want to discard all these delimiters and only extract full words. How can I do this with Python? any library available for crunching text in python? | 2010/07/03 | [
"https://Stackoverflow.com/questions/3172236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348663/"
] | Assuming your definition of "word" agrees with that of the regular expression module (`re`), that is, letters, digits and underscores, it's easy:
```
import re
fullwords = re.findall(r'\w+', thetext)
```
where `thetext` is the string in question (e.g., coming from an `f.read()` of a file object `f` open for reading,... | Assuming your delimiters are whitespace characters (like space, `\r` and `\n`), then basic [`str.split()`](http://docs.python.org/library/stdtypes.html#str.split) does what you want:
```
>>> "asdf\nfoo\r\nbar too\tbaz".split()
['asdf', 'foo', 'bar', 'too', 'baz']
``` | 16,722 |
74,200,925 | I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value.
Example of what I'm trying to do:
```
list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0]
'area1': [83740], 'area2': [18150... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74200925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248393/"
] | You can use a generator expression to multiply the pairs of values in your dictionary, then `sum` the output of that:
```py
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
total = sum(v[0]*v[1] for v in lst.values())
# 101890.0
``` | You can find the area using list comprehension.
Iterate through `lst.values()` -> `dict_values([[395.0, 212.0], [165.0, 110.0]])` and multiply the elements. Finally, use `sum` to find out the total.
```
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
area = sum([i[0]*i[1] for i in lst.values()])
# 101890.0
... | 16,723 |
15,497,896 | I am very new to programming and am converting a fortran90 code into python 2.7. I have done fairly well with it so far but have hit a difficult spot. I need to write this subroutine in Python but I don't understand the fortran notation and can't find any information on what the python equivalent of the Read(1,\*) line... | 2013/03/19 | [
"https://Stackoverflow.com/questions/15497896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In fortran, `open(1,FILE=TRIM(filenameBC),RECL=2000)` opens the file with name `filenameBC`. The `TRIM` part is unnecessary as the fortran runtime library will do that for you (it's python equivalent is `filenameBC.rstrip()`). The `RECL=2000` part here is also a little fishy. I don't think that it does anything here --... | `READ(1,*)` is reading .... something out of your file and not storing it, i.e. just throwing it away. All those `READ(1,*)` statements are just a way of scrolling through the file until you get to the data you actually need. (Not the most compact way to code this, by the way. Whoever wrote this FORTRAN code may have b... | 16,728 |
23,566,970 | I have been using argparse in a program I am writing however it doesnt seem to create the stated output file.
My code is:
```
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
output_file.write("... | 2014/05/09 | [
"https://Stackoverflow.com/questions/23566970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3616869/"
] | You are missing the bit where the arguments are actually parsed:
```
parser.add_argument("-o", "--output", help="Directs the output to a name of your choice")
args = parser.parse_args()
with open(args.output, 'w') as output_file:
output_file.write("%s\n" % item)
```
parser.parse\_args() will give you an object f... | When I run your script I get:
```
Traceback (most recent call last):
File "stack23566970.py", line 31, in <module>
with open(output, 'w') as output_file:
NameError: name 'output' is not defined
```
There's no place in your script that does `output = ...`.
We can correct that with:
```
with open(args.output,... | 16,729 |
50,447,751 | I'm trying to retrieve last month's media posts from an Instagram Business profile I manage, by using `'since'` and `'until'`, but it doesn't seem to work properly as the API returns posts which are out of the time range I selected.
I'm using the following string to call the API:
```
business_profile_id/media?fields... | 2018/05/21 | [
"https://Stackoverflow.com/questions/50447751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8542692/"
] | Unfortunately the `since` and `until` parameters are not supported on this endpoint and this endpoint has only support cursor based pagination. The only way to do what I wish to do is to load each page of results individually using the `before` and `after` cursors provided in the API response. | For your task, I would recommend you to not use InstagramAPI library. I will show you a simple solution for this using [instabot](https://github.com/instagrambot/instabot) library. For pip installation of this library, use this command:
`pip install instabot`
Use the following python code to get the media within the ... | 16,732 |
72,470,453 | ```
import os
import sys, getopt
import signal
import time
from edge_impulse_linux.audio import AudioImpulseRunner
DEFAULT_THRESHOLD = 0.60
my_threshold = DEFAULT_THRESHOLD
runner = None
def signal_handler(sig, frame):
print('Interrupted')
if (runner):
runner.stop()
sys.exit(0)
signal.signal(signal.SIGINT, sign... | 2022/06/02 | [
"https://Stackoverflow.com/questions/72470453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19253158/"
] | [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) short-circuits after finding the first match so it doesn't necessarily have to iterate over the whole array of objects. And it also returns a boolean which satisfies your use-case.
```js
const query1 = ['empid','Name'... | Use `_.isEqual(object, other);`
It may help you. | 16,733 |
37,277,206 | Currently while using `babel-plugin-react-intl`, separate json for every component is created with 'id', 'description' and 'defaultMessage'. What I need is that only a single json to be created which contains a single object with all the 'id' as the 'key' and 'defaultMessage' as the 'value'
Present situation:
`Compon... | 2016/05/17 | [
"https://Stackoverflow.com/questions/37277206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380918/"
] | There is a [translations manager](https://github.com/GertjanReynaert/react-intl-translations-manager) that will do this.
Or for a custom option see below
---
The script below which is based on this [script](https://github.com/emmenko/redux-react-router-async-example/blob/master/scripts/i18nToXliff.js) goes through... | You can use [babel-plugin-react-intl-extractor](https://github.com/Bolid1/babel-plugin-react-intl-extractor) for aggregate your translations in single file. Also it provides autorecompile translation files on each change of your messages. | 16,734 |
33,111,338 | I am trying to find out the sum of multiples of two numbers using python.I have done it already. I just want to solve it using lambda functions.
Without lambda code
```
def sumMultiples(num, limit):
sum = 0
for i in xrange(num, limit, num):
sum += i
return sum
def sum(limit):
return (sumMu... | 2015/10/13 | [
"https://Stackoverflow.com/questions/33111338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5442186/"
] | Try this code:
```
a = input("enter first number\n")
b= input("enter second number\n")
limit=[]
limit.append(a)
limit.append(b)
natNo=range(1,1000)
xyz = []
for i in limit:
xyz +=filter(lambda x: x == i or x % i==0, natNo)
set = {}
map(set.__setitem__, xyz, [])
nums=set.keys()
print "the multiples of the given ... | ```
limit = 1000
a=lambda num, limit: sum([i for i in xrange(num, limit, num)])
print a(3,limit)+a(5,limit)-a(15,limit)
``` | 16,735 |
42,562,876 | I'm trying to read the frames of an .mov file using OpenCV 3.2 (from the [menpo conda channel](https://anaconda.org/menpo/opencv3)). I'm using Python 3.5.3 through Anaconda on an Ubuntu 16.04 64-bit setup.
Problem is, I get the following error message from OpenCV when it hits the `cap.read()` call, and the loop immedi... | 2017/03/02 | [
"https://Stackoverflow.com/questions/42562876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13604/"
] | Solved the problem by getting around it entirely.
Used the [opencv-feedstock](https://github.com/conda-forge/opencv-feedstock) recipe of OpenCV for conda-forge. In the `recipe` folder is the build information for conda. I modified the `build.sh` file, changing the following options:
```
-DBUILD_PNG=1
-DBUILD_JPEG=1
-... | I faced the same problem with Anaconda private env & Python 3.5 on Ubuntu 16.04 .
Initially installed Opencv3 using
```
conda install -c menpo opencv3
```
Solution:
1. Remove Opencv3 `conda remove opencv3`
2. Install Opencv3 using `pip install opencv-contrib-python`
If the problem still persists:
1. Uninstall Op... | 16,736 |
19,609,456 | Is there any way of creating a simple java(or c,c ++, python) program that prints 3 (outputs the 3) when given input=6 and it gives output=6 when given input=3 without using "if conditions" ? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19609456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2829141/"
] | Assuming you're happy for it to produce other outputs on inputs that aren't 6 or 3, then you can just compute 9-x. | You can always just use a switch-case statement. Also, if you only want those two answers, you could also take the input as an int and do 9-[your int] and print that answer. | 16,737 |
63,067,003 | I'm a beginner in python but I need to fix this small mistake. I tried different ways to fix it by changing the indentation. Maybe I'm overlooking something? The error is attached. Any help is much appreciated! Thank you
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using... | 2020/07/24 | [
"https://Stackoverflow.com/questions/63067003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13986513/"
] | Here you go.
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
``` | My solution:
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
``` | 16,742 |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0... | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | Somehow, my computer was one year behind the actual time.
I adjusted to the correct time and the time zone.
I closed and open Google Chrome. Problem was fixed. | The problem is basically on older version of OS e.g. Windows-XP with SP-II. SHA-2 algorithm has been used to generate SSL certificates which is not in range of older version of OS.
There are two solutions for the problem as:
1. Upgrade the OS. Use another OS or upgrade existing one (with SP-III). or
2. Generate new S... | 16,744 |
71,875,058 | I have a sample spark df as below:
```
df = ([[1, 'a', 'b' , 'c'],
[1, 'b', 'c' , 'b'],
[1, 'b', 'a' , 'b'],
[2, 'c', 'a' , 'a'],
[3, 'b', 'b' , 'a']]).toDF(['id', 'field1', 'field2', 'field3'])
```
What I need next is to provide a multiple aggregations to show summary of the a, b, c values f... | 2022/04/14 | [
"https://Stackoverflow.com/questions/71875058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16762881/"
] | Let me answer your question in two steps. First, you are wondering if it is possible to avoid hard coding all your aggregations in your attempt to compute all your aggregations. It is. I would do it like this:
```py
from pyspark.sql import functions as f
# let's assume that this is known, but we could compute it as w... | ### update
based on discussion in the comments, I think this question is a case of an [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The task at hand is something that is seen very frequently in the world of Data Engineering and ETL development: how to partition and then quantify... | 16,754 |
49,007,215 | I want get the occurrence of characters in a string, I got this code:
```
string = "Foo Fighters"
def conteo(string):
copia = ''
for i in string:
if i not in copia:
copia = copia + i
conteo = [0]*len(copia)
for i in string:
if i in copia:
conteo[copia.index(i)] =... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49007215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7590594/"
] | Depending on why you want this information, one method could be to use a `Counter`:
```
from collections import Counter
print(Counter("Foo Fighters"))
```
Of course, to create exactly the same output as requested, use itertools as well:
```
from collections import Counter
from itertools import chain
c = Counter("F... | It's not clear whether you want a critique of your current attempt or a pythonic solution. Below is one way where output is a dictionary.
```
from collections import Counter
mystr = "Foo Fighters"
c = Counter(mystr)
```
**Result**
```
Counter({' ': 1,
'F': 2,
'e': 1,
'g': 1,
'h... | 16,755 |
35,782,575 | I am using a python package called kRPC that requires a basic boilerplate of setup code to use in any given instance, so here's my question:
Once I create a generic *'kRPCboilerplate.py'*, where can I place it inside my Python27 directory so that I can simply type,
```
import kRPCboilerplate
```
at the beginning of... | 2016/03/03 | [
"https://Stackoverflow.com/questions/35782575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5910286/"
] | Your module root directory is 'Python27\Lib' where Python27 is your main python folder which includes the python executable file. You can drag and drop the .py files into there and import it without any complications! | Bit late to reply, but the safest is to set a special environmental variable called PYTHONPATH which will add search location for Python to search for libraries:
eg in Linux terminal:
`export PYTHONPATH=$PYTHONPATH:/path/to/file`
note it is only the path to the file, not the filename.
If you want a more permanent so... | 16,757 |
50,070,398 | I am new to tensorflow. When I am using `import tensorflow.contrib.learn.python.learn` for using the DNNClassifier it is giving me an error: `module object has no attribute python`
Python version 3.4
Tensorflow 1.7.0 | 2018/04/27 | [
"https://Stackoverflow.com/questions/50070398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5878765/"
] | You can use `transition-delay` combined with sass loops and completely avoid javascript:
```
@for $i from 0 through 3
.mobile-container.active li:nth-child(#{$i})
transition-delay: 330ms + (100ms * $i) !important
```
Check this [fork](https://codepen.io/anon/pen/aGBPXL) of your codepen. | You can use jquery plugin <https://github.com/morr/jquery.appear/> to track elements when they appear and provide data animations based on it.
E.g. You can give your element and attribute data-animated="fadeIn" and the plugin will do the rest. | 16,758 |
17,903,144 | I am new in python and I am supposed to create a game where the input can only be in range of 1 and 3. (player 1, 2 , 3) and the output should be error if user input more than 3 or error if it is in string.
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if ChoosePlayer... | 2013/07/27 | [
"https://Stackoverflow.com/questions/17903144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626540/"
] | `raw_input` returns a string. Thus, you're trying to do `"1" > 4`. You need to convert it to an integer by using [`int`](http://docs.python.org/2/library/functions.html#int)
If you want to catch whether the input is a number, do:
```
while True:
try:
ChoosePlayer = int(raw_input(...))
break
ex... | You have to cast your value to int using method [`int()`](http://docs.python.org/2/library/functions.html#int):
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if int(ChoosePlayer) not in [1,2,3]:
print "Sorry! Error! Please Try Again!"
ChoosePlayer= (r... | 16,760 |
54,530,138 | I am stuck on why my code doesn't count the number of vowels, including case-insensitive, and print a sentence reporting the number of vowels found in the word 'and'.
```
import sys
vowels = sys.argv[1]
count = 0
for vowel in vowels:
if(vowel =='a' or vowel == 'e' or vowel =='i' or vowel =='o' or vowel =='u' or... | 2019/02/05 | [
"https://Stackoverflow.com/questions/54530138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | sys.argv is a list of the running arguments, where the first element is always your running file. therefore, you do not iterate over the text but rather over the arguments ['vowel\_counter.py', 'and'].
You should do something like this:
```
vowels=sys.argv[1]
``` | The following will take care of single or multiple arguments passed in the command line. Like `python vowel_count.py foo` and `python vowel_count.py foo bar`
```
$ cat vowel_count.py
import sys
args = sys.argv[1:]
print(args)
count = 0
for arg in args: # handling multiple commandline args
for char in arg:
... | 16,763 |
59,134,194 | This is a part of HTML code from following page [following page](https://orange.e-sim.org/battle.html?id=5377):
```
<div>
<div class="sidebar-labeled-information">
<span>
Economic skill:
</span>
<span>
10.646
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Strength:
</span>
<s... | 2019/12/02 | [
"https://Stackoverflow.com/questions/59134194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12460618/"
] | You need to change the format string a little and pass `width` as a keyword argument to the `format()` method:
```
width = 6
with open(out_file, 'a') as file:
file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))
```
Contents of file afterwards:
```none
a b
``` | It's a bit ugly but you can do this. Using `{{}}` you can type a literal curly brace, and by that, you can format your format string with a variable width.
```
width = 6
format_str = "{{:{}}}{{:{}}}\n".format(width, width) #This makes the string "{:width}{:width}" with a variable width.
with open(out_file, a) as fil... | 16,766 |
54,722,251 | I am trying to connect to a mysql database (hosted on media temple) with my python script (ran locally) but I am receiving an error when I run it.
The error is:
```
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cex... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54722251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320977/"
] | make sure you've installed mysql-connector and not mysql-connector-python, to make this sure just run the following commands: `pip3 uninstall mysql-connector-python pip3 install mysql-connector` | Make sure you have given correct port number | 16,769 |
15,912,804 | Standard python [distutils provides a '--user' option](http://docs.python.org/2/install/index.html#alternate-installation-the-user-scheme) which lets me install a package as a limited user, like this:
```
python setup.py install --user
```
Is there an equivalent for **easy\_install** and **pip**? | 2013/04/09 | [
"https://Stackoverflow.com/questions/15912804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376587/"
] | For `pip`, see [User Installs](http://www.pip-installer.org/en/latest/cookbook.html#user-installs) for details, but basically, it's just what you'd expect:
```
pip install --user Foo
```
It's a bit trickier for `easy_install`. As Ned Deily points out, if you can rely on `distribute` rather than `setuptools`, and 0.6... | From the easy\_install docs
<http://peak.telecommunity.com/DevCenter/EasyInstall#downloading-and-installing-a-package>
>
> --install-dir=DIR, -d DIR Set the installation directory. It is up to you to ensure that this directory is on sys.path at runtime, and to
> use pkg\_resources.require() to enable the installed... | 16,770 |
48,791,900 | I'm using the python api to upload apks, mapping files and release note texts.
See <https://developers.google.com/resources/api-libraries/documentation/androidpublisher/v2/python/latest/androidpublisher_v2.edits.html>
I'm using the `apks().upload()`, `deobfuscationfiles().upload()` and `apklistings().update()` APIs t... | 2018/02/14 | [
"https://Stackoverflow.com/questions/48791900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261009/"
] | You need to use the new version of Google Play Developer API v3, where you can now set "status" (completed, draft, stopped, inProgress) for Edits.tracks.
<https://developers.google.com/resources/api-libraries/documentation/androidpublisher/v3/python/latest/androidpublisher_v3.edits.tracks.html> | It isn't possible to have a manual review step at the moment. | 16,772 |
23,768,865 | I am trying to list some of software installed on a PC by using:
```
Get-WmiObject -Class Win32_Product |
Select-Object -Property name,version |
Where-Object {$_.name -like '*Java*'}
```
It works, but when I added more names in `Where-Object` it gave me no results neither an error.
```
Get-WmiObject -Class Win32_Pr... | 2014/05/20 | [
"https://Stackoverflow.com/questions/23768865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3303155/"
] | I don't think `-like` will take an array on the right hand side. Try a regex instead:
```
Where-Object {$_.name -match 'Java|python|adobe|access'}
``` | The -Like operator takes a string argument (not a string array), so whatever you give it will get cast as [string]. If you cast the arguments you've give it to string:
```
[string]('*Java*','*python*','*adobe*','*access*')
```
you get:
```
*Java* *python* *adobe* *access*
```
and that's what you're trying to mat... | 16,773 |
60,250,462 | I have a large list that contains usernames (about 60,000 strings). Each username represents a submission. Some users have made only one submission i.e. they are **"one-time users"**, so their username appears only once in this list. Others have made multiple submission (**returning users**) so their username can appea... | 2020/02/16 | [
"https://Stackoverflow.com/questions/60250462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900486/"
] | You can improve by using a [Counter](https://docs.python.org/2/library/collections.html#collections.Counter), in `2.` for each element you are iterating the whole list, and you are doing this multiple times for the same user if an user occurs more than once.
Note that when you use `users.count(user)` you iterate all... | As mentioned in your own comment, Counter is significantly faster here. You can see from your own timing that creating a set of the results takes around 10ms to complete (#8->#9), which is roughly the time Counter will take as well.
With counter you look at at each of the N elements once, and then at each unique eleme... | 16,774 |
56,206,422 | Try to pass the dictionary into the function to print them out, but it throws error: most\_courses() takes 0 positional arguments but 1 was given
```
def most_courses(**diction):
for key, value in diction.items():
print("{} {}".format(key,value))
most_courses({'Andrew Chalkley': ['jQuery Basics', 'Node.js... | 2019/05/19 | [
"https://Stackoverflow.com/questions/56206422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11523169/"
] | When you pass your dict as a param, you can either do it as you wrote:
```
most_courses({'Andrew Chalkley': ...
```
in this case `most_cources` should accept a "positional" param. That's why it raises: `most_courses() takes 0 positional arguments but 1 was given`.
You gave it 1 positional param, while `most_cour... | There is no reason to use `**` here. You want to pass a dict and have it processed as a dict. Just use a standard argument.
```
def most_courses(diction):
``` | 16,775 |
61,853,196 | I have a python file that contains these elements:
```
startaddress = 768
length = 64
subChId = 6
protection = 1
bitrate = 64
```
and I want to convert them to a single dictionary string like this:
```
{"startaddress":"768","length":"64","subChId":"6","protection":"1","bitrate":"64"}
```
so I can... | 2020/05/17 | [
"https://Stackoverflow.com/questions/61853196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150586/"
] | Let a package manager like [brew](https://brew.sh/) do the work for you:
```sh
brew install deno
```
Easy to install, easy to upgrade.
Check the [official repo](https://github.com/denoland/deno_install) for all the installation options. | To find the instillation options use official documentation <https://deno.land/#installation>.
For MacOS following installation options are available.
**01.Using Shell**
```
curl -fsSL https://deno.land/x/install/install.sh | sh
```
**02.Using [Homebrew](https://brew.sh/)**
```
brew install deno
```
**03.Using ... | 16,777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.