Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
1,800 | 43,433,075 | Create list of tuples from 2d array | <p>I'm looking to create a list of tuples from a 2xn array where the first row is an ID and the second row is that IDs group assignment. I'd like to create a list of the IDs organized to their group assignments. </p>
<p>For example:</p>
<pre><code>array([[ 0., 1., 2., 3., 4., 5., 6.],
[ 1., 2., 1., 2.... | <p>The standard (sorry, not creative -- but reasonably quick) numpy way would be an indirect sort:</p>
<pre><code>import numpy as np
data = np.array([[ 0., 1., 2., 3., 4., 5., 6.],
[ 1., 2., 1., 2., 2., 1., 1.]])
index = np.argsort(data[1], kind='mergesort') # mergesort is a bit
... | python|arrays|numpy | 1 |
1,801 | 48,783,917 | How can we get response of next loading web page | <p>I am writing a scraper to get all the movie list available on hungama.com</p>
<p>I am requesting "<a href="http://www.hungama.com/all/hungama-picks-54/4470/" rel="nofollow noreferrer">http://www.hungama.com/all/hungama-picks-54/4470/</a>" url to get the response.</p>
<p>When you go to this url, this will show 12 m... | <p>There seems to be an <code>ajax</code> request as a lazy load feature with url <a href="http://www.hungama.com/all/hungama-picks-54/4470/2/?ajax_call=1&_country=IN" rel="nofollow noreferrer">http://www.hungama.com/all/hungama-picks-54/4470/2/?ajax_call=1&_country=IN</a> which fetches movies .<br>
In the abov... | python|css|python-2.7|xpath|web-scraping | 0 |
1,802 | 51,392,297 | How to compare time stamps in log lines that also has version numbers? | <p>I am trying to find the version number log line with the most recent time stamp, and I am currently trying to do it by using parse_version. </p>
<p>log line examples: </p>
<pre><code>2018-05-08T15:25:02.053Z 00000000-0000-0000-0000-000000000000 > LVL:2 RC: version: 2.11.0.10451
2018-05-08T21:27:14.2049217Z>... | <p>Since you're looking to store and display the second-latest version number, you can simply use another variable to retain the current latest version number before it gets replaced by the new latest version number.</p>
<p>Change:</p>
<pre><code> if parse_version(line) > parse_version(latest_versio... | python-3.x|timestamp|comparison | 0 |
1,803 | 44,606,051 | Manually compute the length of a string | <p>I have a homework assignment asking for string length calculation without using built-in functions.</p>
<p>What I had in mind is to use a counter:</p>
<pre><code>s = 0
while name[s] != "":
s += 1
</code></pre>
<p>but I'm stuck with how to solve the <code>string index out of range</code> error...or is there ac... | <p>you have two simple options :</p>
<p>Either add a <code>try/except</code> clause:</p>
<pre><code>s = 0
try:
while(name[s]):
s += 1
except IndexError:
pass
print(s)
</code></pre>
<p>Or use an iterator:</p>
<pre><code>s = 0
for _ in name:
s += 1
print(s)
</code></pre> | python|string | 3 |
1,804 | 44,760,064 | Machine learning multi-classification: Why use 'one-hot' encoding instead of a number | <p>I'm currently working on a classification problem with tensorflow, and i'm new to the world of machine learning, but I don't get something.</p>
<p>I have successfully tried to train models that output the <code>y</code> tensor like this:</p>
<pre><code>y = [0,0,1,0]
</code></pre>
<p>But I can't understand the pri... | <p>Ideally, you could train you model to classify input instances and producing a single output. Something like</p>
<p><code>y=1</code> means <code>input=dog</code>, <code>y=2</code> means <code>input=airplane</code>. An approach like that, however, brings a lot of problems:</p>
<ol>
<li>How do I interpret the output... | machine-learning|tensorflow|classification|multiclass-classification | 2 |
1,805 | 23,848,801 | List comprehension to create list of strings from two lists | <p>I have two lists of strings and I want to use them to create a list of strings.</p>
<pre><code>m1 = ["Ag", "Pt"]
m2 = ["Ir", "Mn"]
codes = []
for i in range (len (m1) ):
codes.append('6%s@32%s' %(m1[i], m2[i] ) )
print codes
</code></pre>
<p>For example codes could have the elements ["6Ag@32Ir", "6Pt@32Mn"]</p... | <p>Non-zip method:</p>
<pre><code>>>> m1 = ["Ag", "Pt"]
>>> m2 = ["Ir", "Mn"]
>>> ['6%s@32%s' %(m1[i], m2[i]) for i in range(min(len(m1), len(m2)))]
['6Ag@32Ir', '6Pt@32Mn']
</code></pre>
<p>Turn that into a generator:</p>
<pre><code>>>> ('6%s@32%s' %(m1[i], m2[i]) for i in xrange... | python|list|functional-programming | 4 |
1,806 | 23,515,779 | python sort dictionary by value array | <p>I have a dictionary with an array as elements.
Say:</p>
<pre><code>masterListShort = {'a': [5, 2, 1, 2], 'b': [7, 2, 4, 1], 'c': [2, 0, 1, 1]}
</code></pre>
<p>I would like to reverse sort this dictionary by the first element of the values.
I would then like to write my output to a tab delimited file like this:</p... | <p>You'll need to sort the <em>values</em> then, on the <em>first</em> index (so <code>0</code> for zero-based indexing), and tell <code>sorted()</code> to reverse the order:</p>
<pre><code>import operator
sorted(myDict.values(), key=operator.itemgetter(0), reverse=True)
</code></pre>
<p>Without the <code>dict.value... | python|list|sorting|python-2.7|dictionary | 8 |
1,807 | 20,509,570 | Merge dictionaries without overwriting previous value where value is a list | <p>I am aware of <a href="https://stackoverflow.com/questions/12121417/merge-dictionaries-without-overwriting-values">Merge dictionaries without overwriting values</a>, <a href="https://stackoverflow.com/questions/9415785/merging-several-python-dictionaries">merging "several" python dictionaries</a>, <a href=... | <p>I'm pretty sure that <code>.extend</code> works here ...</p>
<pre><code>>>> dict_a = {'a': [3.212], 'b': [0.0]}
>>> dict_b = {'a': [923.22, 3.212], 'c': [123.32]}
>>> dict_c = {'b': [0.0]}
>>> result_dict = {}
>>> dicts = [dict_a, dict_b, dict_c]
>>>
>>&g... | python|dictionary|merge | 4 |
1,808 | 71,843,852 | Passing nested list as an argument to a method | <p>Below code is working fine</p>
<pre><code>class p:
def __init__(self):
self.log={
'name':'',
'id':'',
'age':'',
'grade':''
}
def parse(self,line):
self.log['id']=line[0]
self.log['name']=line[1]
self.log['age'... | <p>I dont get why you are trying to avoid an explicit loop. I mean, even if you don't see it in your code, if there is something being iterated, there will be a loop somewhere, and if so, <a href="https://peps.python.org/pep-0020/#the-zen-of-python" rel="nofollow noreferrer">"explicit is better than implicit"... | python|list|nested | 0 |
1,809 | 36,198,264 | convert numpy matrix into pyspark rdd | <p>I have a 2d numpy array. How do I create a pyspark rdd from that where each row in the matrix is an entry in the rdd?</p>
<p>Such that:</p>
<pre><code>rddData.take(1)[0] == list(aaData[0])
</code></pre>
<p>where <code>aaData</code> is the numpy 2d array (matrix) and <code>rddData</code> is the rdd created from <... | <p>Just <code>parallelize</code> it:</p>
<pre><code>mat = np.arange(100).reshape(10, -1)
rdd = sc.parallelize(mat)
np.all(rdd.first() == mat[0])
## True
</code></pre> | python|pyspark | 5 |
1,810 | 29,418,338 | Python file-IO and zipfile. Trying to loop through all the files in a folder and then loop through the texts in respective file using Python | <p>Trying to extract all the zip files and giving the same name to the folder where all the files are gonna be.
Looping through all the files in the folder and then looping through the lines within those files to write on a different text file.<br>
This is my code so far:</p>
<pre><code>#!usr/bin/env python3
import gl... | <p>You need to open the file and also join the path to the file, also using splitlines and then adding a newline to each line is a bit redundant:</p>
<pre><code>path = dir_name
with open("Output.txt", "w") as fOut:
for filename in os.listdir(path):
# join filename to path to avoid file not being found
... | python|python-3.x|file-io|nested-loops|python-zipfile | 2 |
1,811 | 29,709,359 | Multiprocesses python with shared memory | <p>I have an object that connects to a websocket remote server. I need to do a parallel process at the same time. However, I don't want to create a new connection to the server. Since threads are the easier way to do this, this is what I have been using so far. However, I have been getting a huge latency because of GIL... | <p>You sure can, use something along the lines of:</p>
<pre><code>from multiprocessing import Process
class WebSocketApp(object):
def on_open(self):
# Create another thread to make sure the commands are always been read
print "Creating thread..."
try:
p = Process(target = WebSocketApp.read_co... | python|multiprocessing | 1 |
1,812 | 46,466,171 | Can't embed graph into tkinter | <p>I am trying to embed a graph into a tkinter window. The import code looks like this:</p>
<pre><code>import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
# implement the default mpl key bindings
from matp... | <p>I did what the second answer by @Volodia to <a href="https://stackoverflow.com/questions/32767491/matplotlib-wont-install-properly-on-python-3-5">this</a> question said and worked fine. Problem solved.</p> | python|debugging|matplotlib|tkinter|module | 0 |
1,813 | 46,559,466 | Creating 2d histogram from 2d numpy array | <p>I have a numpy array like this:</p>
<pre><code>[[[0,0,0], [1,0,0], ..., [1919,0,0]],
[[0,1,0], [1,1,0], ..., [1919,1,0]],
...,
[[0,1019,0], [1,1019,0], ..., [1919,1019,0]]]
</code></pre>
<p>To create I use function (thanks to @Divakar and @unutbu for helping in other question):</p>
<pre><code>def indices_zero_gri... | <p>If I understand correctly, you want an image of size 1920x1080 which colors the pixel at coordinate <code>(x, y)</code> according to the value of <code>out[x, y]</code>.</p>
<p>In that case, you could use</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def indices_zero_grid(m,n):
I,J = np.o... | python|numpy|matplotlib | 1 |
1,814 | 49,515,048 | Loop over multiple files to merge according their names | <p>I'm a new python. I have for loop function gives me a folder contains 100 files "the data inside is numbers and the nuber of raws are the same" like the follow:</p>
<pre><code>A_0.20_1_.txt for example A_0.20_1_ B_0.20_1_
B_0.20_1_.txt 1 4
A_0.20_2_.txt ... | <p>Your code is actually working the problem is you don't pass a full path to <code>os.path.isfile()</code> so it does not return <code>True</code> and your list of files is empty</p>
<pre><code>import numpy as np
import os
file_path = r"C:\Users\output"
filename_list = []
for file in os.listdir(file_path):
file =... | python|python-3.x|for-loop|file-handling | 0 |
1,815 | 20,891,445 | Safely viewing lists in ipython | <p>When I ask an ipython notebook to display (via evaluate) a large np.array ipython uses ellipses to summarize the data. However if I ask ipython to display a large list, no such safe guard is in place and my poor ipython notebook struggles. Are there any magics or other tools I can use? I run an ipython notebook in e... | <p>could you not just test the length of the list yourself? Or wrap the lists as generators?</p>
<pre><code>>>> def guard(XS,N):
... if len(XS) > N:
... return "list too long" # or whatever you want
... else:
... return XS
...
>>> guard([1,2,3,4],2)
'list too long'
>>... | list|ipython-notebook | 0 |
1,816 | 21,284,912 | installing matplotlib, error: Setup script exited with error: command 'gcc' failed with exit status 1 | <p>I'm on cygwin and using easy_install to install matplotlib. and i get the above error. I have attached the installation process so far. what is going wrong?</p>
<pre><code> $ easy_install matplotlib
Searching for matplotlib
Reading http://pypi.python.org/simple/matplotlib/
Reading http://matplotlib.org
Reading http... | <p>I recommend you to install <a href="http://code.google.com/p/pythonxy/" rel="nofollow">PythonXY</a>, you will have almost ALL you need, or at least very good and well known libs (including matplotlib, numpy, scipy, and many others). And it works <em>out of the box</em>, no need to find dependencies.</p> | python|matplotlib|cygwin | 1 |
1,817 | 21,079,881 | Is it possible to check for correct python syntax of a given file/string from Java | <p>I am writing a piece of code in java, part of this code deals with handling python code. I was just interested if anyone has come across a way of checking if the python code is syntactically correct during runtime. I don't actually need to run the python code, as i'm writing a program that generates small snippets o... | <p>For Python 2, this can be done with <a href="http://www.jython.org/" rel="nofollow noreferrer">Jython</a>:</p>
<pre><code>new org.python.util.PythonInterpreter().compile("python code here")
</code></pre>
<p>and an exception will be thrown if it finds a problem (likely <code>org.python.core.PySyntaxError</code>)</p... | java|python | 2 |
1,818 | 70,142,081 | Given array size of four, minus from element 0 and plus to element 1, 2 and 3 | <p>I am just looking for ideas that I can carry out such action or a name to "Google" or to learn such ideas.</p>
<p>Given a set of array</p>
<pre><code>a = [10,5,3,6]
</code></pre>
<p>My target is to minus 3 from a, and add back to a[1],a[2] and a[3] respectively.</p>
<p>Example</p>
<pre><code>a = [10,5,3,6]... | <pre><code>import itertools
def my_combinations(my_list, k):
for item in itertools.product(range(k+1), repeat=len(my_list) - 1):
if sum(item) == k:
yield item, [my_list[0] - k] + [n + i for n, i in zip(my_list[1:], item)]
spam = [10, 5, 3, 6]
for item, lst in my_combinations(spam, 3):
prin... | python | 1 |
1,819 | 54,935,465 | How to organize images in directory into classes dependent on dataframe column values? | <p>I have a directory of images from <a href="https://www.kaggle.com/c/petfinder-adoption-prediction/data" rel="nofollow noreferrer">this kaggle comp</a>. Images with the same animal in them have the same prefix in their name, and then followed by <code>-{num}</code> where num is the number image of that specific anima... | <h3>Basic Command</h3>
<p>This answer uses the same approach as <a href="https://stackoverflow.com/a/54935687/6770384">Inder's answer</a> but inside a single <code>awk</code> command which <em>could</em> be faster. Not that it would matter in this case... Here we assume a file as given in your example as input, see ne... | python|bash|dataframe | 2 |
1,820 | 33,427,374 | How to use subprocess to write to file | <p>I am trying to get adb logcat and save to a file. I tried POPEN and call as below</p>
<pre><code> f = open("/Users/log.txt")
subprocess.call(["adb logcat"], stdout=f)
f_read = f.read()
print f_read
</code></pre>
<p>But I get error </p>
<pre><code> File "testPython.py", line 198, in getadbLogs
... | <p>Because you opened <code>f</code> in read mode(<code>r</code>). If you don't select the mode, the default mode is <code>r</code> mode.</p>
<p>To write to the file you should use <code>w</code> mode like this:</p>
<pre><code>f = open("/Users/log.txt", 'w')
subprocess.call(["adb logcat"], stdout=f)
f.close()
f = op... | android|python|python-2.7|subprocess|logcat | 1 |
1,821 | 33,081,957 | Swig: Pass a vector<float> from c++ to python | <p>I want to write some code in C++ which returns a vector to python. I tried the following example, but it returns the following object.</p>
<pre><code><Swig Object of type 'std::vector< float > *' at 0x100331f90>
</code></pre>
<p>How can I convert this to a list so that I can use it in python?</p>
<p>M... | <p>I found an answer to this problem. It was kind of hard to find the right keywords for this problems.</p>
<p>The solution is explained <a href="https://stackoverflow.com/a/16528607/2737994">here</a>.</p>
<pre><code>%include <std_vector.i> //Takes care of vector<type>
</code></pre>
<p>What's still missi... | python|swig | 0 |
1,822 | 21,437,511 | How to select only integers in a list of strings/integers? | <p>I have a list (actually an iterable) which was created using this function of python's itertools library:</p>
<pre><code>comb = [c for i in range(len(menu)+1) for c in combinations(menu, i)]
</code></pre>
<p>To give you an idea <code>menu</code> is a list in this format [ ["name of food", grams of sugar] ]:</p>
<... | <p>As you were alluding to, you can use a list comprehension to iterate through all menu combinations, and restrict to those <code>meals</code> with exactly the sugar amount you are looking for:</p>
<pre><code>>>> # input data
>>> menu = [ ["cheesecake", 13], ["pudding", 24], ["bread", 13] ]
>>... | python|list|iterator|list-comprehension | 1 |
1,823 | 24,478,859 | Sending email in python, message missing | <p>I am deleting several folders which are 30 days old and want to mail myself the list of all those deleted folders using gmail. </p>
<p>Currently it deletes the folder without any trouble but the message in the email is blank along with subject. What am I missing?</p>
<pre><code>import os
import time
import shutil... | <p>Try this:</p>
<pre><code>deleted_folders = []
for r,d,f in os.walk(directory):
for dir in d:
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
shutil.rmtree(os.path.join(r,dir))
deleted_folders.append("Delete... | python|email|smtp|mime|shutil | 1 |
1,824 | 38,211,408 | Speed up pandas dataframe iteration | <p>I have a dataframe with date and values, </p>
<pre><code> Date Price
Jun 30 95.60
Jun 29 94.40
Jun 28 93.59
Jun 27 92.04
Jun 24 93.40
Jun 23 96.10
Jun 22 95.55
Jun 21 95.91
Jun 20 95.10
Jun 17 95.33
Jun 16 97.55
Jun 15 97.14
Jun 14 97.46
Jun 13 97.34
Jun 10 98.83
Jun... | <p>Let's invite <code>Scipy</code> too!</p>
<p><strong>The Idea :</strong> Compare the current element with the previous <code>4</code> values by calculating the minimum in that interval and comparing with the current one. If it matches, we have basically failed all the comparisons and thus choose <code>False</code>. ... | python|numpy|pandas | 2 |
1,825 | 38,167,774 | How to retrieve the integer value of tkinter ttk Scale widget in Python? | <p>Could anyone advise how to retrieve and update a <code>Label</code> widget with the value from a <code>Scale</code> widget in Python? Currently it shows a very large real number. I have tried to type cast the value but this only works when I print to idle. I tried <code>slider.get()</code> but the label is blank. Al... | <p>I don't see a way to control the resolution of the Scale widget, but it's fairly easy to modify the string it produces. According to <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Scale.html" rel="nofollow noreferrer">these ttk docs</a> the Scale widget returns a float, but in my experiments it retur... | python|tkinter|ttk|tkinter-scale | 4 |
1,826 | 40,205,394 | Pandas means in column for subset in another column | <p>I have a dataframe called houses: </p>
<pre><code> transaction_id house_id date_sale sale_price boolean_2015 \
0 1 1 31 Mar 2016 £880,000 True
3 4 2 31 Mar 2016 £450,000 True
4 5 ... | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>replace</code></a> <code>£,</code> to empty string and then convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric<... | python|database|pandas | 0 |
1,827 | 39,981,766 | What does "TypeError: [foo] object is not callable" mean? | <p>I am trying to iterate through a list of Facebook postIDs, and I am getting the following error:</p>
<p>TypeError: 'list' object is not callable</p>
<p>Here is my code:</p>
<pre><code>MCTOT_postIDs = [["126693553344_10155053097028345"],
["126693553344_10155050947628345"],
["126693553344_10155048566893345"],
["126... | <p>EDIT:
For the other error, the function g.get_object(...) requires one more argument, that you are not passing.
You're passing the fields, but you're must pass an ID as an argument too, you must pass the x of your loop, that contains the id.</p>
<p>Probably should go like:</p>
<pre><code>g.get_object('fields="mes... | python | 4 |
1,828 | 29,313,021 | AttributeError: 'module' object has no attribute 'DatePickerCtrl' | <p>In trying to learn, I am running code developed by others who indicate is it working. It does not work for me. I am attempting for the 1st time to use <code>wx.DatePickerCtrl</code>. After running my code, I get the following error:</p>
<p><code>test8000.py", line 12, in __init__
self.datepick = wx.DatePicke... | <p>I know this is old, but in case anyone else comes across it.</p>
<p>On wxPython Phoenix (what you're using), the DatePickerCtrl is part of the wx.adv module.
On wxPython Classic, the DatePickerCtrl is part of the wx module. Your code was most likely written for WxPython Classic.</p>
<p>You can find a link to old i... | wxpython | 1 |
1,829 | 29,291,270 | Threading in python - processing multiple large files concurrently | <p>I'm new to python and I'm having trouble understanding how threading works. By skimming through the documentation, my understanding is that calling <code>join()</code> on a thread is the recommended way of blocking until it completes. </p>
<p>To give a bit of background, I have 48 large csv files (multiple GB) whic... | <p>I can't understand where mistake in your code. But I can recommend you to refactor it a little bit.
First at all, threading in python is not concurrent at all. It's just illusion, because there is a <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">Global Interpreter Lock</a>, so only one t... | python|multithreading|concurrency | 4 |
1,830 | 8,541,110 | Check for a stale element using selenium 2? | <p>Using selenium 2, is there a way to test if an element is stale?</p>
<p>Suppose I initiate a transition from one page to another (A -> B). I then select element X and test it. Suppose element X exists on both A and B.</p>
<p>Intermittently, X is selected from A before the page transition happens and not tested u... | <p>I don't know what language you are using there but the basic idea you need in order to solve this is:</p>
<pre><code>boolean found = false
set implicit wait to 5 seconds
loop while not found
try
element.click()
found = true
catch StaleElementReferenceException
print message
found = false
wait a few secon... | python|selenium-webdriver | 1 |
1,831 | 52,378,074 | How can I connect to MySQL on Heroku? | <p>I have a Django project that uses MySQL as its database. On my development machine the MySQL database runs on my local machine as shown here:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xxx',
'USER': 'root',
'PASSWORD': 'xxxx',
... | <p><a href="https://stackoverflow.com/a/52378789/354577">juanmhidalgo's answer</a> is a good start, and can be generalized for arbitrary environment variables. But if you only care about the database variable there's another solution.</p>
<p>By default, Heroku provides a PostgreSQL database and sets your application's... | python|mysql|django|heroku | 2 |
1,832 | 51,702,538 | pyramid-arima auto_arima order selection | <p>I am working on Time Series Forecasting(Daily entry) using <code>pyramid-arima</code> <code>auto_arima</code> in python where y is my target and x_features are all exogenous variables. I want best order model based on lowest aic, But <code>auto_arima</code> returns only few order combinations. </p>
<p><img src="htt... | <p>You say error_action='ignore', so probably (0,1,2) and (0,1,3) (and other orders) gave errors, so they didn't appear in the results.
(I don't have enough reputation to write a comment, sorry).</p> | python-3.x|time-series|forecasting|pyramid-arima | 1 |
1,833 | 51,730,061 | how to get soup.find_all to work in BeautifulSoup? | <p>I'm trying to scrape information a page consisting names of attorneys using BeaurifulSoup</p>
<pre><code>#importing libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
</code></pre>
<p>Following is an example of each attorney's names that are nested in HTML tags</p>
<pre><c... | <p>You need to change your soup.find_all to <code>div</code> since the class goes with <code>div</code> and not <code>a</code></p>
<pre><code>page=requests.get("https://www.foxrothschild.com/people/search%5Bname%5D=&search%5Bkeywod%5D=&search%5Boffice%5D=&search%5Bpeople-position%5D=&search%5Bpeople-ba... | python-3.x|web-scraping|beautifulsoup | 1 |
1,834 | 51,674,486 | Python click module is_flag not working as expected | <p>According to click <a href="http://click.pocoo.org/6/options/#boolean-flags" rel="nofollow noreferrer">documentation</a> there are two ways to specific a boolean flag. The "on/off" method:</p>
<pre><code>@click.option('--shout/--no-shout', default=False)
</code></pre>
<p>and the "is_flag" method:</p>
<pre><code>@... | <p>You have specified <code>is_flag=False</code> which means it is not a flag. Change the click option for two to:</p>
<pre><code>@click.option('--two', is_flag=True, help='is_flag')
</code></pre> | python | 3 |
1,835 | 51,921,470 | Error Installing PyInstaller for Python 3.7 on Windows 10 | <p>I used the command <code>pip install pyinstaller</code> to installer PyInstaller for Python 3.7 on Windows 10, but the Command Prompt gave me the following errors:</p>
<pre><code>ModuleNotFoundError: No module named 'pywintypes'
...
ModuleNotFoundError: No module named 'cffi'
...
During handling of the above except... | <p>I got that problem.
The solution was</p>
<pre><code>python -m pip install pip==18.1
</code></pre>
<p>then just</p>
<pre><code>python -m pip install -U pyinstaller
</code></pre> | python|windows-10|pyinstaller | 11 |
1,836 | 19,004,118 | Faster way to split a numpy array according to a threshold | <p>Suppose I have a random numpy array:</p>
<pre><code>X = np.arange(1000)
</code></pre>
<p>and a threshold:</p>
<pre><code>thresh = 50
</code></pre>
<p>I want to split <code>X</code> in two partitions <code>X_l</code> and <code>X_r</code> in such a way that every element in <code>X_l</code> is less or equal to <co... | <p><code>X[~Z]</code> is faster than <code>X[Z==0]</code>:</p>
<pre><code>In [13]: import numpy as np
In [14]: X = np.random.random_integers(0, 1000, size=1000)
In [15]: thresh = 50
In [18]: Z = X <= thresh
In [19]: %timeit X_l, X_r = X[Z == 0], X[Z == 1]
10000 loops, best of 3: 23.9 us per loop
In [20]: %time... | python|arrays|numpy | 7 |
1,837 | 36,498,478 | Why is \d+ only matching one digit in this python regexp? | <p>Regexp: <code>editClassification/(?P<pk>[\d+])</code></p>
<p>String to match: <code>foo/editClassification/10</code></p>
<p><a href="http://pythex.org/?regex=editClassification%2F(%3FP%3Cpk%3E%5B%5Cd%2B%5D)&test_string=foo%2FeditClassification%2F9%0Afoo%2FeditClassification%2F10&ignorecase=0&mult... | <p>Because <code>\d+</code> is within a character class (<code>[...]</code>); <code>[\d+]</code> matches exactly one character that is either a digit or <code>+</code>. </p>
<p>You were supposed to write <code>(?P<pk>\d+)</code> instead.</p> | python|regex | 2 |
1,838 | 19,528,503 | Django views: Object value not recognized | <p>I am trying to learn django from official tutorial.</p>
<p>I am stuck with a strange issue, it may be trivial but I am not able to figure it out -</p>
<p>I am following this tutorial :</p>
<p><a href="https://docs.djangoproject.com/en/dev/intro/tutorial03/" rel="nofollow noreferrer">Tutorial 3</a></p>
<p>My prob... | <p>You've forgotten one of the curly braces in /srv/www/hello/poll/templates/poll/index.html.</p> | python|django|django-models|django-templates|django-views | 2 |
1,839 | 13,650,618 | monospaced font for coding with splitted underlines | <p>Are there any monospaced fonts with separate underlines, like this: </p>
<p><img src="https://i.stack.imgur.com/aA4y2.png" alt="enter image description here"></p>
<p>with support of Cyrillic script? Consolas' underlines are not separate and Adobe Source Code Pro doesn't support Cyrillic script right now.
Or maybe... | <p>Try <a href="http://www.dafont.com/monofur.font" rel="nofollow">Monofur</a>. It has the separate underscores, and has Cyrillic glyphs.</p> | python|fonts|sublimetext2 | 2 |
1,840 | 13,685,201 | How to add hours to current time in python | <p>I am able to get the current time as below:</p>
<pre><code>from datetime import datetime
str(datetime.now())[11:19]
</code></pre>
<p><em><strong>Result</strong></em></p>
<pre><code>'19:43:20'
</code></pre>
<p>Now, I am trying to add <code>9 hours</code> to the above time, how can I add hours to current time in Pytho... | <pre><code>from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
</code></pre>
<p>And then use string formatting to get the relevant pieces:</p>
<pre><code>>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31... | python|time|add|timedelta | 481 |
1,841 | 43,721,531 | How can I execute simple interactive program in spyder? | <p>I wrote typical guess-number game:</p>
<pre><code>import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print("Hey you on board! I am the dreadfull pirat Robert, and I have a
secret!")
print("that is a magic number from 1 to 99. I give you 6 tries.")
while guess != secret & tries < 6:
guess ... | <p>Couple of issues with your code, in the <code>tires=tries+1</code> you've probably made a code typo. </p>
<p>Second, guess reads in a string so you will need to convert guess into an int to do integer comparisons, use something like <code>guess=int(guess)</code>.</p>
<p>The reason you aren't seeing this is because... | python-3.x|ide|spyder|interactive | 1 |
1,842 | 54,259,717 | Comparing each element of two arrays | <p>So I have two arrays and i want the amount of elements smaller than the individual elements of the other arrays. So i have two arrays like this:</p>
<pre><code>array1 = np.array([4.20, 3.52, 9.44, 12.00, 10.50, 7.30, 9.44])
array2 = np.array([3.8600000000000003, 5.75, 8.37, 9.969999999999999, 11.25]
</code></pre>
... | <p>You can iterate over each element in the second array, and use that element to create a mask, then sum up all of the <code>True</code> values:</p>
<pre><code>output = []
for el in array2:
output.append(np.sum(array1 < el))
</code></pre>
<p>Output:</p>
<pre><code>[1, 2, 3, 5, 6]
</code></pre>
<p>Your appro... | python|arrays | 0 |
1,843 | 54,471,731 | Total number of unique values for each person in a large file | <p>I have this unique list:</p>
<pre><code>unique_list = {'apple', 'banana', 'coconut'}
</code></pre>
<p>I want to find how many of the elements occur exactly in my large text file. I just need the number, not the names. For example, if only 'apple' and 'banana' are found for a particular person, then it should retur... | <p>you can leverage python's basic library - <code>collections</code></p>
<pre><code>from collections import Counter
dict(Counter(pd.Series(['cody', 'cody ', 'cody ', 'melton', 'melton', 'harry'])))
</code></pre>
<p>Output</p>
<pre><code>{'cody ': 2, 'melton': 2, 'cody': 1, 'harry': 1}
</code></pre>
<p>In my examp... | python|python-3.x|python-3.7 | 0 |
1,844 | 54,675,965 | Saving the DateTime format applied in the .csv file in Pandas | <p>I have imported a csv file in pandas that contains fields that look like <code>'datetime'</code> but initially parsed as <code>'object'</code>. I make the required conversion from <code>'datetime'</code> to <code>'object'</code> using <code>'df.X = pd.to_datetime(df.X)'</code>. </p>
<p>Now, when I try to save these... | <p>Date parsing can be expensive, so pandas doesn't parse dates by default. You need to specify parse_dates argument when call read_csv</p>
<pre><code>df = pd.read_csv('my_file.csv', parse_dates=['date_column'])
</code></pre> | python|pandas|datetime|export-to-csv | 1 |
1,845 | 54,441,635 | Convert decimal numpy array in 8 numpy arrays after binary transformation | <p>I'm reading an image with OpenCV in gray scale, so i have a numpy array with values from 0 to 255.</p>
<p>I have to convert it to binary first.</p>
<p>From: <code>[dec, dec, dec, dec, dec, dec]</code> </p>
<p>To: <code>[bin, bin, bin, bin, bin, bin]</code>.</p>
<p>After that i have to build 8 numpy arrays with t... | <p>I think you need:</p>
<pre><code>x = [10,2,4,5,7,8]
# convert decimal to binary
b = [bin(i)[2:] for i in x]
arr1 = []
for i in b:
arr1.append([i]*6)
print(arr1)
</code></pre>
<p><strong>output</strong></p>
<pre><code>[['1010', '1010', '1010', '1010', '1010', '1010'],
['10', '10', '10', '10', '10', '10'],... | python | 0 |
1,846 | 71,269,937 | Why am I getting infinite loop for the this code for any input value of range 1 to 10**9? | <p>Can somebody point out why am I getting infinite loop in this? I mean it shows error for maximum recursion depth reached?
For value of '1' it shows correct output.</p>
<pre><code>def beautiful(n):
new=str(n+1)
new.rstrip('0')
return int(new)
def check(n):
if n==1:
temp.extend(list(range(1,10))... | <p>Unless I've completely misunderstood this, it has been over-complicated in the extreme. It's as simple as this:</p>
<p>Note: no recursion, no string manipulation</p>
<pre><code>def check(n):
result = []
while n > 1:
if (n := n + 1) % 10 == 0:
n //= 10
result.append(n)
retur... | python|recursion | 1 |
1,847 | 9,029,718 | writing scraped data to csv file | <p>I am scraping out the 'h2' and 'h3' tags from some html pages and want to write them to a csv file under particular columns. How to create columns and then insert rows under them using python scrapy.</p>
<p>My code is:</p>
<pre><code>def parse(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.... | <p>why don't you use custom Csv item exporter ? <a href="http://doc.scrapy.org/en/latest/topics/exporters.html" rel="nofollow">suggested reading</a></p>
<p>or </p>
<p>write your own code <a href="http://docs.python.org/library/csv.html" rel="nofollow">suggested reading</a></p> | python|scrapy | 0 |
1,848 | 39,021,754 | Can't split django views into subfolders | <p>I'm following the directions from the first answer here:</p>
<p><a href="https://stackoverflow.com/questions/1921771/django-split-views-py-in-several-files">Django: split views.py in several files</a></p>
<p>I created a 'views' folder in my app and moved my views.py file inside and renamed it to viewsa.py. I also ... | <p>Use relative import, in your <code>__init__.py</code>:</p>
<pre><code>from .viewsa import *
</code></pre>
<p>(notice the dot in <code>.viewsa</code>)</p> | python|django | 1 |
1,849 | 52,733,516 | Python 3.7.0: How do I format datetime to mm-dd-yy hh:mm:ss? | <p>How do I format datetime to mm-dd-yy hh:mm:ss? I did it using the following code:</p>
<pre><code>import datetime
t = datetime.datetime.now()
s = str(format(t.second, '02d'))
m = str(format(t.minute, '02d'))
h = str(format(t.hour, '02d'))
d = str(format(t.day, '02d'))
mon = str(format(t.month, '02d'))
y = str(t.ye... | <p>Like this:</p>
<pre><code>import datetime
now = datetime.datetime.now()
now.strftime('%m-%d-%y %H:%M:%S')
</code></pre>
<p>Also see docs - <a href="https://docs.python.org/3/library/datetime.html" rel="noreferrer">https://docs.python.org/3/library/datetime.html</a></p> | python-3.x|date|datetime|datetime-format|python-datetime | 10 |
1,850 | 52,890,944 | How to use properly Tensorflow Dataset with batch? | <p>I am new to Tensorflow and deep learning, and I am struggling with the Dataset class. I tried a lot of things and I can’t find a good solution.</p>
<h2>What I am trying</h2>
<p>I have a large amount of images (500k+) to train my DNN with. This is a denoising autoencoder so I have a pair of each image. I am using the... | <p>As far as I know, <a href="https://www.tensorflow.org/performance/datasets_performance" rel="nofollow noreferrer">Official Performance Guideline</a> is the best teaching material to make input pipelines.</p>
<blockquote>
<p>I want to shuffle the dataset in a different way for each epoch.</p>
</blockquote>
<p>Usi... | python|tensorflow|tensorflow-datasets | 4 |
1,851 | 52,593,745 | How to make my multiplication table more neat? | <p>My multiplication that I created is not formatted/organized neatly - I want it to have lines that separate the numbers.</p>
<p>My code:</p>
<pre><code>n = int(input("Enter a positive interger between 1 and 9: "))
for row in range(1, n+1):
print(*(f"{row*col:5}" for col in range(1, n+1)))
</code></pre>
<p>It w... | <p>Use <a href="https://pypi.org/project/tabulate/" rel="nofollow noreferrer">tabulate</a>:</p>
<pre><code>import pandas as pd
from tabulate import tabulate
n = int(input("Enter a positive interger between 1 and 9: "))
data = []
for row in range(1, n+1):
tmp = [row*col for col in range(1, n+1)]
data.append(t... | python | 1 |
1,852 | 47,826,744 | Read multiple web sockets at the same time and plot data in Python | <p>I'm fairly new to scripting in general and I'm pretty sure this is trivial but i can't seem to find a solution. I want to use the python websockets library to listen to multiple websockets in order to get ticker information about crypto prices. </p>
<p><a href="https://stackoverflow.com/questions/45543334/how-to-ge... | <p>The GDAX websocket allows you to subscribe to multiple pairs.
As seen below I subscribe to both the <code>BTC-USD</code> and <code>ETH-USD</code> pairs. I assume you can subscribe to unlimited pairs.</p>
<pre><code>import websocket
from json import dumps, loads
try:
import thread
except ImportError:
import ... | python|websocket | 3 |
1,853 | 37,366,120 | Spark python most repeated value for each key | <p>I have an RDD with format: (date, city). And the data inside is something like this:</p>
<pre><code>day1, city1
day1, city2
day1, city2
day2, city1
[...]
</code></pre>
<p>I need to obtain the most "repeated" city by each day, ie I need the following result:</p>
<pre><code>day1, city2
day2, city1
day3, ...
</code>... | <p>It is just a modified wordcount:</p>
<pre><code>rdd.map(lambda x: (x, 1)) \
.reduceByKey(lambda x, y: x + y) \
.map(lambda ((day, city), count): (day, (city, count))) \
.reduceByKey(lambda x, y: max(x, y, key=lambda x: x[1]))
</code></pre> | python|apache-spark|rdd | 0 |
1,854 | 37,283,584 | Extracting html-as-text between break tags using regex | <p>Have a series of elements in a list which are extracted from html -- each with break tags (<code><br>...</br></code>). I used this code below with one element, and will apply to a loop, but it throws an an error <code>SyntaxError: unexpected EOF while parsing</code> on the single element. </p>
<pre><co... | <p>It's because of your HTML:</p>
<pre><code>firstElementText = '<td align="center" bgcolor="#e0e0e0" nowrap="" valign="middle"><b>Season</b></td>'
</code></pre>
<p>Has no <code><br></code>. Change it to</p>
<pre><code> firstElementText = '<td align="center" bgcolor="#e0e0e0" nowr... | regex|python-3.x | 1 |
1,855 | 34,031,194 | equation Solution Set in python | <p>i have a problem that i should make a programme to solve this equation </p>
<blockquote>
<p>a2 + b2 + c2 = d</p>
</blockquote>
<p>and sort the solution in <code>Lexicographical order</code> the order comes without make it and if there is no solution print -1 so i write my Code and i use three nested loop... | <p>notice that your break statement breaks only out of the most inner for loop.
you may want to use p for that and make checks at the end of each for loop, i.e (it wasn't checked...):</p>
<pre><code>d=int(raw_input())
p=0
for a in range(d+1):
a
for b in range(d+1):
b
for c in range(d+1):
... | python|python-2.7|loops|math|mathematical-optimization | 0 |
1,856 | 34,046,377 | python regular expression "12x4x67" match only the second group of numbers | <p>all i am a little stuck on this regular expression (Python beginner) I have a string here "12x4x67" and I need to split the numbers up into variables, for example: length, width and height. I have successfully gotten the first group. Now I need to match the second group. Here's a link to the regex tester I am using ... | <p>No regular expression needed:</p>
<pre><code>length, width, height = "12x4x67".split('x')
</code></pre>
<p>Or if you prefer dealing with integers:</p>
<pre><code>length, width, height = [int(s) for s in "12x4x67".split('x')]
</code></pre> | python|regex | 4 |
1,857 | 39,419,343 | shortest distance from plane to origin using a plane equation | <p>suppose i have a plane equation ax+by+cz=d, how can I go about finding the shortest distance from the plane to the origin?</p>
<p>I am going in reverse of this post. In this post, they start out with a point P0 and the normal. In my case, I only have the plane equation
<a href="https://stackoverflow.com/questions/8... | <p>The normal of your plane is <code>[a,b,c]</code>. Multiply it by <code>d</code> and get the length of the result. This should give you what you need.</p> | python|3d|plane | 1 |
1,858 | 39,664,509 | How can I add to the initial definition of a python class inheriting from another class? | <p>I'm trying to define <code>self.data</code> inside a class inheriting from a class</p>
<pre><code>class Object():
def __init__(self):
self.data="1234"
class New_Object(Object):
# Code changing self.data here
</code></pre>
<p>But I ran into an issue.</p>
<pre><code>class Object():
def __init__... | <p>You use <code>super</code> to call the original implementation.</p>
<pre><code>class New_Object(Object):
def __init__(self):
super(NewObject, self).__init__()
self.info = 'whatever'
</code></pre> | python|class|inheritance|instance | 3 |
1,859 | 16,502,105 | How do I select an ndb property with a string? | <p>With a data model like this</p>
<pre><code>class M(ndb.Model):
p1 = ndb.StringProperty()
p2 = ndb.StringProperty()
p3 = ndb.StringProperty()
</code></pre>
<p>I'm trying to set the property values with a loop something like this</p>
<pre><code>list = ["a","b","c", "d"]
newM = M( id = "1234" )
for p in... | <p>python has <a href="http://docs.python.org/2/library/functions.html#setattr" rel="nofollow">setattr</a> which will do what you want. Inside your loop:</p>
<pre><code>setattr(newM, p, choice(list)
</code></pre> | python|google-app-engine|app-engine-ndb | 3 |
1,860 | 31,708,816 | python performance tips for looping calculation | <p>Python 2.7, Windows 7.</p>
<p>I'm looking for tips on how to make a calculation heavy script run faster. First an idea of what I'm doing:</p>
<p>Starting with a given color, I want to generate a list of 30 more colors (rgb values) that are maximally distinctive to the human eye from one another, and with the front... | <p>I'm sure a color that is R:100 G:100 B:101 would not be a "maximally distinctive" solution if color R:100 G:100 B:100 is chosen already. </p>
<p>One quick improvement you could make is to omit checking colors which are similar (ie. R and G values which are the same that have a B value within a given range).</p> | python|python-2.7 | 1 |
1,861 | 32,066,051 | Python + WSGI - Can't import my own modules from a directory? | <p>I'm new to Python and i have looked around on how to import my custom modules from a directory/ sub directories. Such as <a href="https://stackoverflow.com/questions/4142151/python-how-to-import-the-class-within-the-same-directory-or-sub-directory">this</a> and <a href="https://en.wikibooks.org/wiki/A_Beginner%27s_P... | <p>You should have an <code>__init__.py</code> file in the <code>modules/</code> directory to tell Python that <code>modules</code> is a <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="noreferrer">package</a>. It can be an empty file.</p>
<p>If you like, you can put this into that <code>__init_... | python|python-2.7|mod-wsgi|wsgi | 7 |
1,862 | 40,720,651 | How to create colour map from 3 arrays in python | <p>I'm trying to create a colour plot in python of two arrays t1 and t2 with the colours being set by a third one v, but I can't get the colour bar to be in terms of the v array, it is instead in terms of t1. This is my code:</p>
<pre><code> import matplotlib.pyplot as plt
import numpy as np
t1 = [75, 76, 7... | <p>You cannot use <code>imshow</code> to set x and y coordinates, and color as 3rd.
It is to show a matrix image, where there are X*Y values, and all these values represent color.
Perhaps you want to use <code>scatter</code>.
E.g. you can try:</p>
<pre><code>import matplotlib.pyplot as plt
t1 = [0,1,2,3]
t2 = [0, 10, ... | python|arrays|numpy|matplotlib|colormap | 0 |
1,863 | 40,719,358 | Generate all possible 2 and 3 string combinations from a list in python | <p>I have a following list:</p>
<pre><code>mylist = ['car', 'truck', 'ship']
</code></pre>
<p>Currently I am able to only get all the possible combinations of 2 strings using this:</p>
<pre><code>from itertools import combinations
print(list(combinations(mylist,2)))
</code></pre>
<p>which gives me:</p>
<pre><code>... | <p>This is an adjusted case of the powerset. Typically the code for the powerset in Python looks like this:</p>
<pre><code>from itertools import chain, combinations
def powerset(it):
yield from chain.from_iterable(combinations(it, r) for r in range(len(it)+1))
</code></pre>
<p>You can change it, though, to only ... | python|list|combinations | 5 |
1,864 | 9,711,357 | Pointing of variables in Python | <p>Suppose I create a function <code>A</code> that is used as an argument in another function, so <code>B(A)</code>. Function <code>A</code> points to an entry in a (SciPy) array <code>C</code>. If I change the array <code>C</code> from within <code>B</code>, then the value in the array will be changed globally, so tha... | <p>The most straightforward way is to write A so that B passes it the array to work on (hence: the locally modified one). Is there any reason you don't want to do that?</p>
<pre><code>def func(arr):
return arr[0]
</code></pre>
<p>(Incidentally your <code>func</code> ignores its argument).</p> | python | 0 |
1,865 | 68,145,805 | Looping Two Values from a JSON Dictionary in Python3 | <p>I know this should be simple, but in the dozens of questions I've read, there is no answer for this. I'm did a lot of reading about comprehensions <a href="https://docs.python.org/3.3/tutorial/datastructures.html#nested-list-comprehensions" rel="nofollow noreferrer">here</a>, but it's going a bit over my head on thi... | <p>Accessing a list with <code>[0]</code> just gives you the first element. You want to iterate over the list:</p>
<pre><code>twitterlists = twitter.show_owned_lists()['lists']
for i in twitterlists:
print(f"List name: {i['name']}. List ID: {i['id']}.")
</code></pre> | python|json|api|loops | 2 |
1,866 | 1,376,438 | How to make a repeating generator in Python | <p>How do you make a repeating generator, like xrange, in Python? For instance, if I do:</p>
<pre><code>>>> m = xrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>I get the same result both times — the numbers 0..4. However, if I try the same with yield:</p>
<pre><code>>>... | <p>Not directly. Part of the flexibility that allows generators to be used for implementing co-routines, resource management, etc, is that they are always one-shot. Once run, a generator cannot be re-run. You would have to create a new generator object.</p>
<p>However, you can create your own class which overrides <co... | python | 21 |
1,867 | 63,124,611 | I am facing an error while i try to load a file in python 3 | <pre><code>f = open(path,'r',encoding='utf8')
</code></pre>
<p>This is the code I'm trying to run but it outputs <code>'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte</code> as the error. What might be the reason for this?</p> | <p>Try changing your encoding to utf-8, and see if that fixes it. Otherwise, the file might not be encoded in utf-8.</p> | python|python-3.x | 1 |
1,868 | 32,344,291 | Python Image using Numpy | <p>I am trying to show 2 images using PYQT Numpy format. But the 2nd image comes after 1 image closes. I want to show both the image simultaneously. </p>
<pre><code>ImageAddress = 'D:\\Boot.PNG'
ImageItself = Image.open(ImageAddress)
ImageNumpyFormat = np.asarray(ImageItself)
plt.imshow(ImageNumpyFormat)
plt.title('De... | <p>I assume <code>plt</code> comes from <a href="http://matplotlib.org/matplotlib" rel="nofollow">matplotlib</a>. Instead of your first <code>plt.close()</code>, use <code>plt.figure(2)</code> to open a second figure. Also, you probably don't need <code>plt.draw()</code> at all, instead, end the program with <code>plt.... | python|numpy|pyqt | 1 |
1,869 | 32,153,663 | Better code prediction in PyCharm | <p>I'm trying various IDE for development on Python. Basic requirement better code-prediction and git association. I really liked PyCharm, but code-prediction is somewhat better in PyDev. </p>
<p>Here is a comparison of code prediction side-by-side (Left - PyDev, Right - PyCharm)</p>
<p><a href="https://i.stack.imgur... | <p>You will be surprised but if you are using windows try VS community edition with Python plugin. intellisense just works. </p> | python|pycharm|pydev|code-completion | 1 |
1,870 | 32,456,167 | parsing the Json for the Optional fields | <p>I have the JSON in the below format:</p>
<pre><code>{
"type":"MetaModel",
"attributes":[
{
"name":"Code",
"regexp":"^[A-Z]{3}$"
},
{
"name":"DefaultDescription",
},
]
}
</code></pre>
<p>The <code>attributes["regexp"]</code> is opt... | <p>Use <code>get</code>, a method of dictionaries that will return <code>None</code> if a key doesn't exist:</p>
<pre><code>foo = json.loads(the_json_string)
value = foo.get('regexp')
if value:
# do something with the regular expression
</code></pre>
<p>You can also just catch the exception:</p>
<pre><code>value ... | python|json|regex | 15 |
1,871 | 28,092,982 | looping throught the folder | <p>I need to solve trivial task running in loop sequence of the commands:</p>
<p>1) to take input .dcd file from the folder
2) to make some operations with the file
3) to save results in list</p>
<p>My code (which is not working !) looks like</p>
<pre><code># make LIST OF THE input DCD FILES
path="./inputs/"
dirs=o... | <p><code>os.listdir()</code> gives you only the base filenames <em>relative to the directory</em>. No path is included.</p>
<p>Prefix your filenames with the path:</p>
<pre><code>for traj in dirs:
trajectory = command(os.path.join(path, traj))
</code></pre> | python|loops|for-loop | 1 |
1,872 | 28,222,769 | Google Drive Resumable Upload Failing | <p>I am trying to upload a file using the Google Drive resumable upload api[<a href="https://developers.google.com/drive/web/manage-uploads#resumable]" rel="nofollow">https://developers.google.com/drive/web/manage-uploads#resumable]</a> and i'm always getting a 400 status code with Invalid Upload request in the step 3 ... | <p>I finally nailed it myself. It was a bug in the code where the content-range for the last chunk was off by 1 byte.</p> | python|google-drive-api|python-requests | 2 |
1,873 | 27,973,544 | Python - Prime finder/calculator error | <p>Okay, I know my code is extremely inefficient and longer than it be, but I am very new to python and only know a few basic functions. </p>
<pre><code>restart = True
numtocheck = 2 #number to be tested for being a prime
while 0==0: #forever loop
if restart == True:
testnum = 2 #used to test the 'numtoch... | <p>What you want to do is probably the following:</p>
<pre><code>restart = True
numtocheck = 2 #number to be tested for being a prime
while 0==0: #forever loop
if restart == True:
testnum = 2 #used to test the 'numtocheck' varible
calculated = numtocheck % testnum #modulo computation
if (calcul... | python | 0 |
1,874 | 43,959,653 | XSLT matching with namespaces | <p>I am trying to build bottle.py templates from RelaxNG definitions using Python 3.6 and lxml (which means XSLT 1.0 and XPath 1.0). I cannot find the trick to getting the name of the starting template, which in this example is 'AddressBook'. I need this from <em>rng:grammar/rng:start/rng:start/rng:ref/@name</em> inste... | <p>Your problem is not with namespaces, but with paths. Your instruction:</p>
<pre><code><xsl:apply-templates select="rng:start"/>
</code></pre>
<p>does not do anything because <code>start</code> is not a child of the current node (which is the <code>/</code> root node matched by <code><xsl:template match="/... | python|xml|xslt|xpath|lxml | 0 |
1,875 | 34,729,532 | What does struct.calcsize (python) actually calculate? | <p>Following <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">the manual about struct.calcsize</a></p>
<pre><code>truct.calcsize(fmt)¶
Return the size of the struct (and hence of the string) corresponding to the given format
</code></pre>
<p>But I do not get why struct.calcsize('hll') is no... | <p>I would assume this is due to padding elements shorter than a machine word, for efficiency purposes.</p>
<p>Accesses to memory addresses that are multiples of the machine word length (e.g. 8 bytes for 64-bit machines) tend to be faster. For this reason, C compilers will pad their structs, unless told otherwise. The... | python | 1 |
1,876 | 23,193,275 | How to find out size of crawled webpage in Scrapy? | <p>I am learning <a href="http://scrapy.org/" rel="nofollow">Scrapy</a>.<br>
I want to find out size of crawled webpage or size of response in KB or MB etc using Scrapy.<br>
I can find out length of content of crawled webpage using<code>response.body</code><br>
what is the simplest way to findout how much data is getti... | <p>You can get size by using information provided by reading content-length from headers property of <a href="http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Response" rel="nofollow">Response Object</a>. </p>
<pre><code>parse(self, response):
url=response.url
content=response.body
... | python|web-crawler|scrapy | 1 |
1,877 | 982,260 | Obfuscate strings in Python | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the passw... | <p>If you just want to prevent casually glancing at a password, you may want to consider encoding/decoding the password to/from <a href="http://docs.python.org/library/base64.html" rel="nofollow noreferrer">base64</a>. It's not secure in the least, but the password won't be casually human/robot readable.</p>
<pre><cod... | python|linux|encryption|passwords|obfuscation | 26 |
1,878 | 41,925,548 | BeautifulSoup HTTPResponse has no attribute encode | <p>I'm trying to get beautifulsoup working with a URL, like the following:</p>
<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://proxies.org")
soup = BeautifulSoup(html.encode("utf-8"), "html.parser")
print(soup.find_all('a'))
</code></pre>
<p>However, I am getting a e... | <p>Check this one.</p>
<pre><code>soup = BeautifulSoup(html.read().encode('utf-8'),"html.parser")
</code></pre> | python|python-3.x|beautifulsoup|urlopen | 0 |
1,879 | 57,367,582 | constructing Page URL that i can reach after inserting an item number into search box | <p>I'm writing a python script to <strong>scrape</strong> an online shopping website
every item on this website has an item number and after inserting an item number into search box I'm redirected to item page
when I looked to the URL of this page there was no clue about the item number in this URL _ so I can replace i... | <p>If I understand your question correctly, you want to go straight to the search result pages using a series of search strings. If so, then - at least in the case of ebay (if will likely be different for each site) - you can use f-strings together with a base url to achieve that:</p>
<pre><code>base_url = 'https://ww... | python|url|web-scraping | 0 |
1,880 | 70,895,101 | How to create multiprocess with regression function? | <p>I'm trying to build a regression function that call itself in a new process. The new process should not stop the parent process nor wait for it to finish, that is why I don't use join(). Do you have another way to create regression function with multi-process.
I use the following code:</p>
<pre><code>import multipro... | <p>Here's a simplified example of what I think you're trying to do (side note: launching processes recursively is a great way to accidentally create a <a href="https://en.wikipedia.org/wiki/Fork_bomb" rel="nofollow noreferrer">"fork bomb"</a>. It is extremely more common to create multiple processes in some s... | multiprocessing|regression|python-3.8|attributeerror | 0 |
1,881 | 70,863,314 | matplotlib.cpp, Python 3.10 from C++ | <p>I'm learning how to use Matplotlib from within C++ according to the <a href="https://matplotlib-cpp.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">readthedocs</a>. I have installed Python 3.10 from scratch and copied matplotlibcpp.h from <a href="https://github.com/Cryoris/matplotlib-cpp/blob/master/... | <p>I understand, correct me if I'm wrong, matplotlibcpp.h contains a couple constructors, each of which falls through to the first one, that is the one finally calling plot_base. Now, the compiler cannot decide between this "fall-through to" constructor and another one further below.</p>
<pre><code>// @brief ... | python|c++|matplotlib|visual-c++ | 0 |
1,882 | 30,243,522 | Django admin.py readonly_fields not working | <p>I need to show on Django administration the date the object was created, but date field should be disabled of modification.</p>
<p>here is my model on Models.py</p>
<pre><code>from django.db import models
from django.utils import timezone
class MyModel(models.Model):
name = models.CharField(max_length=200)
... | <p>You need to register the admin class as well as the model. </p>
<pre><code>admin.site.register(MyModel, MyModelAdmin)
</code></pre> | python|django|django-admin | 2 |
1,883 | 43,421,333 | Why do pygame and pyglet show different results on the screen with the SAME matrices? | <p>Why do I see different results when I run this code with <code>use_pyglet</code> being <code>True</code> vs. <code>False</code>?</p>
<p>The matrices and viewport are the same in both cases, so I'm really confused.</p>
<pre><code>import ctypes
import numpy
use_pyglet = False # change this to True to see the diff... | <blockquote>
<p>The matrices and viewport are the same in both cases, so I'm really confused.</p>
</blockquote>
<p>They actually aren't. The thing is that at the point where you check it they haven't been changed yet. If you instead move the check into <code>on_draw</code>. Then you'll notice that <code>GL_PROJECTIO... | python|windows|opengl|pygame|pyglet | 1 |
1,884 | 43,226,977 | Django User password not getting hashed for custom users | <p>I am currently implementing the authentication for a Django application, I am writing. Following code of the Thinkster Django course, I implemented the whole registration process, but I cannot login, because the password is not getting hashed, when registering a user. </p>
<p>Here is my custom User model and the <c... | <p>You need to use set_password method like this in serializer:</p>
<pre><code>def create(self, validated_data):
user = User(email=validated_data['email'], username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
</code></pre> | python|django|django-rest-framework | 3 |
1,885 | 19,984,843 | (x,y) pair for max z value in list | <p>I have a list of lists such as:</p>
<pre><code>nodes =[[nodeID,x,y,z],....]
</code></pre>
<p>I want to find:</p>
<pre><code>xi,yi for zi=zmax given zmax= max z for same x,y
</code></pre>
<p>and store the <code>(xi,yi,zi)</code> in another list.</p>
<p>I can do this using:</p>
<pre><code>nodes=[[literal_eval(x)... | <del>
You could use the <code>max</code> function with a key:<br>
<code>maxz = max(list_, key=lambda x: x[3])</code><br>
This will assign <code>maxz</code> to the item of the list <code>list_</code> with the maximum value with index 3 (z value). You can then extract the `xi` and `yi` values:<br>
<code>xi, yi = (... | python|list|max | 1 |
1,886 | 4,692,726 | Threads, wxpython and statusbar | <p>I'm doing a program in which I'm using a wxStatusBar, when a download starts I start a child thread like this:</p>
<pre><code>def OnDownload(self, event):
child = threading.Thread(target=self.Download)
child.setDaemon(True)
child.start()
</code></pre>
<p>Download is another function without parameters ... | <p>Most people get directed to the wxPython wiki:</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks" rel="nofollow">http://wiki.wxpython.org/LongRunningTasks</a></p>
<p>I also wrote up a little piece on the subject here:</p>
<p><a href="http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/" rel=... | python|multithreading|wxpython|statusbar | 1 |
1,887 | 48,065,361 | Scrapy: downloader/response_count vs response_received_count | <p>I am using <code>scrapy</code> to crawl multiple websites, and I want to analyze the crawling rate.
The stats dumped at the end contain a <code>downloader/response_count</code> value and a <code>response_received_count</code> value. The former is systematically greater than the latter.</p>
<p>Why is there a differe... | <ul>
<li><code>CoreStats</code> is the <a href="https://doc.scrapy.org/en/latest/topics/extensions.html" rel="noreferrer"><code>Extension</code></a> responsible for <code>response_received_count</code></li>
<li><code>DownloaderStats</code> is the <a href="https://doc.scrapy.org/en/latest/topics/downloader-middleware.ht... | python|web-scraping|scrapy|web-crawler | 8 |
1,888 | 48,160,554 | Using Python Requests to simulate clicking a 'show more' button | <p>I am not sure what code to use for clicking the show more button. I want to get a list of university who are doing certain topic. below is one of the websites </p>
<p><a href="http://www.sciencedirect.com/science/article/" rel="nofollow noreferrer">http://www.sciencedirect.com/science/article/</a></p>
<p>your h... | <p>You shouldn't have to simulate, in Python, an actual "click" of the "show more" button to accomplish web-scraping.</p>
<p>"Show more" buttons in websites are usually tied to some JavaScript that either reveals a hidden element already in the HTML (see <a href="https://getbootstrap.com/docs/4.0/components/collapse/"... | python|web-scraping|python-requests | 5 |
1,889 | 51,298,034 | What does "-" (dash) after color do in matplotlib? | <p>I have this code that draws a graph.
<code>plt.plot([1,7], [1,1], 'k-', linewidth=2)</code>
In lines like this, there are <code>k-</code> which represents the color black.
However the code works without the dash, so <code>k</code> is just fine.</p>
<p>Why is that dash <code>-</code> there? What does it do?</p>
<p>... | <p>The dash is the symbol for a solid line. Since it is the default line type, omitting it does not alter the plot.</p>
<p>For more information, see the <a href="https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html" rel="nofollow noreferrer">line-style reference</a>:</p>
<p><a href="https:... | python|matplotlib | 4 |
1,890 | 51,372,240 | Group by with multiple conditions in pandas | <p>I want to aggregate rows, using different conditions for two columns.</p>
<p>When I do <code>df.groupby('[a]').agg('count')</code>, I get the <strong>output 1</strong></p>
<p>When I do <code>df.groupby('[a]').agg('mean')</code>, I get the <strong>output 2</strong></p>
<p>Is there a way to do an aggregation that s... | <p>Code below should work:</p>
<pre><code># Import libraries
import pandas as pd
import numpy as np
# Create sample dataframe
df = pd.DataFrame({'a': ['A1', 'A1', 'A2', 'A3', 'A4', 'A3'],
'value': [1,2,3,4,5,6]})
</code></pre>
<p><a href="https://i.stack.imgur.com/ueB6X.png" rel="nofollow noreferr... | python|pandas|group-by|aggregate | 1 |
1,891 | 64,486,115 | How do I search files in a folder to be moved to another folder in a certain condition in Python 3? | <p>I will try to explain a little more clearly: I am trying to figure out how to use shutil and os modules on Python 3.8.5 to be able to take a look at a folder, determine if its contents have been created and/or modified within the last 24 hours... and then if they have, move those files to another folder.</p>
<p>I am... | <p>I am not sure, what are you trying to achieve by using <code>shutil.copystat</code>. It only copies the stats and permissions onto the path. (If your <code>File B.txt</code> is read only, the <code>needToCopy</code> will be also read only)</p>
<p>In order to find out creation and modification times, consult <a href=... | python|operating-system|shutil | 0 |
1,892 | 64,342,913 | How to create a column based on the value of an element of an array indicated by the other column? | <p>I have one large data frame and I want to create a column based on the position of an array that is indicated by the other column. In the example below, I want to create a column that assigns the value based on the param array, where the position is indicated by the column "type".</p>
<pre><code>>>&g... | <pre><code>df['outcome'] = [param[i-1] for i in df.type.values]
</code></pre> | python|arrays|dataframe|slice | 0 |
1,893 | 55,849,575 | values_list() in query_set is showing only numbers but not the names of countries | <p>I selected my field with 'values_list' which contains name of countries. But what I get is country_id numbers. </p>
<p>I already used flat=True but it did not help any.</p>
<p>my models.py: </p>
<pre><code>class Report(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
church_name ... | <p>Use <code>Report.objects.values_list('country__name', flat=True)</code> (assuming that is the country name field on the country model). By default django will list the object id if no field is specified.</p>
<p>E.G if your country model was </p>
<pre><code>class Country(models.Model):
name = Charfield()
an... | python|django | 3 |
1,894 | 55,662,860 | How to convert Json array list with multiple possible values into columns in a dataframe using pyspark | <p>I am using the Google Admin Report API via the Python SDK in Databricks (Spark + Python 3.5).</p>
<p>It returns data in the following format (Databricks pyspark code): </p>
<pre><code>dbutils.fs.put("/tmp/test.json", '''{
"userEmail": "rod@test.com",
"parameters": [
{
"intValue": "0",
... | <p>The code below converts the example JSON provided to a dataframe(without using <code>PySpark</code>). </p>
<p><strong>Import Libraries</strong></p>
<pre><code>import numpy as np
import pandas as pd
</code></pre>
<p><strong>Assign variables</strong></p>
<pre><code>true = True
false = False
</code></pre>
<p><stro... | python|json|apache-spark|pyspark|azure-databricks | 1 |
1,895 | 64,705,298 | Members in A Guild | <p>I have this code that is supposed to send a list of members in a server that the bot is in, only with a guild id. Here is my code:</p>
<pre><code>@client.command(name='members')
async def _members(ctx, guild_id: int):
guild = client.get_guild(guild_id)
for m in guild.fetch_members(limit=None):
await ctx.send... | <p>According to the API References:</p>
<blockquote>
<p>Retrieves an AsyncIterator that enables receiving the guild’s members.</p>
</blockquote>
<p>Also it says:</p>
<blockquote>
<p><strong>Note:</strong> This method is an API call. For general usage, consider <code>members</code> instead.</p>
</blockquote>
<p>But if y... | python|discord|discord.py | 0 |
1,896 | 64,131,072 | Can one matplotlib style file inherit values from another? | <p>Suppose I have a matplotlib style file <code>base.mplstyle</code> with several specifications</p>
<pre><code>legend.fancybox: True
legend.numpoints: 1
legend.frameon: True
legend.framealpha: 0.8
legend.shadow: True
text.color: white
text.usetex: True
figure.figsize : 9, 9
</code></pre>
<p>Suppose I want to create an... | <p>Style sheets are designed to be combined, so you can set up the styles you want to combine in list form. Note, however, that they will be overridden by the values of the more right-handed styles.</p>
<pre><code>import matplotlib.pyplot as plt
plt.style.use(['base', 'small_figure'])
</code></pre> | python|matplotlib | 3 |
1,897 | 71,815,922 | How to Extract Numbers from String Column in Pandas with decimal? | <p>I need to extract Numbers from String Column.</p>
<p>df:</p>
<pre><code>Product
tld los 16OZ
HSJ14 OZ
hqk 28.3 OZ
rtk .7 OZ
ahdd .92OZ
aje 0.22 OZ
</code></pre>
<p>I need to Extract Numbers from column "Product" along with Decimal.</p>
<p>df_Output:</p>
<pre><code> Product Numbers
tld los 16... | <p>If as simplified as presented, replace every other string except digit and dot</p>
<pre><code>df['Numbers'] =df['Product'].str.replace('[^\d\.]','', regex=True).astype(float)
Product Numbers
0 tld los 16OZ 16.00
1 HSJ14 OZ 14.00
2 hqk 28.3 OZ 28.30
3 rtk .7 OZ 0.70
4 ahdd .92OZ... | python|regex|pandas | 2 |
1,898 | 71,578,599 | Inserting data into xlsx | <p>I'm running a python script and the result of it is a group of values. Let's say the result is a unique date and time.</p>
<pre><code>date = now.strftime("%d/%m/%Y")
time = now.strftime("%H:%M:%S")
</code></pre>
<p>I would like to write down the data into xlsx file, but the problem is that the da... | <p>You can open the excel in append mode and then keep inserting data. Refer below snippet:</p>
<pre><code>with pd.ExcelWriter("existing_file_name.xlsx", engine="openpyxl", mode="a") as writer:
df.to_excel(writer, sheet_name="name")
</code></pre> | python|xlsx|xlsxwriter | 0 |
1,899 | 60,365,118 | Python extracting only the First href link for every nth occurence in the for loop | <p>I am trying simple web scraping using python, but there is problem fetching link names as there are 2 to 3 <code>href</code> headers in the same class <code>btn</code> as mentioned below whereas i need only the first one to be printed for every new occurrence in the loop.</p>
<pre><code>#!/usr/bin/python3
from bs4 ... | <p>BeautifulSoup has excellent <a href="https://facelessuser.github.io/soupsieve/" rel="nofollow noreferrer">CSS support</a>, just use that to <a href="https://facelessuser.github.io/soupsieve/selectors/#:nth-of-type" rel="nofollow noreferrer">pick every odd item</a>:</p>
<pre><code>soup = BeautifulSoup(data, 'lxml')
... | html|python-3.x|web-scraping|beautifulsoup | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.