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
2,500
46,406,080
How to speed up append in Python?
<p>My code is something like this:</p> <pre><code>def fun -&gt; list: array = ... # creating of array return array def fun2: array2 = [] # some code for i in range(some_value): array2.append(fun) </code></pre> <p>Note that it isn't known how many values function <strong>fun</strong> retur...
<p>If you take a look at the <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow noreferrer">time complexity table</a> of different python operations on lists, you can see that that the speed of appending k elements to a list is always the same regardless to the number of elements to append.</p>
python|append
0
2,501
49,344,890
duplicate key value violates unique constraint .... Django error
<p>I am trying to make a 'get' query on a model. The parameters that i'm using to query the model are foreign keys(both of them). The models looks something like this...</p> <pre><code>class model_1(models.Model): field_1 = models.ForeignKey(model_2) field_2 = models.CharField(max_length = 512) field_3 = ...
<p>You are trying to create a unique index on (field_1, field_3) which already have duplicate data. Please check your data there must be 2 rows with the same value of field_1 and field_3 ie.(1339, 5), which is violating the unique constraint.</p>
python|django|model|key|unique
0
2,502
21,013,656
How to fetch data from AngularJS to Python Script
<p>I am new for python so if you can help me to solve my problem. I want fetch Username and Password from angularjs to python script In my python script then what mechanism i want to follow to achieve this gole. </p> <hr> <p>html code</p> <pre><code>&lt;form action="" method="post" id="homeTitle"&gt; &lt;table wid...
<p>It seems you have tagged this post as Django but have not used Django yet. I suggest that you read the <a href="https://docs.djangoproject.com/en/1.6/intro/tutorial01/" rel="nofollow">Django tutorial</a> and solve this. <a href="https://docs.djangoproject.com/en/1.6/intro/tutorial04/" rel="nofollow">Part 4</a> cover...
angularjs|python-2.7
3
2,503
21,114,246
Django ModelAdmin Fieldset within fieldset
<p>What I've been asked create is an admin page with the following layout:</p> <ul> <li><p>Fieldset 1 name</p> <ul> <li>Section 1 name <ul> <li>field 1</li> <li>field 2</li> </ul></li> </ul></li> <li><p>Fieldset 2 name</p> <ul> <li>Section 2 name <ul> <li>field 3</li> </ul></li> </ul></li> </ul> <p>and so on.</p> ...
<p>Unfortunately you're out of luck, the Django admin <a href="https://code.djangoproject.com/ticket/10590" rel="nofollow">does not support nested fieldsets</a> and has no way to output other structural tags, except by customising the templates.</p> <p>You can have a look at:<br> <a href="http://django-betterforms.rea...
python|django
2
2,504
70,149,929
Tkinter Photo Image Issues
<p>I am trying to run sample code and I am running into a problem where sublime says &quot;_tkinter.TclError: couldn't recognize data in image file &quot;C:\Users\atave\Dropbox\Python\tkinter Python Tutorial\Labels\prac.png&quot;. Can anyone tell me why? I have already set up sublime as an exception in the firewall, do...
<p>the <code>tk.PhotoImage</code> doesn't work that well with <code>.png</code> files. I would suggest conversion to <code>.bmp</code> file or using PIL(Pillow) module- <code>tk.PhotoImage(ImageTk.PhotoImage(file=&quot;C:\\Users\\atave\\Dropbox\\Python\\tkinter Python Tutorial\\Labels\\prac.png&quot;)</code></p> <p>The...
python|tkinter
-1
2,505
46,167,783
Python - multiplication between a variable that belong to the same class
<p>How to set a class variable return to other data type (list or int)?</p> <p>So I have two variable that is belong to the same class and I want to use the operator for example multiplication to both of the variables, but It cannot be done because both of them have the class data type.</p> <p>For example:</p> <pre>...
<p>To get this to work, do this:</p> <pre><code>otherclass = other.x*other.y </code></pre> <p>instead of</p> <pre><code>otherclass = other </code></pre> <p>This will mean otherclass is an int and the multiplication will work.</p>
python|python-3.x|class|oop
1
2,506
54,882,027
Inner workings of NumPy's logical_and.reduce
<p>I'm wondering how does <code>np.logical_and.reduce()</code> work.</p> <p>If I look at <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_and.html" rel="nofollow noreferrer">logical_and</a> documentation it presents it as a function with certain parameters. But when it is used with <e...
<p>I'm not sure what your question is. Using Pythons help the parameters to reduce are as shown below. <code>reduce</code> acts as a method of the ufunc, it's reduce that takes the arguments at run time.</p> <pre><code>In [1]: import numpy as np help(np.logical_and.reduce) Help on built-in function reduce: reduce(....
python|numpy
1
2,507
54,789,544
How can I print every values of each attributes of a class in Python
<p>I want to print each values of a class, but I don't know how to do it. I understand why my method of doing it doesn't work though.</p> <pre class="lang-py prettyprint-override"><code>class test: def __init__(self, a = 1, b = 2, c = 3): self.a = a self.b = b self.c = c classobject = test...
<p><code>classobject.attr</code> is specifically looking for an attribute named <code>attr</code> in <code>classobject</code>.</p> <p><code>attr</code> does not get magically replaced at runtime by the appropriate value.</p> <p>What you need is the <a href="https://docs.python.org/2/library/functions.html#getattr" re...
python|python-3.x|class
2
2,508
33,086,942
Pyglet Opengl VBOs
<p>I'm new in pyglet, B4, I've tried to use PyOpenGL with Pygame, but PyOpenGL creates weird NuffFunctionErrors, so I've moved to Pyglet.</p> <p>I've tried out this code, it runs perfectly:</p> <pre class="lang-python prettyprint-override"><code>from pyglet.gl import * window = pyglet.window.Window() vertices = [ ...
<p>Ok, I received the answer in comment, but the problem was that 12 bytes wan't enough 4 six floats.</p> <p>Each float uses 4 byte.</p>
python|opengl|pyglet
0
2,509
33,137,269
To find the _id of document other than during insertion
<p>I have created several documents and inserted into Mongo DB.I am using python for the same . Is there a way where in I can get the _id of a particular record? I know that we get the _id during insertion. But if i need to use it at a lateral interval is there a way I can get it by say using the find() command?</p>
<p>You can user the projection to get particular field from the document like this </p> <p>db.collection.find({query},{_id:1}) this will return only _id </p> <p><a href="http://docs.mongodb.org/manual/reference/method/db.collection.find/" rel="nofollow">http://docs.mongodb.org/manual/reference/method/db.collection.f...
python|mongodb
0
2,510
29,151,332
How to parse JSON from python service with unicode? SyntaxError: Unexpected token u
<p>I'm loading json from <a href="http://pythond3jsmashup.appspot.com/chart" rel="nofollow">http://pythond3jsmashup.appspot.com/chart</a> using angular js</p> <pre><code>$http.get('http://pythond3jsmashup.appspot.com/chart'); </code></pre> <p>I got this service from a an example of how to get Google BigQuery data as ...
<blockquote> <p>Angular has a problem with the json parse with unicode.</p> </blockquote> <p>No, the problem is that the service literally returns </p> <pre><code>{u'kind': u'bigquery#queryResponse', ...}`. </code></pre> <p>Which is not JSON. That <code>u</code> right after the <code>{</code> is invalid (which is...
python|json|angularjs|unicode|google-bigquery
5
2,511
28,932,344
'str' object is not callable Python to SQL database
<p>I'm trying to enter details into an SQL database through Python. I have already created the database with fields customerID, firstname, surname, town and telephone.</p> <p>When running this function, I get the error 'str' object is not callablefor the line where I am trying to INSERT the values of the variables.</...
<p>You forgot a comma between the SQL statement string and the parameters:</p> <pre><code>c.execute('INSERT INTO Customer VALUES (NULL, ?,?,?,?,)'(firstname, surname, town, telephone)) # ^ </code></pre> <p>so you effectively do this: <code>"some string"(arg1, arg2...
python
0
2,512
29,252,338
how to print list in a column?
<p>How do i print these function in one column.</p> <pre><code> item = stock.stock_list(location_name) for x in sorted(item): """Stock list of given location""" print (x) for y in sorted(item): """Stock price of give location and stock list""" print ("{0:.2f}".format(stock.stock_price(y))) for...
<p>For the second question try this:</p> <pre><code>print "(%s)" % location_id </code></pre> <p>If you want to print more variables you can do it like this:</p> <pre><code>print "%s %s (%s)" % (toptext, location_name, location_id) </code></pre>
python|python-3.x
0
2,513
8,830,216
How to write Generators , list comprehension in python
<p>When i think about any problem , thinking via list comprehension doesn't come naturally.</p> <p>Whats the best way to think through this?</p> <p>Regards Ashish</p>
<p>Here's how I think through list comprehensions.</p> <p>1) I need to output a list</p> <p>2) I'm starting with a list/iterable. </p> <p>3) I either need to perform an action on all the elements and/or choose specific elements from the original list.</p> <p>That leads me to the following construction:</p> <p><cod...
python|list-comprehension
2
2,514
8,763,730
Gunicorn + Subprocesses raises exception [Errno 10]
<p>I've stumbled across a weird exception I haven't been able to resolve... can anyone suggest what is wrong or a new design? I'm running a Gunicorn/Flask application. In the configuration file, I specify some work to do with an <code>on_starting</code> hook [1]. Inside that hook code, I have some code like this (no...
<p>The error turns out to be related to signal handling of <code>SIGCHLD</code>. </p> <p>The <code>gunicorn</code> arbiter intercepts <code>SIGCHLD</code>, which breaks <code>subprocess.Popen</code>. The <code>subprocess.Popen</code> module requires that <code>SIGCHLD</code> not be intercepted (at least, this is tru...
python|subprocess|flask|python-2.6|gunicorn
3
2,515
52,366,326
Question about Django tutorial official part3 html code
<p>I have a question about the js code when I'am learning on Django official tutorial part3. In the "Raising a 404 error" section, the official code use following code to display the "question_text" in object called "question":</p> <pre><code>{{ question }} </code></pre> <p>I don't understand why this code could work...
<p>Because you defined a <code>__str__</code> for the object:</p> <pre><code>class Question(models.Model): # ... <b>def __str__(self): return self.question_text</b></code></pre> <p>Django implicitly calls <code>str(..)</code> over the variables. In case you did not override the <code>__str__</code> ...
python|django
1
2,516
52,040,904
Working with session cookies in Python
<p>I am trying to get access to the Kerio Connect (mailserver) api which uses jsonrpc as a standard for their api.</p> <p>There is <code>Session.login</code> method that works just fine, I get back a SESSION_CONNECT_WEBADMIN cookie that gets saved in the session:</p> <pre><code>SESSION_CONNECT_WEBADMIN=2332a56d0203f2...
<p>Working example:</p> <pre><code>import json import urllib.request import http.cookiejar import ssl jar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) urllib.request.install_opener(opener) server = "https://mail.smkh.ru:4040" username = "admin" password =...
python|python-requests
0
2,517
51,676,390
What optimization algorithm is used within the .fit() method in scikit-learn?
<p>I'm curious what's 'under the hood' of <code>model.fit()</code> method from scikit-learn library? If it depends on a particular model, then let's say it's <code>linear_model.LinearRegression.fit()</code>.</p>
<p>It is dependent on the particular model. Some methods have analytical solutions, like Linear-, Ridge- and Kernel Ridge regression. Some methods like neural networks use numerical solvers. In some cases the documentation has details on the exact methods used, or have options to set it yourself.</p>
python|machine-learning|scikit-learn
1
2,518
19,152,578
No handlers could be found for logger paramiko
<p>I am using paramiko module for ssh connection.I am facing below problem:</p> <p>No handlers could be found for logger I am not getting the reason of this problem.I tried to get solution from below link but not able to get reason. <a href="https://stackoverflow.com/questions/15437700/no-handlers-could-be-found-for-l...
<p>I found the solution from <a href="https://translate.google.com/translate?hl=en&amp;sl=zh-CN&amp;tl=en&amp;u=http%3A%2F%2Fwww.ouvps.com%2F%3Fp%3D869" rel="noreferrer">this website</a>.</p> <p>Basically, you just need to add a line:</p> <pre><code>paramiko.util.log_to_file("filename.log") </code></pre> <p>Then all...
python
26
2,519
18,991,907
Creating a C++ Wrapper in Python using .dylib
<p>I'm basically trying to develop a Wrapper in Python that can access a library I have developed in C++. At the minute, it is very basic, as this is just for testing purposes. </p> <p>In my .h file I have the following:</p> <pre><code>#include &lt;iostream&gt; class Foo { public: void bar() { std::c...
<p>The <code>ctypes</code> library doesn't know about c++, you need to write your shared library in c if you want to use <code>ctypes</code>.</p> <p>You can look at something like <a href="http://www.swig.org" rel="nofollow">http://www.swig.org</a> instead, which can hook into a shared library written in c++.</p>
c++|python|macos|wrapper
1
2,520
62,065,917
How do I put together members of two Python lists that have the same indexes?
<p>How do I combine the first member of a list in Python with the first member of the second list as well as the second member of the first list with the second member of the second list? And will this happen until the last members of the lists go ahead?</p>
<p>This is a basic zip function. For example:</p> <pre><code>list_1 = [1, 2, 3] list_2 = ["s", "u", "p"] final_list = list(zip(list_1, list_2)) print(final_list) </code></pre> <p>This will return a list of tuples such that the first value from the first list is paired with the first value of the second list, iterati...
python
1
2,521
56,090,186
Class variables - missing one required positional argument
<p>I have two scripts. The first containing a class, with class variables defined and a function using those class variables. The second script calls the class and function within a function of it's own.</p> <p>This sort of set up works fine for functions inside a class, however adding class variables is causing me th...
<p>As the commentors have pointed out, since the <code>test_func</code> is a class method, we need to call it using a class instance object.</p> <p>Also <code>print</code> function returns None, so doing <code>new_var = print(var, self.test1, self.test2, self.test3)</code> assigns <code>new_var=None</code>, so if you ...
python|python-3.x
1
2,522
19,576,978
How to retrieve model column value dynamically in python
<p>Suppose I have a model object. </p> <pre><code>print (dir(table)) ['...', 'col1', 'col2', '...'] # this will output column 1 value print (table.col1) </code></pre> <p>I would like to do it dynamically, for example:</p> <pre><code>col = 'col1' table.col </code></pre> <p>Thx</p>
<p>You want to use <code>getattr</code> when doing dynamic attribute retrieval in python:</p> <pre><code>col = 'col1' getattr(table, col) </code></pre>
python|sqlalchemy
2
2,523
22,348,668
PCA decomposition with python: features relevances
<p>I'm following now next topic: <a href="https://stackoverflow.com/questions/14205941/how-can-i-use-pca-svd-in-python-for-feature-selection-and-identification">How can I use PCA/SVD in Python for feature selection AND identification?</a> Now, we decompose our data set in Python with PCA method and use for this the <c...
<blockquote> <p>what the input features proportions has every PCA component (to know, which features are much important for us). How is possible to do it?</p> </blockquote> <p>The <code>components_</code> array has shape <code>(n_components, n_features)</code> so <code>components_[i, j]</code> is already giving you ...
python|scikit-learn|pca
7
2,524
43,860,337
How can I locate to this image by using selenium (python script)?
<p><a href="https://i.stack.imgur.com/LeMNk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LeMNk.png" alt="enter image description here"></a></p> <p>I would like to know how to use selenium to locate to this img location by using selenium by using python script. I have tried:</p> <pre><code>driver...
<p>The tooltip is inside <code>&lt;iframe&gt;</code> tag, you need to switch to it first</p> <pre><code># switch to the iframe iframe = driver.find_element_by_tag_name('iframe') driver.switch_to.frame(iframe) # close the tooltip driver.find_element_by_css_selector('#welcome-tooltip-dialog &gt; .close').click() # swi...
python|selenium
1
2,525
9,088,957
SQLAlchemy cannot find a class name
<p>Simplified, I have the following class structure (in a single file):</p> <pre><code>Base = declarative_base() class Item(Base): __tablename__ = 'item' id = Column(BigInteger, primary_key=True) # ... skip other attrs ... class Auction(Base): __tablename__ = 'auction' id = Column(BigInteger, ...
<p>This all turned out to be because of the way I've set SQLAlchemy up in Pyramid. Essentially you need to follow <a href="http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/database/sqlalchemy.html#importing-all-sqlalchemy-models">this section</a> to the letter and make sure you use the same <code>decla...
python|sqlalchemy|pyramid|relationships
38
2,526
39,108,464
Running two separate (non-nested) for loops within one CSV file
<p>I am currently trying to create a config template using CSV rows and columns as variable output into a text file for one of my network configurations. Here is the code:</p> <pre><code>import sys import os import csv with open('VRRP Mapping.csv', 'rb') as f: reader = csv.reader(f) myfile = open('VRRP fix.tx...
<p>You have consumed all lines in your reader object and need to start from the beginning again. Before the second for loop add:</p> <pre><code>f.seek(0) </code></pre> <p>This will bring the pointer back to the beginning of the file so you can loop over it again. <a href="http://www.tutorialspoint.com/python/file_see...
python|networking|network-programming
2
2,527
39,328,878
Python fails to compile a regex
<p>I'm trying to detect all <code>set</code> from a cmake file using a python regex, fo the file below:</p> <pre><code># Library to include set(LIB_TO_INCLUDE a b c) # comon code (inclusion in source code) set(SHARED_TO_INCLUDE d e f) # Library to include set(THIRD_PARTY g h) </code></pre> ...
<p>This should do it: <code>set\(([^)]*?)\)</code></p> <p>The "single line" modifier is passed as an argument when you compile the regex:</p> <pre><code>&gt;&gt;&gt; t = """set(LIB_TO_INCLUDE ... a ... b ... c)""" &gt;&gt;&gt; &gt;&gt;&gt; pattern = r'set\(([^)]*?)\)' &gt;&gt;&gt; &gt;&gt;&...
python|regex
2
2,528
26,059,804
Python3 executing Javascript
<p>I need to execute a Javascript function from Python 3 (pass a few variables into it's environment and collect the result). I found pyv8 and python-spidermonkey, but neither supports Python 3.</p> <p>Is there a library for that job?</p>
<p>What you can always do:</p> <ul> <li><p>Install Node.Js binaries on the server-side</p></li> <li><p>Write a script as standalone .js file</p></li> <li><p>Pass input as command-line arguments, pipes (stdin) or files</p></li> <li><p>Execute the script using <a href="https://docs.python.org/3/library/subprocess.html?h...
javascript|python|python-3.x
1
2,529
26,211,308
preclassified trained twitter comments for categorization
<p>So I have some 1 million lines of twitter comments data in csv format. I need to classify them in certain categories like if somebody is talking about : "product longevity", "cheap/costly", "on sale/discount" etc. </p> <p>As you can see I have multiple classes to classify these tweets data into. The thing is that ...
<blockquote> <p>The thing is that how do I even generate/create a training data for such a huge data</p> </blockquote> <p>I would suggest finding a training data set that could help you with the categories you are interested in. So let's say price related articles, you might want to find a training data set that i...
python|twitter|machine-learning|classification|nltk
0
2,530
1,462,003
Django forms: how to display media (javascript) for a DateTimeInput widget?
<p>Hello (please excuse me for my bad english ;) ),</p> <p>Imagine the classes bellow:</p> <p><strong>models.py</strong></p> <pre><code>from django import models class MyModel(models.Model): content_type = models.ForeignKey(ContentType, verbose_name=_('content type')) object_id = models.PositiveIntegerField...
<p>The standard DateTimeWidget doesn't include any javascript. The widget used in the admin is a different one - <code>django.contrib.admin.widgets.AdminSplitDateTime</code> - and this includes the javascript.</p>
python|django|django-models|django-admin|django-forms
5
2,531
1,953,958
deleting old folders with datetime function
<p>I am trying to delete old folders and I am asking does anyone know how to set up a variable that allows me to check the variable 'todaystr' which is today's date and minus 7 days of this string and store it another variable. I am wanting to automatically delete old files after a week. Below shows the variable 'today...
<pre><code>import datetime import os import shutil threshold = datetime.datetime.now() + datetime.timedelta(days=-7) file_time = datetime.datetime.fromtimestamp(os.path.getmtime('/folder_name')) if file_time &lt; threshold: shutil.rmtree('/folder_name') </code></pre>
python
4
2,532
1,352,980
Multiprocessing debug techniques
<p>I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in the multiprocessing module.</p> <p>A...
<p>Yah, debugging deadlocks is fun. You can set the logging level to be higher -- see <a href="http://docs.python.org/library/multiprocessing.html" rel="noreferrer">the Python documentation</a> for a description of it, but really quickly:</p> <pre><code>import multiprocessing, logging logger = multiprocessing.log_to_...
python|debugging|deadlock|multiprocessing
45
2,533
63,013,527
Comparing pixels between image and colourbar
<p>I am working on a project where I have to extract the pixels from a thermal image and convert it into temperature to detect the respiratory time, using which I can detect the respiratory rate. I have done upto detecting the object(i.e the nostrils), but I am not sure how to extract and convert the pixel values to te...
<p>You don't need to effectively draw the color bar, it suffices to have a representation in an array. Then you can indeed match the colors of the pixels to the colors in the color bar and deduce the &quot;position&quot;. If your system is correctly calibrated, you should know the corresponding temperatures.</p> <p>For...
python|python-3.x|image-processing|heatmap|temperature
2
2,534
32,598,754
Script to Check if Torque Jobs are Running/Queued
<p>Is there a way to programmatically check if there are running and/or queued jobs? I'm looking for a script (can be Bash, Python, or any other typical language) that does that and then take some actions if necessary, e.g., shutdown the server (or in my case, an instance in Google Compute Engine). I'd also like to che...
<pre><code>import subprocess def runCmd(exe): p = subprocess.Popen(exe,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: retcode = p.poll() line = p.stdout.readline() yield line if retcode is not None: break def hasRQJob(): jobs = runCmd('qstat') f...
python|bash|scripting|torque
2
2,535
32,507,493
CPython - Making the date show up using the date on your computer
<p>I'm really new to programming and I only just started using Python, if anyone could edit the code I put up to make it work how I want it to then please do.</p> <p>I was wondering if I could make the date show up, on my python program but make it different for different regions, so if someone opened the program in U...
<p>Does this work for you?</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; today = datetime.date.today() &gt;&gt;&gt; print(today.strftime('%x')) 09/10/15 </code></pre> <p>Specifically, you probably should look at the <code>%c</code>, <code>%x</code>, and <code>%X</code> format codes. See <a href="https://do...
python|cpython
0
2,536
28,141,346
Bottle Framework PUT request
<p>This is my Bottle code</p> <pre><code>import sqlite3 import json from bottle import route, run, request def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def db_connect(): conn = sqlite3.connect('inventory....
<p>Instead of this,</p> <pre><code>name = request.PUT.get('name') </code></pre> <p>use this:</p> <pre><code>name = request.params.get('name') </code></pre>
python|bottle
0
2,537
44,266,677
Machine Learning - test set with fewer features than the train set
<p>guys. I was developing an ML model and I got a doubt. Let's assume that my train data has the following data:</p> <h2>ID | Animal | Age | Habitat</h2> <h2>0 | Fish | 2 | Sea</h2> <h2>1 | Hawk | 1 | Mountain</h2> <h2>2 | Fish | 3 | Sea</h2> <h2>3 | Snake | 4 | Forest</h2> <p>If I apply One-ho...
<p>It sounds like you have your train and test sets completely separate. Here's a minimal example of how you might automatically add "missing" features to a given dataset:</p> <pre><code>import pandas as pd # Made-up training dataset train = pd.DataFrame({'animal': ['cat', 'cat', 'dog', 'dog', 'fish', 'fish', 'bear']...
python|machine-learning
7
2,538
32,682,754
np.delete and np.s_. What's so special about np_s?
<p>I don't really understand why regular indexing can't be used for np.delete. What makes np.s_ so special? </p> <p>For example with this code, used to delete the some of the rows of this array..</p> <pre><code>inlet_names = np.delete(inlet_names, np.s_[1:9], axis = 0) </code></pre> <p>Why can't I simply use regul...
<p><code>np.delete</code> is not doing anything unique or special. It just returns a copy of the original array with some items missing. Most of the code just interprets the inputs in preparation to make this copy.</p> <p>What you are asking about is the <code>obj</code> parameter</p> <blockquote> <p>obj : slice,...
python-2.7|numpy|indexing|slice|delete-row
25
2,539
32,761,416
SyntaxError: Non-UTF-8 code starting with '\xae'
<p>I am using Python in selenium to create scripts. When used the below code getting syntax error. I could find that the issue is with the registered trademark symbol '®' in title. Please help me out of this.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdri...
<p>The content of your question is fine: I inspected it to see that StackOverflow provides the ® symbol encoded as UTF-8.</p> <p>Based on the error message in the title, Python is reading the file as UTF-8 but I suspect that your editor is using a different encoding to save the file.</p> <p>Perhaps it is using <a hre...
python
2
2,540
32,840,586
Having trouble running Python file out of Terminal. ImportError: no module named requests
<p>I originally asked this question and took up <a href="https://stackoverflow.com/questions/32839336/import-error-no-module-named-requests">Martijn Pieters solution </a> and did as he posted:</p> <p><a href="https://i.stack.imgur.com/kPDXf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kPDXf.png"...
<p>Your shebang line should read:</p> <pre><code>#!/path/to/anaconda/python </code></pre> <p>instead of <code>/usr/bin/python</code> or <code>/usr/bin/env python</code>. </p> <p>Per your comment, the solution posted <a href="https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-reque...
python|python-requests
3
2,541
14,163,532
Is there anything like Python export?
<p>We use all the time python's import mechanism to import modules and variables and other stuff..but, is there anything that works as export? like:</p> <p>we import stuff from a module:</p> <pre><code>from abc import * </code></pre> <p>so can we export like?:</p> <pre><code>to xyz export * </code></pre> <p>or ...
<p>First, import the module you want to export stuff into, so you have a reference to it. Then assign the things you want to export as attributes of the module:</p> <pre><code># to xyz export a, b, c import xyz xyz.a = a xyz.b = b xyz.c = c </code></pre> <p>To do a wildcard export, you can use a loop:</p> <pre><code...
python|python-module
9
2,542
14,010,551
How to convert between bytes and strings in Python 3?
<p>This is a Python 101 type question, but it had me baffled for a while when I tried to use a package that seemed to convert my string input into bytes. </p> <p>As you will see below I found the answer for myself, but I felt it was worth recording here because of the time it took me to unearth what was going on. It s...
<p>The 'mangler' in the above code sample was doing the equivalent of this:</p> <pre><code>bytesThing = stringThing.encode(encoding='UTF-8') </code></pre> <p>There are other ways to write this (notably using <code>bytes(stringThing, encoding='UTF-8')</code>, but the above syntax makes it obvious what is going on, and...
string|python-3.x|byte
119
2,543
47,332,282
How to install OpenCV+Python on Mac?
<p>I am trying to install OpenCV+Python on Mac. I am trying to do this in six steps by running commands at terminal (after step2):</p> <p><strong>Step1:</strong> Install Xcode</p> <p><strong>Step2:</strong> Install Homebrew </p> <p><strong>Step3: Install Python2 and Python3</strong></p> <p>1) <code>brew install pyt...
<p>The officially recommended python packaging tool is <code>pipenv</code>. One example of a workflow you could use to make a virtual environment with the exact libraries your project needs as well as ensuring security is this:</p> <pre><code>$ brew install pipenv $ cd /path/to/project $ pipenv --three $ pipenv instal...
python|macos|opencv
1
2,544
57,527,187
Get rid of script text in HTML using beautifulsoup
<p>I want to analyze all visible text from an HTML.</p> <p><a href="https://www.pflegejob.de/index.php?section=anzeige&amp;id=1233125" rel="nofollow noreferrer">Url</a></p> <p>To get rid of all HTML elements I currently use: </p> <pre><code>from bs4 import BeautifulSoup import re soup = BeautifulSoup(test.conte...
<p>Apparently, the page keeps it's content in <code>&lt;script&gt;</code> tag. To get content from it, I used <code>re</code> module:</p> <pre><code>import re import requests from bs4 import BeautifulSoup url = 'https://www.pflegejob.de/index.php?section=anzeige&amp;id=1233125' soup = BeautifulSoup(requests.get(url)....
regex|python-3.x|beautifulsoup
2
2,545
71,039,351
How do I detect laser line from 2 images and calculate its center using python opencv?
<p>How can I detect laser line using 2 images, first with laser turned off and second with turned on and then calculate its center? These are my images: <a href="https://i.stack.imgur.com/efli5.jpg" rel="nofollow noreferrer">img1.jpg</a> <a href="https://i.stack.imgur.com/u8W7w.jpg" rel="nofollow noreferrer">img2.jpg</...
<ol> <li>difference</li> <li>gaussian blur to suppress noise, and smooth over saturated sections</li> <li><code>np.argmax</code> to find maximum for each row</li> </ol> <p>I would also recommend</p> <ul> <li>some more reduction in exposure</li> <li>PNG instead of JPEG for real processing. JPEG saves space, okay for vie...
python|opencv
1
2,546
58,374,261
How to convert a rectangular matrix into a stochastic and irreducible matrix?
<p>I have written the following code to convert a matrix into a stochastic and irreducible matrix. I have followed a paper (Deeper Inside PageRank) to write this code. This code works well for the square matrix but giving an error for rectangular matrices. How can I modify it to convert rectangular matrices into stoch...
<p>You are trying to multiply two arrays of different shapes. That will not work, since one array has 30 elements, and the other has 36 elements.</p> <p>You have to make sure the array <code>e * eT_n</code> has the same shape as your input array <code>P</code>.</p> <p>You are not using the <code>row_len</code> value....
python|numpy
1
2,547
58,227,509
How to read multiple partitioned .gzip files into a Spark Dataframe?
<p>I have the following folder of partitioned data-</p> <pre><code>my_folder |--part-0000.gzip |--part-0001.gzip |--part-0002.gzip |--part-0003.gzip </code></pre> <p>I try to read this data into a dataframe using-</p> <pre><code>&gt;&gt;&gt; my_df = spark.read.csv("/path/to/my_folder/*") &gt;&gt;&gt; my_df.show(...
<p>For some reason, Spark does not recognize the <code>.gzip</code> file extension. So I had to change the file extensions before reading the partitioned data-</p> <pre><code>import os # go to my_folder os.chdir("/path/to/my_folder") # renaming all `.gzip` extensions to `.gz` within my_folder cmd = 'rename "s/gzip/g...
python|python-3.x|dataframe|pyspark|apache-spark-sql
2
2,548
33,786,956
Print string between two variable substrings
<p>I am looking for the following:</p> <pre><code>dna = '**atg**abcdefghijk**tga**aa' start = 'atg' stop = 'tag' or 'taa' or 'tga' </code></pre> <p>I would like to get all the characters between start and stop. I have tried with:</p> <pre><code>print (dna.find(start:stop)) </code></pre> <p>but it keeps me saying ...
<p>You could use a regular expression to help find any suitable matches as follows:</p> <pre><code>import re dna = 'atgabcdefghijktgaaa' start = 'atg' stop = ['tag', 'taa', 'tga'] print re.findall(r'{}(.*?)(?:{})'.format(start, '|'.join(stop)), dna) </code></pre> <p>This would display the following:</p> <pre><code...
python|regex
1
2,549
33,530,725
Alphabetically sorting URLs to Download Image
<p>Having an issue with the sorting of urls. The .jpg files end in "xxxx-xxxx.jpg". The second set of keys need to be sorted in alphabetical order. Thus far I've only been able to sort the first set of characters alphabetically (which is not necessary).</p> <p>For instance:</p> <p><a href="http://code.google.com/edu/...
<p>Given the urls end in the format <code>xxxx-yyyy.jpg</code></p> <p>and you want to sort the urls based on the second key, i.e. <code>yyyy</code></p> <pre><code>def read_urls(filename): with open(filename) as f: s = {el.rstrip() for el in f if 'puzzle' in el} return sorted(s, key=lambda u: u[-8:-4]...
python|sorting
1
2,550
46,642,360
Python unitest doesn't work
<p>I'm beginning to learn TDD. I have just started with unit test from python. When I try to execute:</p> <pre><code>vagrant@vagrant:~/pruebaTestPython$ python test_python_daily_software.py ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>I have read ...
<p>If your <code>python_daily.py</code> Python module is:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- def get_string(number): return 'Hello' </code></pre> <p>and your <code>test_python_daily_software.py</code> test module is:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import unittes...
python|unit-testing|tdd
1
2,551
38,019,888
Python: Writing to csv-file
<p>I am trying to read a csv-style file and create another one. Here is the (simplified) code.</p> <pre><code>import os import csv import sys fn = 'C:\mydird\Temp\xyz' ext = '.txt' infn = fn+ext outfn = fn+'o'+ext infile = open(infn, newline='') outfile = open(outfn, 'w', newline='') try: reader = csv.reader(i...
<p>Your code doesn't define a writer.</p> <p>Add <code>writer = csv.writer(outfile)</code> and then close the outfile and it should work. Using the <code>with</code> idiom makes the code cleaner.</p> <pre><code>import csv fn = 'C:\mydird\Temp\xyz' ext = '.txt' infn = fn+ext outfn = fn+'o'+ext with open(infn) as rf...
python|csv
4
2,552
37,863,253
Reverse a python dictionary ordered pairs
<p>This question has been asked many times, and I searched diligently to no avail. Here is an example of my question:</p> <p><code>dict = {"a":"1", "b":"2", "c":"3"}</code></p> <p>The output I am looking for is as below:</p> <p><code>dict = {"c":"3", "b":"2", "a":"1"}</code></p> <p>I am really unsure how to attack...
<p>Firstly, the <code>dict</code> object of python is a hashtable, so It have no order. but if you only want to get a list is order you can use <code>sorted(iterable, key=None, reverse=False)</code> method. <code> def order(dic): return sorted(dic.items(),key=lambda x:x[1],reverse=True) </code></p>
python|python-2.7|sorting|dictionary|reverse
0
2,553
37,850,869
Storing objects in file instead of in memory
<p>I've created a genetic programming system in Python, but am having troubles related to memory limits. The problem is with storing all of the individuals in my population in memory. Currently, I store all individuals in memory, then reproduce the next generation's population, which then gets stored in to memory. This...
<p>Given the RAM constraint, I'd change the population model from generational to <strong><em>steady state</em></strong>.</p> <p>The idea is to iteratively breed a new child or two, assess their fitness and then reintroduce them directly into the population itself, killing off some preexisting individuals to make room...
python|memory|memory-management|genetic-programming
2
2,554
30,043,709
Python: sorting a list of tuples on alpha case-insensitive order
<p>I have a list of tuples ("twoples")</p> <pre><code>[('aaa',2), ('BBB',7), ('ccc',0)] </code></pre> <p>I need to print it in that order, but</p> <pre><code>&gt;&gt;&gt; sorted([('aaa',2), ('BBB',7), ('ccc',0)]) </code></pre> <p>gives</p> <pre><code>[('BBB', 7), ('aaa', 2), ('ccc', 0)] list.sort(key=str.tolower)...
<p>You're right that this is a Python 2 thing, but the fix is pretty simple:</p> <pre><code>list.sort(key=lambda a: (a[0].lower(), a[1])) </code></pre> <p>That doesn't really seem any less clear, because the names <code>a</code> and <code>b</code> don't have any more inherent meaning than <code>a[0]</code> and <code>...
python|list|sorting
8
2,555
30,150,537
Python Quicksort Recursion unsupported operand type(s) for -: 'list' and 'int'`
<p>I have been having issues with a sorting program I am writing, the error </p> <pre><code>Traceback (most recent call last): File "/Users/Shaun/PycharmProjects/Sorts/BubbleSort.py", line 117, in &lt;module&gt; sorted = quick_sort(unsorted, 0, len(unsorted - 1)) TypeError: unsupported operand type(s) for -: 'li...
<p>It is clearly stated in the Error message:</p> <pre><code>TypeError: unsupported operand type(s) for -: 'list' and 'int' </code></pre> <p>It means you are doing an operation, which is "-" (as stated in the error message: "for -") on operands whose type(s) not supported by this Operation.</p> <p>So you were subtra...
python|function|sorting|call
3
2,556
29,959,044
Removing comments using lex: why doesn't this work?
<p>I'm writing a parser using Python/lex and trying to create an entry to remove C-style comments. My current (faulty) attempt is:</p> <pre><code>def t_comment_ignore(t): r'(\/\*[^*]*\*\/)|(//[^\n]*)' pass </code></pre> <p>This produced a quirk that baffled me. When I parse the string below: </p> <pre><code...
<p>My guess is that your pattern for EQUALS matches <code>=.</code> instead of (or as well as) <code>=</code>. </p> <p>By the way, the correct comment pattern is <code>/[*][^*]*[*]+([^/*][^*]*[*]+)*/|//[^\n]*</code>.</p>
python|lex|ply
1
2,557
61,490,560
Python 3 decimal module calculation reversability
<p>I am trying to implement a reversible physics engine so I have decided to use the decimal module. So this obviously works.</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; a = Decimal('1') &gt;&gt;&gt; b = Decimal('0.82') &gt;&gt;&gt; a = a*b/b &gt;&gt;&gt; print(a) 1 </code></pre> <p>However, when t...
<p>Decimal doesn't have infinite precision. You can <a href="https://docs.python.org/3/library/decimal.html#quick-start-tutorial" rel="nofollow noreferrer">increase its precision</a> if you're finding it too inaccurate.</p> <pre><code>from decimal import * getcontext().prec = some larger number </code></pre>
python|decimal|precision|bignum|arbitrary-precision
2
2,558
65,793,281
My code is wrong? I can't seem to find the answer
<p>Question is:</p> <blockquote> <p>Create a text file named team.txt and store 8 football team names and their best player, separate the player from the team name by a comma. Create a program that reads from the text file and displays a random team name and the first letter of the player’s first name and the first let...
<p>The issue is with this line:</p> <pre><code>splitLetters = letters.append('') </code></pre> <p>The issue is .append() does not return any value, so splitLetters is <code>None</code> and therefore doesn't have a length. To use .append(), you need to append directly to the string (i.e letters.append('t') would append ...
python|syntax|file-handling
0
2,559
72,389,951
List to a json object
<p>I have a list of ec2 instanceID like below:</p> <pre><code>['i-111111111111', 'i-22222222222'] </code></pre> <p>And I want to convert it to json.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;instance_id&quot;: &quot;i-111111111111&quot;, &quot;instance_id&quot;: &quot;i-222222222222&quot; } </c...
<pre><code>li = ['i-111111111111', 'i-22222222222'] di = dict() for i in li: a = {'instance_id':i} di.update(a) print(di) </code></pre> <p>But having a single key is not a good approach</p>
python|python-3.x|amazon-web-services
0
2,560
72,321,396
Query SQL Server encrypted columns through python and show decrypted values
<p>I am trying to query a table (in an on premise database), which has some encrypted columns, in Python. I don't have any problem querying this data in Microsoft SQL Server Management Studio. Since I have a certificate, I just use Windows authentication to login, and in Additional Connection Parameters, I add &quot;Co...
<p><code>Driver={SQL Server}</code> (SQLSRV32.DLL) is the ancient SQL Server driver that ships with Windows. It dates back to the days of SQL Server 2000 and does not support many of the more modern SQL Server features.</p> <p>Today's applications should use a more current driver like <code>Driver=ODBC Driver 17 for SQ...
sql-server|python-3.x|encryption|pyodbc|pymssql
2
2,561
37,140,873
Pass arguments to slot function built by QT Designer
<p>I'm new to GUI designing and I started working with QT Designer 4.8.6. I'm connecting buttons to function using the signals-slots mechanism.</p> <p>Here is some connections generated by the pyuic4 util to create the GUI script:</p> <pre><code>QtCore.QObject.connect(self.btn_add_codes, QtCore.SIGNAL(_fromUtf8("clic...
<p>Does this lambda work? At least that's how I do it with Qt when using C++.</p> <pre><code>self.btn_add_codes.clicked.connect(lambda codes=self.path_codes: MainWindow.select_file(codes)) </code></pre>
python|c++|qt|user-interface|qt-designer
0
2,562
37,142,838
Convert time strings to integers
<p>I am reading in a file that has a column of times that is in the format of hour, minute, seconds (023456). There are other columns in the file that I am not dealing with at the time. I have ignored the other values. </p> <pre><code>020746 10 -1 020823 5 -1 020839 6 -1 020812 6 0 </code></pre> ...
<p>As suggested by pyNoob. Create a <code>list</code> with the times and <code>append</code> the info to it.</p> <pre><code>time_list = [] f = open(file, 'r') for line in flash: line = line.strip() columns = line.split() time = columns[0] hour = int(time[0:2]) minute = int(time[2:4]) second = i...
python|string
0
2,563
48,448,577
Interrupt python grpc client when receiving stream
<p>I am playing a little bit with gRPC and I do not know how to close a connection between a client and the server when receiving a stream. Both the client and the server are written in Python.</p> <p>For example, my server reads messages from a Queue and it yields each message. My idea is that the client subscribes t...
<blockquote> <p>I would like to get the client killed whenever CTRL+C is pressed, but it gets stuck with the current code. How can it be done properly?</p> </blockquote> <p>The <code>KeyboardInterrupt</code> should be enough to terminate the client application. Probably the process is hanging on the <code>stub.uns...
python|queue|python-multithreading|grpc
3
2,564
48,471,955
Test the presence of a subexpression involving noncommutative symbols
<p>I have the following Sympy expression</p> <pre><code>expr=b0*d0*u0 - b0*d1*u1 - b1*d0*u1 - b1*d1*u0 + d0*b0*u0 - d0*b1*u1 - d1*b0*u1 - d1*b1*u0 </code></pre> <p>And I want to know if, for example, the product</p> <pre><code>d0*u0 </code></pre> <p>is in this expression. For this, I use</p> <pre><code>print(expr....
<p>This appears to be currently an issue with noncommutative symbols, otherwise <code>expr.has(d0*u0)</code> returns True. </p> <p>The following works whenever <code>subs</code> can identify a subexpression:</p> <pre><code>dummy = Dummy() print(expr.subs(d0*u0, dummy).has(dummy)) </code></pre> <p>I.e., replace the s...
python|sympy
0
2,565
19,865,649
A single executable file with Py2Exe
<p>I have been trying to make a single executable file and I am getting close. Please do not recommend that I use PyInstaller -- I have tried that route, asked on SO <a href="https://stackoverflow.com/questions/19669640/bundling-data-files-with-pyinstaller-2-1-and-meipass-error-onefile">here</a>, and have put in ticke...
<p>Guy <a href="https://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014">here</a> explains how to package to one file with py2exe. He's setup doesn't package resources inside the executable either.</p> <p>When I package my apps, I don't use one executable option</p> <pre><code>options...
python|python-2.7|matplotlib|executable|py2exe
4
2,566
66,840,201
how to monitor availability Decathlon's products with python?
<p>I have a request for you.</p> <p>I wanna to <strong>scrape</strong> the following product <a href="https://www.decathlon.it/p/kit-manubri-e-bilanciere-bodybuilding-93kg/_/R-p-10804?mc=4687932&amp;c=NERO#" rel="nofollow noreferrer">https://www.decathlon.it/p/kit-manubri-e-bilanciere-bodybuilding-93kg/_/R-p-10804?mc=4...
<p>Try this:</p> <pre><code>import requests import re import time urls = ['p/kit-manubri-e-bilanciere-bodybuilding-93kg/_/R-p-10804.html'] user_agent = {'User-agent': 'Mozilla/5.0'} def main(site): with requests.Session() as req: for url in urls: r = req.get(site.format(url), headers=user_agen...
python|python-3.x|web-scraping|request
0
2,567
4,120,258
Python Cookies and PHP virtual()
<p>I narrowed down the problem:</p> <pre><code>os.environ.get('HTTP_COOKIE') </code></pre> <p>This always seems to be None when calling the Python file with that line using PHP's virtual(). Does anyone know why this is?</p> <p>I'm using Python 2.7 because of how much I need the Python Imaging Library.</p> <p><stron...
<p>Try to set cookies by your own with <a href="http://www.php.net/manual/en/function.apache-setenv.php" rel="nofollow">apache_setenv</a> function.<br> But if the only thing that you need from python is PIL, then you probably don't need python at all. PHP have very powerful tools like <a href="http://www.magickwand.org...
php|python|cgi
0
2,568
48,116,218
Multiple keys vs dictionary in memcache?
<p>What is a better approach? Having multiple keys or having a dictionary?</p> <p>In my scenario I want to store songs in a country basis and cache that for further access later on. Below I write the rough pseudocode without disclosing too many details to keep it simple. The actual songs will most probably be IDs from...
<p>As mentioned in the comment it mainly depends on the application requirement. </p> <p>To Add another perspective,</p> <p>You can think of it as the problem of 'storing and retrieve 1 object vs multiple granular objects'. There is a detailed discussion on this tradeoff in this <a href="https://stackoverflow.com/que...
python|django|caching|memcached
1
2,569
51,250,987
How to update the weights of a Tensorflow.js model?
<p>I currently have a tensorflow.js convolutional neural network model that detects if certain images are happy or sad (based on facial expression). This is done through the browser with the user uploading an image of a face or using the webcam which the model then determines the outcome for. However, the user also has...
<p>You can update the data of the objects within the Cloud Storage bucket by <a href="https://cloud.google.com/storage/docs/using-object-versioning" rel="nofollow noreferrer">setting up Object Versioning</a>. Only thing is that if you want to access a previous version of the object, you would have to use the generation...
javascript|tensorflow|keras|google-cloud-storage|tensorflow.js
0
2,570
73,765,374
Generating a date in a particular format using python
<p>I have a python code that looks like this. I am receiving the values of year, month and day in form of a string. I will test whether they are not null.</p> <p>If they are not null I will like to generate a date in this format MMddyyyy from the variables</p> <pre><code> from datetime import datetime y...
<p>It should work without calling <code>len</code> as well.</p> <pre><code>from datetime import datetime, date year = &quot;2022&quot; month = &quot;7&quot; day = &quot;15&quot; if year and month and day: print('variables are not empty') prepare = date(int(year), int(month), int(day)) valueDt = datetime.s...
python-3.x
1
2,571
17,562,182
Scrapy image problems on production server
<p>I have a scrapy script to download images from a site. Locally work perfectly, and also seems on production server, but despite not receiving any error, don't save the images.</p> <p>This is the output on production server:</p> <pre><code>2013-07-10 05:12:33+0200 [scrapy] INFO: Scrapy 0.16.5 started (bot: mybot) 2...
<p>From the <a href="http://doc.scrapy.org/en/latest/topics/images.html" rel="nofollow">docs</a>:</p> <blockquote> <p>The images in the list of the images field will retain the same order of the original image_urls field. If some image failed downloading, an error will be logged and the image won’t be present in the...
python|image|scrapy
0
2,572
17,160,151
Is tzinfo=tzutc() same as +00:00 in python?
<p>Are both the time formats equivalent in python : </p> <pre><code>datetime.datetime(2013, 6, 17, 7, 46, 0, 609263, tzinfo=tzutc()) datetime.datetime(2013, 6, 17, 7, 46, 0, 609263, +00:00) </code></pre> <p>Also is there a way to replace <code>tzinfo=tzutc()</code> with <code>+00:00</code> and vice versa?</p>
<p>If you look into the <a href="http://bazaar.launchpad.net/~dateutil/dateutil/trunk/view/head:/dateutil/tz.py" rel="nofollow">source of dateutil</a> </p> <pre><code>ZERO = datetime.timedelta(0) # same as 00:00 class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def dst(self, dt): ...
python
2
2,573
70,449,909
Find all partitions of n of length less-than-or-equal to L
<p>How might I find all the <a href="https://en.wikipedia.org/wiki/Partition_(number_theory)" rel="nofollow noreferrer">partitions</a> of <code>n</code> that have length less-than-or-equal-to <code>L</code>?</p>
<p>Based on the code given <a href="https://stackoverflow.com/a/44209393/3614134">here</a>, we can include an additional argument <code>L</code> (which defaults to <code>n</code>).</p> <p>We might naively include <code>if len((i,) + p) &lt;= L:</code> before <code>yield (i,) + p</code>. However, since <code>len((i,) + ...
python|python-3.x|combinatorics
0
2,574
69,926,410
Creating a new variable with the average of categories of another variable
<p>I have data of houses sold in different locations. There are a variable &quot;zipcode&quot; and a variable &quot;price&quot;. I have to predict for every object the average price for the relative zipcode.</p> <pre><code>import pandas as pd data = {&quot;zipcode&quot;:[100, 100, 101, 101], &quot;price&quot;:[500, 60...
<p>You can actually merge the result with the dataframe:</p> <pre><code>df = df.merge(zipcode_mprice, on= &quot;zipcode&quot; ) df.columns = [&quot;zipcode&quot;,&quot;price&quot;,&quot;mean_zipcode&quot;] df </code></pre> <p><a href="https://i.stack.imgur.com/SPkAC.png" rel="nofollow noreferrer"><img src="https://i.st...
python|replace
0
2,575
72,965,205
How to fix ERR_TOO_MANY_REDIRECTS?
<p>I'm developing a site on Django, but I got an error ERR_TOO_MANY_REDIRECTS. I think that the matter is in the views.py file. Help figure it out. P.S. already tried to delete cookie files, it didn't help(</p> <pre><code>from email import message from wsgiref.util import request_uri from django.shortcuts import redire...
<p>The problem is coming from your <code>return redirect('/')</code>. Redirect to one of the views written in your <code>urls.py</code> and your problem will be solved.</p>
python|django
1
2,576
55,635,090
How to execute a function on two values of two separate arrays
<pre><code>for value in distance_moduli_error_array: DM_error = (np.log(10)*(10**((distance_moduli_array/5)+1))*(value*0.2)) list.append(distance_to_galaxies_parsecs_error, DM_error) </code></pre> <p><code>distance_moduli_error_array</code> and <code>distance_moduli_array</code> are two arrays each with 8 valu...
<pre><code>for x,y in zip(distance_moduli_error_array, distance_moduli_array): DM_error = (np.log(10)*(10**((y/5)+1))*(x*0.2)) list.append(distance_to_galaxies_parsecs_error, DM_error) </code></pre> <p>Use <code>zip</code></p>
python
0
2,577
55,650,373
Where do I find the python source code/documentation for the selenium ActionBuilder class?
<p>I would like to rewrite the selenium <a href="https://seleniumhq.github.io/selenium/docs/api/py/_modules/selenium/webdriver/common/action_chains.html#ActionChains" rel="nofollow noreferrer">ActionChains class</a> and noticed that it uses the ActionBuilder class. Browsing the python documentation and the internet I w...
<p>You can find the source code in the selenium github repository. But I don't know if there are any documentation for <code>ActionBuilder</code> class exists or not. </p> <p>Here is the link to <code>action_builder.py</code> file. <a href="https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/comm...
python|selenium|selenium-webdriver
1
2,578
64,760,626
Why are tables not being created in flask SQLAlchemy?
<p>This is what I have in my app.py:</p> <pre><code>from flask import Flask, render_template, url_for, request, redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///D:/Documents/.my projects/flask-website/blog.db' db = ...
<p>Turns out I had my file path wrong in <code>app.config['SQLALCHEMY_DATABASE_URI']</code>... currently hitting my head on my desk because I have spent more time than I care to admit on this issue.</p>
python|sqlite|flask|flask-sqlalchemy
0
2,579
65,102,318
How can I achieve a 30 FPS frame rate using this Python screen recorder code?
<p>I want a screen recorder. I thought of making my own.</p> <p>I checked the internet and found: <a href="https://www.thepythoncode.com/code/make-screen-recorder-python" rel="nofollow noreferrer">https://www.thepythoncode.com/code/make-screen-recorder-python</a></p> <p><strong>The Code:</strong></p> <pre><code>import ...
<p>basically if you want to continue with your same code, you will have to compromise on resolution or frame rate.</p> <p>My suggestion is to try the <code>cv2.VideoCapture()</code> functionality.</p> <p>I am attaching the link to the webpage where there is a detailed step-by-step process where the author has achieved ...
python|frame-rate|pyautogui|screen-recording
1
2,580
68,624,410
what is the easiest way to find if a specific value exists in a table with multiple rows on a website using selenium in python?
<p>I am trying to make my script perform a specific action based on the existence of a value in a table row on a website. E.g if x is in row 1 of table 'lab', create investigation, else move to next row and check if x is in that row. Sorry the website I am trying this on is not accessible by those who do not have an ac...
<p>If I understand correctly what you need, you should remove both <code>continue</code> from your code and the <code>break</code> at the bottom as well and add a <code>break</code> inside the <code>if</code> and <code>else</code> blocks so if you found the condition you are looking for and performed the action you nee...
python|selenium|for-loop|automation|nested-for-loop
1
2,581
70,304,403
Kivy add widget won't appear on screen:
<p>I'm stuck with the following problem:</p> <p>When I run the following code - this seems to work:</p> <pre><code>class Board(GridLayout): def __init__(self, numLines=8, numCols=8, **kwargs): # constructor of the board GridLayout._init_(self, **kwargs) self.finish_game = Button() # ...
<p>Running <code>Board()</code> creates an instance of the <code>Board</code> class, but that doesn't fundamentally draw anything. It will appear on your screen only if you add it to your widget tree somehow.</p> <p>In your code you <code>return Board()</code>, but that return doesn't go anywhere so the <code>Board()</...
python|kivy|grid-layout
1
2,582
60,824,850
How to import pyinstaller modules/files
<p>I have files with functions which I've already compiled with pyinstaller. How would I import these files' functions into a new python file? Is this even possible?</p> <p>(The idea is for them to be somewhat of an equivalent to a Windows dll. Ideally I would like to dynamically import functions from these files.)</p...
<p>As far as I know,no.The pyinstaller basicly creates a compiled .pyc file plus the interpter.</p> <p>If you want to have something like the DLL, you may turn to the .pyd files.</p>
python|python-3.x|pyinstaller
0
2,583
60,803,964
Python distribute 8 bits into beginnings of 4 x 8 bits, two by two
<p>I have an integer that is 8 bits and I want to distribute these bits into beginnings of 4 integers (4x8 bit) two by two. For example:</p> <pre class="lang-py prettyprint-override"><code>bit_8 = 0b_10_11_00_11 bit_32 = b"\x12\x32\x23\54" # --&gt; [0b100_10, 0b1100_10, 0b1000_11, 0b1011_00] what_i_want = [0b100_10, ...
<p>You could do it by iterating in reverse on <code>bit_32</code>, and at the same time taking the last two bits of <code>bit_8</code>, then shifting it right. This way, you can build a list of the output values, in reverse order, which you can reorder while converting to bytes.</p> <pre><code>bit_8 = 0b_10_11_00_11 ...
python|bit-manipulation|bitwise-operators
1
2,584
60,916,649
How to I get July month of all years in a yearly time series? (Jupyter notebook)
<p>I need some help to get my script to plot my SPI values only for July-month. My script looks like this:</p> <pre><code>from pandas import read_csv import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import cartopy %matplotlib inline df = pd.read_csv('SPI1_and_rr_for_200011.0.csv...
<p>Make sure <code>df['time']</code> is of type <code>datetime</code> and use the <code>dt</code> accessor to filter by month.</p> <pre><code># Convert to datetime df['time'] = pd.to_datetime(df['time']) # Filter by month number (July == 7) july_df = df[df['time'].dt.month == 7] </code></pre>
python|pandas|datetime
1
2,585
69,067,530
how to solve weasyprint error message gobject-2.0-0 error 0x7e message?
<p>I installed several files based upon `https://pbpython.com/pdf-reports.htm to create reports. However the following error messages</p> <pre><code>Traceback (most recent call last): File &quot;C:\histdata\test02.py&quot;, line 10, in &lt;module&gt; from weasyprint import HTML File &quot;C:\Users\AquaTrader\Ap...
<p>The error means that the <code>gobject-2.0.0</code> library, which is part of GTK3+, cannot be found. Did you follow the installation instructions (<a href="https://doc.courtbouillon.org/weasyprint/stable/first_steps.html" rel="nofollow noreferrer">https://doc.courtbouillon.org/weasyprint/stable/first_steps.html</a>...
python|weasyprint
5
2,586
62,921,081
Beautiful Soup - making a list
<p>I've been at it for several days in the soup trying to scrape a simple html structure into a list to make a dataframe. If it was html tables i have no problem. I am working with a structure like:</p> <pre><code> &lt;div class=&quot;someTypeofRow&quot;&gt; &lt;a href=&quot;/mainpage/choc.html&quot;&gt; ...
<p>You can select all <code>&lt;a&gt;</code> tags whose <code>href=</code> begins with <code>&quot;/mainpage&quot;</code> and then do <code>.find_next()</code> for <code>&lt;span class=&quot;yearText&quot;&gt;</code>.</p> <p>For example:</p> <pre><code>import pandas as pd from bs4 import BeautifulSoup txt = ''' ...
python-3.x|beautifulsoup
1
2,587
31,506,987
Scikit-Learn One-hot-encode before or after train/test split
<p>I am looking at two scenarios building a model using scikit-learn and I can not figure out why one of them is returning a result that is so fundamentally different than the other. The only thing different between the two cases (that I know of) is that in one case I am one-hot-encoding the categorical variables all a...
<p>While the previous comments correctly suggest it is best to map over your entire feature space first, in your case both the Train and Test contain all of the feature values in all of the columns.</p> <p>If you compare the <code>vectorizer.vocabulary_</code> between the two versions, they are exactly the same, so th...
python-2.7|scikit-learn
14
2,588
61,251,379
Appending HDFStore pandas TypeError
<p>According to <a href="https://stackoverflow.com/a/46206376/11578009">https://stackoverflow.com/a/46206376/11578009</a> I am trying to append HDFStore file</p> <pre><code>import pandas as pd hdfStore = pd.HDFStore('dataframe.h5') #df= #a b c d f #0 125 ...
<p>I found out answer when I was replicating error, but maybe it will be useful for sb.</p> <p>Error does not occur when dtypes in used pd.DataFrame are </p> <pre><code>df.dtypes Out[65]: time_diffrences int64 temp_diffrences int64 label object dtype: object </code></pre> <p>So dtypes cant be f...
python|pandas|hdf5
0
2,589
56,277,014
I have a code where I import another code file, but the other code gets executed before my actual code runs
<p>So I am making <strong>a Voice assistant</strong>, and then I have to <strong>import another file</strong>, but the file always gets <strong>executed</strong>.</p> <p>So I know there is a <strong>fix using an if loops</strong> but none of the answers are <strong>elaborate enough</strong>.</p> <pre><code>#voice_ass...
<p>What you want to do is write everything in your second module that runs right away inside a check like this: </p> <pre><code>if __name__ == "__main__": do_things() </code></pre> <p>this way, your <code>do_things()</code> function will be called if you open up this file and run it directly, BUT if you import th...
python-3.x
0
2,590
45,303,724
How can I create a list of records groupedby index in Pandas?
<p>I have a CSV of records:</p> <pre><code>name,credits,email bob,,test1@foo.com bob,6.0,test@foo.com bill,3.0,something_else@a.com bill,4.0,something@a.com tammy,5.0,hello@gmail.org </code></pre> <p>where <code>name</code> is the index. Because there are multiple records with the same name, I'd like to roll the enti...
<p>Is that what you want?</p> <pre><code>cols = df.columns.drop('name').tolist() </code></pre> <p>or as recommended by @jezrael:</p> <pre><code>cols = df.columns.difference(['name']) </code></pre> <p>and then:</p> <pre><code>s = df.groupby('name')[cols].apply(lambda x: x.to_dict('r')).to_json() </code></pre> <p>...
python|json|pandas|csv|numpy
4
2,591
45,656,457
How to print the processing steps/report from model.fit MXNet Python
<p>I am trying to train my 20x20 images dataset using MXNet deep learning library, you can see the code below: the question is when I run it, although it shows no errors it returns nothing, I mean it does not show any processing like :</p> <p>epoch 0 : ........accuracy:.....</p> <p>epoch 1 : ........accuracy:.....</p...
<p>Solved add to your code these lines:</p> <pre><code>import logging logging.getLogger().setLevel(logging.INFO) </code></pre> <p>for different types of processing report, refer to "Callback API in MXNet" </p>
python|mxnet
2
2,592
57,146,518
Detect difference in x, y direction between 2 images using OpenCv and ORB detector
<p>I am trying to detect is there any shift in x or y direction between 2 images, one of the images is reference image and the other one is live image coming from camera. </p> <p>Idea is to use ORB detector to extract keypoints in 2 images and then use BFFMatcher to find good matches. After that do further analysis by...
<p>Basically, you want to know <a href="https://stackoverflow.com/questions/30716610/">How to get pixel coordinates from Feature Matching in OpenCV Python</a>. Then you need some way to filter outliers. If only differnce between your images is translation (shift) on live image, this should be straightforward. But I'd s...
python|opencv|orb
0
2,593
31,196,760
How to filter out data into unique pandas dataframes from a combined csv of multiple datatypes?
<p>Sample csv</p> <pre><code>time,type,-1, time,type,0,w time,type,1,a,12,b,13,c,15,name,apple time,type,5,r,2,s,43,t,45,u,67,style,blue,font,13 time,type,11,a,12,c,15 time,type,5,r,2,s,43,t,45,u,67,style,green,font,15 time,type,1,a,12,b,13,c,15,name,apple time,type,11,a,12,c,15 time,type,5,r,2,s,43,t,45,u,67,style,gr...
<pre><code>import pandas as pd headers = {1:['a','b','c','name'], 5:['r','s','t','u','style','font'], } usecols = {1:[4,6,8,10], 5:[4,6,8,10,12,14], } frames = {} for h in headers: frames[h] = pd.DataFrame(columns=headers[h]) count = 0 for line in open('irreg.csv'): row = l...
python|numpy|pandas|matplotlib|data-analysis
1
2,594
40,245,687
How to create files which are named by the elements of a column stored in a file?
<p>I have a file which contains two columns, the first one contains the name and the second one contains the measurements for the corresponding names.</p> <p>I need to create files with the name of the measurements, and each measurement has the corresponding measurement for it.</p> <p>In other words, I need to make f...
<p>This code works...</p> <pre><code>import numpy as np arr = np.genfromtxt('file.txt', dtype=str) for i in range(0, len(arr)): np.savetxt(arr[i, 0], [float(arr[i, 1])]) # int -&gt; float </code></pre>
python|for-loop
1
2,595
40,206,598
sklearn custom scorer multiple metrics at once
<p>I have a function which returns an <code>Observation</code> object with <strong>multiple</strong> scorers How can I integrate it into a custom sklearn scorer? I defined it as:</p> <pre><code>class Observation(): def __init__(self): self.statValues = {} self.modelName = "" def setModelName(s...
<p>In short: you cannot.</p> <p>Long version: scorer <strong>has to</strong> return a single scalar, since it is something that can be used for model selection, and in general - comparing objects. Since there is no such thing as a complete ordering over vector spaces - you cannot return a vector inside a scorer (or di...
python|scikit-learn|classification|scoring
4
2,596
47,811,533
can't perform this operation for unregistered loader type
<p>I'm using bokeh for data visualization, and trying to make an executable but it shows an error message of "can't perform this operation for unregistered loader type"</p> <p>I have tried as a solution of <strong>init</strong>.py to the directory (+subdir) of my script.py, but it's not work.</p> <p>PS. Win10, Python...
<p>Ran into the same error using pyinstaller.</p> <p>This should solve your problem and the problem of not finding jinja2 that will follow:</p> <p>edit the file: your-python-env\Lib\site-packages\bokeh\core\templates.py</p> <p>(nb: change your-python-env to wherever you've installed python)</p> <p>and change the im...
python-3.x|bokeh|pyinstaller
3
2,597
34,208,466
numpy, get maximum of subsets
<p>I have an array of values, said <code>v</code>, (e.g. <code>v=[1,2,3,4,5,6,7,8,9,10]</code>) and an array of indexes, say <code>g</code> (e.g. <code>g=[0,0,0,0,1,1,1,1,2,2]</code>).</p> <p>I know, for instance, how to take the first element of each group, in a very numpythonic way, doing:</p> <pre><code>i...
<p>You can use <code>np.maximum.reduceat</code>:</p> <pre><code>&gt;&gt;&gt; _, idx = np.unique(g, return_index=True) &gt;&gt;&gt; np.maximum.reduceat(v, idx) array([ 4, 74, 10]) </code></pre> <p>More about the workings of the ufunc <code>reduceat</code> method can be found <a href="http://docs.scipy.org/doc/numpy/re...
python|arrays|numpy|max|vectorization
6
2,598
47,145,044
Django Inline Formset - possible to follow foreign key relationship backwards?
<p>I'm pretty new to django so I apologize if this has an obvious answer.</p> <p>Say you have the following three models:</p> <pre><code>models.py class Customer(models.Model): name = models.CharField() slug = models.SlugField() class Product(models.Model): plu = models.Charfield() description = mod...
<p>The formset functionality is only to show forms but something that you can do is create a custom form that display the 2 fields with the function of <code>readonly</code> like: </p> <pre><code>class your_form(models.ModelForm): class Meta() model = Template fields = ['price', 'product'] d...
python|django|python-3.x
1
2,599
64,593,474
How can I solve this problem that shows me the correct output?
<pre><code>import mysql.connector from tabulate import tabulate cnx = mysql.connector.connect(user = 'root' , password = '',host = 'localhost', database = 'karmand') c = cnx.cursor() c.execute('''CREATE TABLE IF NOT EXISTS employee ( Name text, Weight integer, Height integer ...
<p>An Order By clause can contain multiple items quite simply. So to order by height and then by weight, do this:</p> <pre><code>SELECT * FROM employee ORDER BY Height DESC, Weight ASC </code></pre> <p>Live demo: <a href="https://dbfiddle.uk/?rdbms=mysql_8.0&amp;fiddle=7f33f82b79724920be1e1499c4dff9da" rel...
python|mysql|sql
3