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
7,500
69,170,845
Prevent nodes from overlapping the edge of the image in python iGraph
<p>I am using iGraph for python to draw some graphs and I cannot seem to prevent the nodes from hitting the edge of the image, especially with very few nodes. In cases with thousands of nodes the opposite is actually true, they are too clustered in the center. Is there a way to influence the behavior of the layout to c...
<p>Yes, there is a way to define a margin within the visual style dictionary. You can use the following command: visual_style['margin'] and define your margins as a dictionary within a dictionary.</p> <pre><code>visual_style['unit'] = 'cm' visual_style['margin'] = {'top': 1, 'bottom': 1, 'left': 3, 'right': 3} </code><...
python|networkx|igraph
0
7,501
72,691,571
Rate limiting Kedro API requests
<p>I have a few datasets from the government dataset that I'm using on my ML model, the problem is, their server is not that great to put it nicely. Whenever I run my pipeline, when I pull from their API all at once, their server goes down for a few minutes.</p> <p>This is how their data is represented on our <code>cat...
<p>I would consider subclassing the <code>APIDataSet</code> and building in a caching mechanism - you could say pickle responses and build some sort of 'expiry' mechanism where you:</p> <ol> <li>If pickle doesn't exist, call API and save response as pickle</li> <li>If pickle exists and within 'fresh' window, read from ...
python|machine-learning|kedro|mlops
0
7,502
62,440,606
When i call method has a for loop it returns one line
<pre><code> def pagination(): pagination = range(1, 5) for p in pagination: page = f"https://www.xx.xx{p}" return (page) </code></pre> <p>when I call the method it doesn't loop and It only returns this line <a href="https://www.xx.xx1" rel="nofollow noreferrer">https://www....
<p>Return stops the whole function, therefore the loop is immediatly terminated. Try using a list and appending onto that. At the end you can return this list.</p>
python|python-3.x
1
7,503
49,295,149
Validate json string against api.model
<p>I want to post json along with image bytes. I'm using api.parser to specify expected parameters:</p> <pre class="lang-py prettyprint-override"><code>upload_parser = api.parser() a=True upload_parser.add_argument('image', location='files', type=FileStorage, ...
<p>Turns out simply <code>api.model.validate()</code> is enough.</p> <pre class="lang-py prettyprint-override"><code>payload = json.loads(request.form['params']) my_model.validate(payload) </code></pre>
python|flask|flask-restplus
0
7,504
67,810,698
I hit a regex roadblock while exploring a dataset of exported WhatsApp chats
<p>I'm creating a dataset of exported WhatsApp chats. To manipulate the data, I need to split each line of the chat log into <code>date</code>, <code>time</code>, <code>sender</code> and <code>message</code> (columns).</p> <pre><code>import pandas as pd import re column_names = [&quot;date&quot;, &quot;time&quot;, &qu...
<p>Instead of using split, you might match all the different parts in 4 capture groups.</p> <pre><code>^(\d{2}/\d{2}/\d{4}), (\d{2}:\d{2}) - ([^:]+):\s*(.+) </code></pre> <ul> <li><code>^</code> start of string</li> <li><code>(\d{2}/\d{2}/\d{4})</code> Capture <strong>group 1</strong> Match a date like format <em>(whic...
python|regex|pandas|dataset|data-science
0
7,505
66,760,787
Cannot import personal python module (installed with pip -e) from outside the module's directory
<p>I am developing a package for internal use, and said package has a <code>setup.py</code> file (see below). I am a bit baffled because when I install my package (inside an environment &amp; in editable mode so changes get reflected as I develop it), the import works if I am in the development directory, but says &quo...
<p>You need to add where you have your module to the system path</p> <pre><code>import sys sys.path.append(yourPathHere) import yourModule </code></pre> <p>Edit - for clarity - the above goes into the .py that calls your module, not the setup.py that you use for compiling it.</p> <p>Huh - I see your environment does s...
python|pip
-1
7,506
50,472,108
How to set random_state in networkx graph with holoviews/bokeh?
<p>I would like to generate reproducible plots. With <code>networkx</code> is possible to pass the random state to the layout. That is to ensure the plot is the same. When doing the same with holoviews I am getting an error. </p> <pre><code>%pylab inline import pandas as pd import networkx as nx import holoviews as h...
<p>The first issue is that the <code>Graph.from_networkx</code> method accepts the layout function not the dictionary that is output by that function. If you want to pass arguments to the function you can do so as keyword argument, e.g.:</p> <pre><code>hv.Graph.from_networkx(G, nx.layout.spring_layout, random_state=42...
python|networkx|bokeh|holoviews
0
7,507
44,977,300
How can I make Flask work with Python 3?
<p>I have written an API in my personal machine and I want to make it run on a remote machine.</p> <p>I have used Python 3 and flask with Pycharmm without any problems in my own machine. However I connect the remote machine using ssh. So it's impossible to configure environment with an IDE.</p> <p>When I type <code>f...
<p>Try <code>pip3 install flask</code>. Ideally you should be doing this in a <code>virtual environment</code>. Also, you might want to look at <code>dockerizing</code> your code since it will help reduce conflict between different <code>python</code> versions.</p> <blockquote> <p>As an addition I have installed the...
python|python-2.7|python-3.x|rest|flask
2
7,508
61,360,286
python pandas normalize column with keras, then splitting to groups
<p>Having the following data frame (actual data frame contains multiple strings and numeric columns):</p> <pre><code>col1 col2 0 A 10 1 A 10 2 B 5 3 B 5 </code></pre> <p>I want to normalize the data based on column values so the result would look like this:</p> <pre><code> col1 col2 0 A ...
<p>When dealing with categorical data, you should be looking at encoding methods such as a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow noreferrer"><code>OneHotEncoder</code></a>. It doesn't make sense to try to normalize these columns directly. In t...
python|pandas|keras
1
7,509
61,427,400
value error in combining csvs using python
<p>Python Newbie here, First time poster:</p> <p>Attempting to combine csvs. I have put all the files in one folder. Attempting to combine them into 1 csv.</p> <pre><code>from os import chdir from glob import glob import pandas as pdlib # Produce a single CSV after combining all files def produceOneCSV(list_of_files...
<p>You are using file_pattern = ".csv" and then putting another dot(.) in glob('*.{}'.format(file_pattern))</p> <p>So, your program is searching for files with format ..csv which obviously don't exist.</p> <p>To fix it, you can do one of the following</p> <p>1.) Change file_pattern to "csv" (without dot) OR<br> 2.) ...
python|pandas
1
7,510
57,965,606
How to fill in HTML input fields on website using Python
<p>I'm trying to create a program that will input a generated string into a field on a website. However, the input I am trying to put in isn't a form, simply a text box that leads into a JavaScript Script.</p> <p><strong><a href="https://support.logi.com/hc/en-us/requests/new?ticket_form_id=360000621393" rel="nofollow...
<p>To interact with webpages and insert text, consider using <a href="https://selenium-python.readthedocs.io/api.html" rel="nofollow noreferrer">Selenium WebDriver</a>.</p> <p>In addition to installing <code>selenium</code>, you will also need to download a WebDriver binary. For example, the Google Chrome driver is av...
python|python-3.x|beautifulsoup|python-requests|urllib
0
7,511
55,524,577
A methods modifying a database is making a method to remove a row from the database not function
<p>I'm building an election database for university using flask and html for the ui. I have a page listing my candidates and their parties with a field to change the party and a button that should remove the candidate altogether. When I click the remove button, it changes the party to "None".</p> <p>The thing is, when...
<p>Looks like both your candidate_remove and candidate_set_party functions are registered to the same routes and methods.</p> <p>They need to have unique routes. I'll provide an example, in case I'm not being clear.</p> <pre class="lang-py prettyprint-override"><code>@app.route("/set-party/&lt;candidate_id&gt;/", met...
python|html|flask
0
7,512
54,082,208
Access property in Pypi ics
<p>When using the ics library found <a href="https://pypi.org/project/ics/" rel="nofollow noreferrer">here</a> I run into a problem I can't figure out. When accessing a index i.e. cal.events[9].name I can access the information. When I run over that events list I can't access the information and I get this error: Attri...
<p>I'm not familiar with that specific library, but it looks like you meant to iterate over <code>cal.events</code> instead of <code>cal</code>:</p> <pre><code>for event in cal.events: print(event.name) </code></pre>
python|list|icalendar|pypi
2
7,513
49,707,951
How to create a GUI with scroll-able text widgets
<p>I want to create the main window with a horizontal scroll bar at the bottom.</p> <p>This main window then should contain an uncertain number of smaller text widgets with vertical scrollbars.</p> <p>The code below packs 10 scrolled text widgets into a larger text widget. </p> <p>My problem is "attempt one" used <c...
<p>Take a look at this example:</p> <pre><code>import tkinter as tk import tkinter.scrolledtext as St class Example(tk.Frame): def __init__(self, root): tk.Frame.__init__(self, root) self.pack(side="top", fill="both", expand=True) self.canvas = tk.Canvas(self, borderwidth=0) self.h...
python|tkinter
1
7,514
45,901,732
" could not find or load spatialindex_c.dll" in windows?
<p>system:windows</p> <p>versions:python 3.6</p> <p>I successfully install osmnx and Rtree. But still have error. </p> <p>My code:</p> <pre><code>&gt; import osmnx as ox &gt; from Ipython.display import Image &gt; ox.config(log_file=True,log_console=True,use_cache=True) &gt; &gt; img_folder='image'; extension='pn...
<p>I had the same problem <code>“could not find or load spatialindex_c.dll”</code>.</p> <p>What solved for me was <code>pip uninstall rtree</code>. That's it. I am using <code>conda</code> environment in a Windows 7 server without admin.</p> <p>Both <code>osmnx</code> and <code>geopandas</code> are present in my <co...
python|dll
15
7,515
45,736,234
Understanding syntax of expression >>> new = [int(i) for i in old.split(' ')]
<p>I'm a bit confused with the following code, in terms of combining both list comprehension and type conversion.</p> <pre><code># Statement 1 list1 = input('enter 10 integers separated by spaces: ') # type(list1) --&gt; str # Statement 2 list2 = [int(i) for i in list1.split(' ')] # type(list2) --&gt; lst </code></pr...
<p><code>result = [f(x) for x in sequence]</code> can be perceived as a short form of the following:</p> <pre><code>result = [] for x in sequence: # for each element: take it, name it x and do the following result.append(f(x)) </code></pre> <p>(Strictly speaking, these forms may behave differently if some call o...
python|type-conversion|list-comprehension
3
7,516
40,873,464
FLASK, one html with long input forms into two or more divided htmls
<p>I am using SqlAlchemy and FLASK to build a web interface that contains more than 50 user input fields. All the data should enter the database at the same time. Currently every input fields are in one html page(you have to scroll down pretty hard), to minimize this scrolling and for better compartmentalization, I wou...
<p>please follow the link for pagination <a href="http://flask.pocoo.org/snippets/44/" rel="nofollow noreferrer">http://flask.pocoo.org/snippets/44/</a> if you don't want to use javascript to create views.</p>
python|html|flask
0
7,517
40,076,616
iPython magic for Zipline cannot find data bundle
<p>I have a Python 2.7 script that runs Zipline fine on the command prompt, using <code>--bundle=myBundle</code> to load the custom data bundle <code>myBundle</code> which I have registered using <code>extension.py</code>.</p> <pre><code>zipline run -f myAlgo.py --bundle=myBundle --start 2016-6-1 --end 2016-7-1 --data...
<p>It is a known (now closed) bug in zipline, see also <a href="https://github.com/quantopian/zipline/issues/1542" rel="nofollow">https://github.com/quantopian/zipline/issues/1542</a>.</p> <p>As a workaround you can load the following in the cell before the zipline magic:</p> <pre><code>import os from zipline.utils....
python|python-2.7|ipython|zipline
1
7,518
47,853,801
SimpleITK, read metadata without loading image array
<p>I'm using SimpleITK to read MetaImage data.</p> <p>Sometimes I need to access only the metadata (which is stored in a key=value .mhd file) but the only way I found to do it is to call <code>ReadImage</code> which is pretty slow as it loads the whole array into memory.</p> <pre><code>import SimpleITK as sitk mhd =...
<p>ITK itself does support this feature, but SimpleITK does not.</p> <p>Please create a feature request with the project: <a href="https://github.com/SimpleITK/SimpleITK/issues" rel="nofollow noreferrer">https://github.com/SimpleITK/SimpleITK/issues</a></p> <p>UPDATE:</p> <p>This new feature has been added to the Si...
python|medical|simpleitk
6
7,519
34,191,312
Calling a function multiple times with return value
<pre><code>from graphics import * def draw(): returnStuff = {'again' : 0, '1st' : 1 } draw.again = False win = GraphWin("Quadrilateral Maker", 600, 600) win.setBackground("yellow") text = Text(Point(150, 15), 'Click 4 points to create a Quadrilateral') text.draw(win) #gets the 4 points ...
<p>I think you need a while...</p> <pre><code>while count==1 or returnValue['again'] == 1: returnValue = draw() </code></pre>
function|python-3.x|dictionary|return-value|zelle-graphics
0
7,520
47,125,466
Issues when processing json data
<p>Currently, when the input is a company, such as LinkedIn, the code is working perfectly and gives back the proper message. Email input is not working at all. Any suggestions? The current code is as follows:</p> <pre><code>import urllib import json userInput = input('Do you want to find an email (E) or company (C)?...
<p>I dont see a break; for example :</p> <pre><code>while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again...") </code></pre> <p>You could btw check this doc if you want to do it another way. Depends o...
python|json|python-3.x|urllib
0
7,521
47,022,674
with respect to the usage of tf.summary.scalar
<p>I am studying a Tensorflow implementation, which includes the following code segment. I am not quite understand what does <code>tf.summary.scalar</code> try to achieve. My understanding is that <code>"queue/%s/fraction_of_%d_full" % (q.name + "_" + phase, capacity)</code> should be a name, but what does this name lo...
<p>This <a href="https://www.tensorflow.org/api_docs/python/tf/summary/scalar" rel="nofollow noreferrer"><code>tf.summary.scalar</code></a> call will output the queue size (relative to the capacity) to the tensorboard, as it changes during the session.</p> <p>The scalar will be visible by the name matching this patter...
python|machine-learning|tensorflow|tensorboard
2
7,522
43,186,412
Is it possible access an attribute of another model via queryset?
<p>I need to display in a page a list with the candidates for their respective averages, the candidates' scores for the calculation of the average are in another model (Evaluation), this model receives an attribute score that contains the note of that evaluation that the candidate received and a foreign key with the ca...
<p>You can do</p> <pre><code>from django.db.models import Avg candidate = get_object_or_404(Candidate, pk=pk) average = Evaluation.objects.filter(candidate= candidate).aggregate(Avg('score'))['score__avg'] </code></pre>
python|django|django-models|django-views
1
7,523
69,776,280
Converting PDF to PNG with ImageMagick & Wand via Python
<p>I am using ImageMagick to convert a PDF into an image.. it works great when I try: <code>convert -density 150 -trim summary-reports/20211027 -quality 100 -flatten -sharpen 0x1.0 output/20211027.png</code></p> <p>So as far as I can tell, GS is working.</p> <p>I am trying to do this with a script:</p> <pre><code>impo...
<p>Looks like this worked...</p> <pre><code>import os from os.path import exists from wand.image import Image from wand.color import Color filein = &quot;summary-reports/20211027&quot; fileout = &quot;output/20211027.png&quot; with Image(filename=f&quot;{filein}[0]&quot;, resolution=150) as img: format = ...
python|imagemagick-convert|wand
0
7,524
70,006,052
Splitting single row to multiple unique rows Pandas Permutations
<p>I have a problem where I have to split one row into 8 combinations of rows.</p> <p>Example I have 8 columns -- first 6 belonging to each face of coin. and last two any dummy columns. As shown below(this is the old df)</p> <pre><code>Date, Coin1_Face_1, Coin1_Face_2, Coin2_Face_1, Coin2_Face_2, Coin3_Face_1, Coin3_Fa...
<p>Try using <code>pd.wide_to_long</code> and I am not sure about your row expansion, you either have to many or to few rows in your expected output. Please explain how to expand.</p> <pre><code>pd.wide_to_long(df,['Coin1', 'Coin2', 'Coin3'], ['Date', 'Random1', 'Random2'], 'j', '_', '.*').reset_index() </code></pre> ...
python|pandas
1
7,525
66,429,477
how can i solve the following problem in my code?
<p>I want two images to be displayed to the user next to each other and the user selects one of them. code:</p> <pre><code>img1=cv2.imread(&quot;F:/ML_991_Final/Dataset/1/1-1/bee.jpg&quot;,cv2.COLOR_BGR2RGB) img2=cv2.imread(&quot;F:/ML_991_Final/Dataset/1/1-1/parrots.jpg&quot;,cv2.COLOR_BGR2RGB) new_img = cv2.hconcat([...
<p>Your flags are wrong on <code>cv2.imread()</code>. You need to use something more akin to</p> <pre><code>im = cv2.imread('...', cv2.IMREAD_COLOR) </code></pre> <p>The flags you are using are for:</p> <pre><code>cv2.cvtColor() </code></pre>
python|opencv
3
7,526
64,771,546
Unexpected behaviour of hash function when using set in a class
<p>I have 2 classes down below. Since only hashable objects could be stored in sets I define <strong>hash</strong> function for class Person. Everytime I add Person to group object <strong>hash</strong> function is called and generates hash using name only. Could someone explain to me, why when I add a p2 object with t...
<p>From the <a href="https://docs.python.org/3/reference/datamodel.html#object.__hash__" rel="nofollow noreferrer">docs of <code>__hash__</code></a>:</p> <blockquote> <p><strong>If a class does not define an <code>__eq__()</code> method it should not define a <code>__hash__()</code> operation either</strong>; if it def...
python-3.x|hash|set
0
7,527
64,985,537
How can i override the save() method in admin page
<p>It maybe look like a simple question, but i been struggling for weeks now, I want to override the save method in admin page, for a model name <code>Transaction</code> that I created, I want to <code>pre_save</code> each transaction by groups.</p> <p>Lets say for example I have created 2 groups (Test1, Test2) and I a...
<p>Instead of overriding, you could use a decorator:</p> <pre><code>def hello(function): function() print('hello') @hello def dog(): print('woof!') </code></pre> <p>It's like running <code>hello(dog)</code>. Running this script prints:</p> <pre><code>woof! hello </code></pre> <p>So instead of <code>hello</code>,...
python|django|admin
0
7,528
53,089,845
Sort several lists based on first lists order by maximum
<p>How would I sort several other lists on the new order of a list. Example:</p> <pre><code>lst1=[3,5,1,7] lst2= [1,2,3,4] lst3=[100,99,98,97] lst4 = [20,17,192,309] list1_set=list(sorted((set(lst1)))) list1_set.reverse() #gives me lst1=[7,5,3,1] </code></pre> <p>Now I would like the other lists to sort in the same ...
<p>Create the relevant indices <code>idx</code> and then just use getitem/list comprehensions:</p> <pre><code>&gt;&gt;&gt; idx = sorted(range(len(lst1)), key=lst1.__getitem__, reverse=True) &gt;&gt;&gt; [lst2[i] for i in idx] [4, 2, 1, 3] &gt;&gt;&gt; [lst3[i] for i in idx] [97, 99, 100, 98] &gt;&gt;&gt; [lst4[i] for ...
python|list|sorting
4
7,529
68,571,715
In Blender, how do I programmatically display a viewport rendering in a window just like if you pressed F12?
<p>I know I can call <code>bpy.ops.render.opengl()</code> and that will create the render, but what I want to do is to create and then view the render, just like what happens when you use the <strong>View &gt; Viewport Render Image</strong> menu item. Is there a way to do this?</p>
<p>I think that what you are looking for is:</p> <pre><code>bpy.ops.render.opengl('INVOKE_DEFAULT') </code></pre> <p>It will display the render on a new window.</p>
python|blender
1
7,530
10,290,074
can httplib (python) interact with a page and its javascript?
<p>I want to write a python script that will ask for reddit post url, go to the page, login with a specified account and upvote the post and the logout. </p> <p>A) can this be done with python? </p> <p>B) How would I do this? If you can provide code that would be great, but don't kill yourself. </p>
<p>Do you really need to interact with JavaScript?</p> <p>You can reverse engineer Reddit code by looking at AJAX requests made using Firebug or any other debugger, checking cookies, request parameters, etc. </p> <p>After this you can simulate this requests using Python's urllib by setting same request type (GET vs P...
javascript|python|web|httplib
2
7,531
4,846,509
Assign value to a string that is the same as a variable name in Python
<p>Suppose I have,</p> <pre><code>class example(object) def __init__(var1 = 10, var2 = 15, var3 = 5) do a few things here Other methods here </code></pre> <p>There are other classes which are not relevant for the question. </p> <p>To study the behavior of the system, I vary the inputs in the <code>...
<p>If I understand you correctly, you want to specify the name of the parameter that should be set dynamically. You can use <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow"><em>dictionary unpacking</em></a>:</p> <pre><code>example_instance = example(**{var_under_study:...
python|string|variables
3
7,532
5,533,154
question about filtering a dictionary using a list in python
<p>with the following dictionary and array:</p> <pre> a = { 'a':[1,2,3,4,5], 'b':[1,2,3], 'c':[1,2,3,4,5] } b = ['a','c'] </pre> <p>I would like to filter a into a new dictionary to only have the key-values in the array b so i end up with:</p> <pre> c = {'a': [1, 2, 3, 4, 5], 'c': [1, 2, 3, 4, 5]} </pre> <p>So.. th...
<p>The built-in <code>map()</code> can always be substituted by a list comprehension. The call</p> <pre><code>map(callable, iterable) </code></pre> <p>is equivalent to</p> <pre><code>[callable(x) for x in iterable] </code></pre> <p>If <code>callable</code> is a lambda-expression, the latter form is faster and more...
python
4
7,533
62,669,891
CPU Temperature in Python 3 (Linux & Windows)
<p>I'm looking to get the CPU Temperature in Python 3. Can be different lib's but I need one for Linux &amp; Windows.</p> <p>psutil.sensors_temperature only seems to work on Python 2. I haven't been able to find any other suitable alternatives.</p>
<p>You can install <code>psutil</code> in python3 using <code>pip</code>. On Ubuntu, you might need the <code>python-dev</code> packages for some header files required by <code>psutil</code>. You might also need to use <code>pip3</code> instead of <code>pip</code>.</p> <pre><code>Python 3.8.3 (default, May 17 2020, 18:...
python|python-3.x
0
7,534
61,727,662
python for loop wont change value
<p>So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code</p> <pre><code>for c in range(0,20): print("number",c+1) number = input ("Enter number:\n") number = int(number) if (number &lt; 1 or number &gt; 9): print("try again b...
<p>First, do not use range(0,20) but range(20) instead.</p> <p>Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to...
python|for-loop
1
7,535
61,970,975
How do you fix the “element not interactable” exception in selenium?
<p>Disclaimer: I found other issues related to this but no solution worked. When clicking on a button with selenium on python, I get this error:</p> <pre><code>selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable (Session info: chrome=83.0.4103.61) </code></pre> <p>Up until ...
<p>This is happening for different reasons, try the following: 1- Make sure the element is visible in the viewport. 2- Make sure that there is no element with z-index higher than the target element. 3- Make sure that there is no Tippy menu or flyout menu displayed over it. 4- Make sure that there is no Hidden/Glass el...
python-3.x|selenium|selenium-webdriver|webdriver|selenium-chromedriver
0
7,536
71,336,573
JMeter - Error when using Jython/Python Engine in JSR223 Sampler "Cannot find Engine"
<p>Using <a href="https://stackoverflow.com/questions/60450291/how-to-call-a-py-file-to-execute-using-jmeter/60486183#60486183">this SO question</a>, I created a test plan to call a python script.</p> <p>I ran the script with the Log Viewer open.</p> <p>The JMeter log says:</p> <pre><code>2022-03-03 13:44:32,118 ERROR ...
<ol> <li><p>It might be the problem with your <code>jython.jar</code> file, try downloading i.e. <a href="https://repo1.maven.org/maven2/org/python/jython-standalone/2.7.2/jython-standalone-2.7.2.jar" rel="nofollow noreferrer"><code>jython-standalone-2.7.2.jar</code></a> library to &quot;lib&quot; folder of your JMeter...
python|jmeter|jmeter-plugins|jsr223
0
7,537
11,410,896
How json dumps None to empty string
<p>I want Python's <code>None</code> to be encoded in json as empty string how? Below is the default behavior of <code>json.dumps</code>.</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '[&quot;foo&quot;, {&quot;bar&quot;: [&quot;baz&quot;, null, 1.0, 2]}]' </cod...
<p>In the object you're encoding, use an empty string instead of a <code>None</code>.</p> <p>Here's an untested function that walks through a series of nested dictionaries to change all <code>None</code> values to <code>''</code>. Adding support for lists and tuples is left as an exercise to the reader. :)</p> <pre><...
python|json
10
7,538
11,040,461
regex to extract a set number of words around a matched word
<p>I was looking around for a way to grab words around a found match, but they were much too complicated for my case. All I need is a regex statement to grab, lets say 10, words before and after a matched word. Would anybody be able to help me set up a pattern to do that?</p> <p>For example, let's take the sentence (w...
<p>Here's a likely definition of "word": A string of non-space characters. Here's another: A string of letters and digits, but no punctuation. Python has convenient shortcuts for both.</p> <p><code>\w</code> is any "word" character with the second meaning (letters and digits), and <code>\W</code> is any <em>other</em>...
python|regex|django
1
7,539
55,768,881
RecursionError when trying to mock an iterable with an __iter__ method that returns self
<p>For the purpose of a unit test, I made a class whose instance is an iterable that would yield a certain sequence and then raise an exception:</p> <pre><code>class Iter: def __init__(self, seq): self.seq = seq self.pos = 0 def __next__(self): if self.pos == len(self.seq): ...
<p>I agree that this is indeed a bug. Although this is an edge case.</p> <p>As we can see in the source code. <code>mock</code> module expects that <code>iter(ret_val)</code> will return the unchanged iterator if <code>ret_val</code> has already been an iterator.</p> <p>Well, it actually does but still needs to call ...
python|python-3.x|python-mock
1
7,540
56,703,459
'numpy.ndarray' object has no attribute 'columns'
<p>I am trying to find out the feature importance for Random Forest Classification Task. But it gives me following error :</p> <blockquote> <p>'numpy.ndarray' object has no attribute 'columns'</p> </blockquote> <p>Here is a portion of my code :</p> <pre><code>import pandas as pd import numpy as np import matplotli...
<p>Use this:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing dataset dataset=pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:,3:12].values Y = dataset.iloc[:,13].values #spliting dataset into test set and train set from sklearn.model_select...
python|pandas|scikit-learn|random-forest
1
7,541
69,696,232
Insert one-hot along with other data types
<p>I have data with attributes of numerical and categorical types in one row. Numerical values after normalization will be in the range of 0 - 1, float type. There are also some continuous data, also float type. How can I insert both <strong>float</strong> and <strong>one-hot-vector</strong> (categorical) data into som...
<p>You can use Get Dummies or Categorical Codes.</p> <pre><code>import pandas as pd # Intitialise data of lists data = [{'Year': 2020, 'Airport':2000, 'Casino':5000, 'Stadium':9000, 'Size':'Small'}, {'Year': 2019, 'Airport':3000, 'Casino':4000, 'Stadium':12000, 'Size':'Medium'}, {'Year': 2018, 'Airport...
python|machine-learning|keras|one-hot-encoding
0
7,542
69,752,659
Removing tags from a selected number by iterating using beautifulsoup
<p>I am trying to clean html data using beautiful soup. I want to remove a set of tags along with the data associated in that tags which are consescutive starting from <code>et_pb_row_inner et_pb_row_inner_2</code> to <code>et_pb_row_inner et_pb_row_inner_22</code> .</p> <p><a href="https://i.stack.imgur.com/RQD6C.png"...
<p>You could use a regex to find all the <code>&lt;div&gt;</code> tags that have those attributes and end in 2 or higher.</p> <p>So basically the regex <code>r'et_pb_row_inner et_pb_row_inner_([2-9]|[\d]{2,}).*'</code> is saying find all the <code>et_pb_row_inner et_pb_row_inner_</code> that end in a single digit of 2 ...
python|web-scraping|beautifulsoup
1
7,543
17,690,060
Setting up Emacs24 for python development
<p>I want to configure Emacs24 for python development. So far I've fallowed the instructions in <a href="http://www.yilmazhuseyin.com/blog/dev/emacs-setup-python-development/" rel="nofollow">this blog post</a> and done all the steps successfully, but nothing happened when I reopened Emacs. It's maybe because the blog p...
<p>It's probably best to install things from one of the repositories. <code>pymacs</code> and <code>pyflakes</code> are both in MELPA. This repo also has the <code>flymake-python-pyflakes</code> - which is kind of an extension of the snippet in the blog post.</p> <p>You will probably have very little use for <code>rop...
python|emacs|emacs24
4
7,544
66,145,373
How to use sqlite across multiple (spawned) python processes via sqlalchemy
<p>I have a file called db.py with the following code:</p> <pre><code>from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine('sqlite:///my_db.sqlite') session = scoped_session(sessionmaker(bind=engine,autoflush=True)) </code></pre> <p>I am trying to import ...
<p>The problem isn't about thread-local sessions, it's that the original connection object is in a different thread to those sessions. SQLite disables using a connection across different threads by default.</p> <p>The simplest answer to your question is to turn off sqlite's <a href="https://docs.python.org/3/library/sq...
python|python-3.x|sqlite|sqlalchemy|flask-sqlalchemy
1
7,545
66,280,024
django use 2 different databases
<p>I want to use django to make a dashboard. The thing is, I want to have one DB for data (that will be displayed on the dashboard) and one DB for Django operations (all the automatic tables Django creates) I saw <a href="https://stackoverflow.com/questions/57676143/using-multiple-databases-with-django">this answer</a>...
<p>The best approach, in this case, is to define multiple databases and use a feature by Django that is called <code>database routing</code></p> <p>Full documentation <a href="https://docs.djangoproject.com/en/3.1/topics/db/multi-db/#automatic-database-routing" rel="nofollow noreferrer">here</a></p> <p>In few words:</p...
python|django
1
7,546
62,364,813
How to change tuple shape?
<p><strong>what should i do so that a tuple of (1,2,3) is changes to ((1,2),3).</strong> I was trying to use the code</p> <pre><code>index_transform = [(lambda (a,b,c) : ((a,b),c)) (x) for x in index] </code></pre> <p>but i was getting error invalid syntax</p>
<pre><code>orig_tup=(1,2,3) ##tuple slicing with square brackets tup_of_tups=(orig_tup[0:2], orig_tup[2:3]) print(tup_of_tups) </code></pre>
python-3.x|data-science|data-analysis
0
7,547
35,666,573
Use tkinter to draw a specific bar chart
<p><a href="https://i.stack.imgur.com/bFlBO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bFlBO.png" alt="enter image description here"></a></p> <p>I am trying to figure out the easiest way to do the bat chart above. I'm learning <code>tkinter</code> and I know that I can use <code>Canvas</code>, ...
<p>Some googling revealed <a href="https://www.daniweb.com/programming/software-development/code/216816/draw-a-bar-graph-python" rel="nofollow noreferrer"><strong>this</strong></a> link to me. </p> <p>I have included the example code given there and I have hopefully commented it enough so you can understand what is go...
python|python-3.x|tkinter
4
7,548
58,850,378
Alternate to apply in pandas
<p>I have a dataframe like this</p> <pre><code>dat = [['ID1', '[1, 0, 1, 0, 0]'], ['ID2', '[0, 0, 1, 0, 0]'], ['ID3', '[1, 0, 1, 1, 0]']] df = pd.DataFrame(dat, columns = ['ID', 'Values']) df ID Values 0 ID1 [1, 0, 1, 0, 0] 1 ID2 [0, 0, 1, 0, 0] 2 ID3 [1, 0, 1, 1, 0] </code></pre> <p>I want to cal...
<p>May be you can consider using a list comprehension rather than <code>apply</code>:</p> <pre><code>df['Cumsum_Values']=[np.cumsum(ast.literal_eval(i)) for i in df['Values']] df['dot']=[np.dot(ast.literal_eval(a),b) for a,b in zip(df['Values'],df['Cumsum_Values'])] </code></pre> <hr> <pre><code> ID Val...
python|pandas|numpy
2
7,549
58,879,665
Reading csv file in pySpark with double quotes and newline character
<p>I am having problems with reading csv files using pySpark. I have three columns with url address, title (string) and full html file. The last field is in quotes "..." and anything quoted inside of it has double quotes e.g "test" -> ""test"" (it also contains newline character as well). I can read this file using pan...
<p>This seems to work:</p> <pre><code>df = (spark.read .option("multiline", "true") .option("quote", '"') .option("header", "true") .option("escape", "\\") .option("escape", '"') .csv('path_to_file') ) </code></pre> <p>Tested with <code>scala_2.11.0</code> and <code>spark_2.3.4_had...
python|apache-spark|pyspark
10
7,550
59,009,477
How to group Wireshark TCP packets per flow using Python
<p>I captured tcp data in Wireshark and export the data to csv and now I am trying to group the tcp packets per flow, using python but I'm not sure how to do it.</p> <p>if Source, Src Port, Destination, Dest Port is the same across the row forward and backward it's considered apart of the same flow i.e. A->B and B->A<...
<p>I would recommend to export the data from wireshark to .json format, there is a better way to group tcp session using information that isn't exported to the csv format. In order to do make a json file from your pcap do: File->Export Packet Dissection->AS JSON...</p> <p>After you do so, you can look at the field <co...
python|tcp|wireshark|packet|tcpdump
1
7,551
31,270,488
Navigating JSON in Python?
<p><strong>ANSWER:</strong> The square brackets inside data["data"]["items"] indicates a list of dictionaries. I had thought that the brackets indicated that all of those dictionaries were a list <em>inside</em> a list of one item (i.e. [[item1, item2]]) so I had to call a 0 index like so: data["data"]["items"][0]. Tha...
<p>By doing some basic debugging and data examination you will find that the use of the [0] is incorrect </p> <p>I quickly loaded that data and tried it </p> <pre><code>In [11]: for i in x['data']['items'][0]: ....: print i ....: time_completed xid details title date shared sub_type time_created time_updated...
python|json|google-app-engine
1
7,552
15,821,054
Why does the Python ** operator behave differently on arrays and scalars
<p>I don't understand the justification for the following behavior of the ** operator in Python. This returns a float:</p> <pre><code>&gt;&gt;&gt; 10**-1 0.1 </code></pre> <p>And this returns integers:</p> <pre><code>&gt;&gt;&gt; y=np.array([10,10,10]) &gt;&gt;&gt; y array([10, 10, 10]) &gt;&gt;&gt; y**-1 array([0,...
<p>For efficiency, numpy arrays are restricted to a specified type, for example with yours:</p> <pre><code>&gt;&gt;&gt; y=np.array([10,10,10]) &gt;&gt;&gt; y.dtype dtype('int64') </code></pre> <p>Because an int can't represent the fractional part, it's discarded. If you use a floating point array like this, the resul...
python
4
7,553
49,340,520
Matplotlib and Networkx - drawing a self loop node
<p>I have this function and I want to draw a self loop. How can I do that?<br> The edge exists but I think it's just a point in this exemple is (1,1) and I couldn't add the name of nodes. My goal is from adjacency matrix draw a graph. Is there there is better way to do this? </p> <pre><code>import networkx as nx impo...
<p>It seems that your approach is quite advanced a use of matplotlib, but I would still recommend using a specialized graph plotting library (<a href="https://networkx.github.io/documentation/networkx-1.11/reference/drawing.html" rel="nofollow noreferrer">as does the networkx documentation</a>). As graphs get bigger, ...
python|matplotlib|graph|draw|networkx
9
7,554
49,081,114
Assigning (yield) to a variable
<p>First of all, I'd like to mention that I am not particularly familiar with Python. I have recently been forced to familiarise myself with a code sample that's left my jaws ajar, and I have been unable to "translate" it. The various documents and articles I've taken a look at have not helped either:</p> <ul> <li><a ...
<p>The syntax <code>variable = (yield some_value)</code> in a generator does the following:</p> <ul> <li>it returns <code>some_value</code> to the code that invoked it (via <code>next</code> or <code>send</code>);</li> <li>when it is next invoked (via <code>.next</code> or <code>.send(another_value)</code>) it assigns...
python|yield
15
7,555
59,935,639
pygame get key pressed as a string
<p>I want to change the text in the controls screen based on the key which the user presses. how do I convert <code>pygame.event.get()</code> into a string that shows which key has been pressed?</p> <p>preferably without many if staments</p> <pre class="lang-py prettyprint-override"><code>for event in pygame.event.ge...
<p>The code of the pressed can be get by the <code>event.key</code> attribute. The unicode representation for the key can be get by the <code>event.unicode</code> attribute. See <a href="https://www.pygame.org/docs/ref/event.html" rel="nofollow noreferrer"><code>pygame.event</code></a> module.</p> <p>A unser friendly...
python|pygame
4
7,556
6,101,415
PyGTK blocking non-GUI threads
<p>I want to play with the thread-bugs with PyGTK. I have this code so far:</p> <pre><code>#!/usr/bin/python import pygtk pygtk.require('2.0') import gtk import threading from time import sleep class SomeNonGUIThread(threading.Thread): def __init__(self, tid): super(SomeNonGUIThread, self).__init__() ...
<p>You have to call <code>gobject.threads_init()</code> before you do anything Gtk related.</p> <p><a href="http://faq.pygtk.org/index.py?file=faq20.006.htp&amp;req=show" rel="noreferrer">More info in PyGtk's FAQ</a></p>
python|multithreading|pygtk
5
7,557
6,281,633
How to append and uniqify a tuple
<pre><code>d1 = ({'x':1, 'y':2}, {'x':3, 'y':4}) d2 = ({'x':1, 'y':2}, {'x':5, 'y':6}, {'x':1, 'y':6, 'z':7}) </code></pre> <p>I have two tuple <code>d1</code> and <code>d2</code>. I know tuples are <code>immutable</code>. So I have to append another tuple using list. Is there any better solution.</p> <p>Next questio...
<p>Tuples are generally for data where the number of items is fixed and each place has its own "meaning", so things like sorting, appending, and removing duplicates will never be very natural on tuples and weren't designed to be. If you're stuck with tuples, converting to a list, doing these operations, then converting...
python
2
7,558
66,860,747
FLASK uploads broken image
<p>I am trying to upload pictures and display it in a URL.</p> <p>my server:</p> <pre><code>app = Flask(__name__) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/post_pic',methods=['POST','GET']) def...
<p>Usually, a web server will handle a load of content (nginx). If you are trying to save content then the best option is to save them somewhere in a location and use the <a href="https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_from_directory" rel="nofollow noreferrer">send_from_directory</a> with a get imag...
python|flask
1
7,559
67,014,075
Scrapy Returns 'None' after the 10th row in table
<p>I've tried many different xpath expressions but can't quite get this to work. Basically, I will get the text for the first 10 rows in a table, then 'None' for the following 90. If I do a different xpath expression (one that was suggested to me but I personally don't fully understand), it gives me the last 90 but not...
<p>Jacob,</p> <p>as a matter of fact, the solution is at your hands already.</p> <p>You have the xpath expressions for the first ten rows, as well as for the subsequent ninety. All you need to do is to combine them.</p> <p>I suggest that you try the pipe <code>|</code>, which serves as a union operator.</p> <p>The whol...
python|web-scraping|xpath|scrapy
0
7,560
63,930,664
legends not print fully when multiple plots are plotted on same figure
<p>I have the code as below to plot multiple plots on the same figure</p> <pre><code>fig, ax = plt.subplots(figsize=(25, 10)) def wl_ratioplot(wavelength1,wavelength2, dataframe, x1=0.1,x2=1.5,y1=-500,y2=25000): a=dataframe[['asphalt_index','layer_thickness',wavelength1,wavelength2]].copy() sns.scatterplot(x=a[...
<p>every time you call the function wl_ratioplot the legend is being reset the final value. use a array to store all the legends then access it all through a loop.</p> <pre><code>ax.legend([leg]) #it is resetting the legend after each call. </code></pre> <p>use a legends = [];</p> <pre><code>legends.append([leg]) </cod...
python|matplotlib|legend
2
7,561
63,861,546
Deep learning model not giving predictions as input layer is incompatible
<p>bELOW IS A SIMPLE MODEL FOR IMAGE CLASSIFICATION OF HAND GESTURE RECOGNITION using Kaggle <a href="https://www.kaggle.com/gti-upm/leapgestrecog" rel="nofollow noreferrer">dataset</a> # -<em>- coding: utf-8 -</em>- &quot;&quot;&quot;kaggle_dataset_code.ipynb</p> <pre><code>Automatically generated by Colaboratory. Or...
<p>As <a href="https://stackoverflow.com/users/349130/dr-snoopy">Dr. Snoopy</a> suggested, the model is trained on Grey scale images, but you are trying to predict on RGB image. Kindly use the grey scale version of the image.</p> <p>Coming to your next question regarding the predictions, the last layer of your model is...
python|numpy|tensorflow|keras|input
0
7,562
66,646,994
Keep track of two loops at the same time
<p>I want to simulate a race between a rabbit and a fox.<br /> Say that I have two lists with different length: a = [1,2,3,4,5,&quot;rabbit&quot;, 7,8] and b = [1,2,3,4, &quot;fox&quot;,5]. When I loop over list b and fox &quot;breaks&quot; before rabbit - then the fox wins the race.</p> <p>Example:</p> <pre><code>for ...
<p>It can be done in one line:</p> <pre><code>'rabbit' if min([index for index, x in enumerate(a) if x == 'rabbit']) &lt; min([index for index, x in enumerate(b) if x == 'fox']) else 'fox' </code></pre> <p>But @HenriChab's answer is much more readable IMO.</p>
python|for-loop|break
0
7,563
72,155,373
how to put web scraped data into a list
<p>this is the code I used to get the data from a website with all the wordle possible words, im trying to put them in a list so I can create a wordle clone but I get a weird output when I do this. please help</p> <pre><code>import requests from bs4 import BeautifulSoup url = &quot;https://raw.githubusercontent.com/t...
<p>It do not need <code>BeautifulSoup</code>, simply split the text of the response:</p> <pre><code>import requests url = &quot;https://raw.githubusercontent.com/tabatkins/wordle-list/main/words&quot; requests.get(url).text.split() </code></pre> <p>Or if you like to do it wit <code>BeautifulSoup</code> anyway:</p> <pr...
python|beautifulsoup
1
7,564
72,198,544
How to extract data from an api using python and convert it into a pandas data frame
<p>I want to load the data from an API into a pandas data frame. How may I do that? The following is my code snippet:</p> <pre><code>import requests import json response_API = requests.get('https://data.spiceai.io/eth/v0.1/gasfees?period=1d') #print(response_API.status_code) data = response_API.text parse_json = json.l...
<p>Almost there, the json is clean you can directly input it to a dataframe :</p> <pre><code>response_API = requests.get('https://data.spiceai.io/eth/v0.1/gasfees?period=1d') data = response_API.json() df = pd.DataFrame(data) </code></pre>
python|pandas|api
1
7,565
50,969,581
Python - How Do I Make Relative Imports Compatible with Nose
<p>I am working on a package which has a folder structure like:</p> <pre><code>Root |---Source |---Testing |---Test_Utils |---test_fixtures.py |---test_integration.py |---test_unit.py </code></pre> <p>There are a fair amount of relative references flying around (e.g. in test_integratio...
<p><a href="https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH" rel="nofollow noreferrer">PYTHONPATH</a> sets the search path for importing python modules.</p> <p>If you are using (Mac or GNU/Linux distro), add this to your <code>~/.bashrc</code>.</p> <pre><code># add this line to ~/.bashrc export PYTHONP...
python|python-import|nose
0
7,566
50,304,319
How to remove list element using while loop
<p>I open a web page to get the names of the cluster1(p1, p2). I am not sure how many times I need to open a web page to get these cluster1 names. So, I am using a while loop, it will remove the p1 or p2 whichever the value is obtained from web page.</p> <p>When I open a web page, I'll get p1 or p2 and that value will...
<p>It is hard (for me) to understand what happens in the current code, but why not try <code>set</code>s?</p> <pre><code>new = {'some', 'list' 'items', 'p1'} cluster1 ={'p1', 'p2'} in_both = new &amp; cluster1 not_found = cluster1 - new # do stuff with values in `in_both` and `not_found`.... </code></pre>
python-3.x|python-2.7|for-loop|if-statement|while-loop
1
7,567
61,603,947
Misunderstanding the Model-View-Projection matrix in OpenGL
<p>I am attempting to write a basic program in modern OpenGL using Python and pyglet. I am able to place a simple triangle on the screen with different colors for each of the corners. I am at the point where I am attempting to add the projection and view matrix so that I am able to move the "camera" around in 3D spac...
<p>After some more testing I've discovered that the pyrr module seems to be performing matrix multiplication strangely. Pyrr is built on numpy however, so after using:</p> <pre><code>numpy.matmul(projection_matrix, view_matrix) </code></pre> <p>Then, it was able to create the MVP matrix correctly.</p>
python|opengl|matrix
0
7,568
57,758,648
Error using Chatterbot while using a 64-bit system
<p>I' am currently trying to develop a Chatbot using pythons open-source 'chatterbot' library and I have run into an error whilst trying to execute a program.</p> <p>I'm using Python 3.7. on the anaconda terminal i receive the error: </p> <p>OSError: [WinError 193] %1 is not a valid Win32 application</p> <p>after ex...
<p>Windows is complaining that what you're trying to run is not an executable. I suspect that you're trying to run <code>something.py</code> in your terminal. Run <code>python something.py</code> instead to have the Python interpreter run your file.</p>
python|anaconda|64-bit|chatterbot
0
7,569
57,943,000
Django Rest Framework: URL for associated elements
<p>I have the following API endpoints already created and working fine:</p> <p><strong>urls.py:</strong></p> <pre><code>router = DefaultRouter() router.register(r'countries', views.CountriesViewSet, base_name='datapoints') router.register(r'languages', views.LanguageViewSet, base_name...
<p>You can benefit from <a href="https://www.django-rest-framework.org/api-guide/routers/#routing-for-extra-actions" rel="nofollow noreferrer">DRF routers' extra actions capabilities</a> and especially the <code>@action</code> method decorator:</p> <pre><code>from rest_framework.viewsets import ModelViewSet from rest_...
python|django|django-rest-framework
1
7,570
56,122,813
run jupyter notebook using a dynamic name/string from another notebook
<p>One can run a Jupyter notebook from another notebook using the <code>%run</code> magic:</p> <pre><code>%run my_notebook.ipynb </code></pre> <p>However, I have the path and name of the notebook I wish to run in a python variable, <code>notebook_name</code>.</p> <p>Is it possible to run this notebook using the <cod...
<p>You can use <code>$</code> to evaluate Python variables for Jupyter magic functions in general, much like in a shell:</p> <pre><code>%run $notebook_name </code></pre>
python|jupyter-notebook|jupyter
6
7,571
56,365,170
Python - Extract yyyyMMddhhmmss from file using Regex
<p>I am trying to get the date (format is yyyymmddhhmmss) from a string using Regex but I cannot find the pattern to use.</p> <p>I am trying with the code below:</p> <pre><code>import re string = "date file /20190529050003/folder " regex = re.compile(r'\b\d{4}\d{2}\d{2}\s\d{2}\d{2}\d{2}\b') result = regex.findall(str...
<p>If our date is right after the slash, we can simply use this expression:</p> <pre><code>.+\/(\d{4})(\d{2})(\d{2}).+ </code></pre> <p>Then, if necessary, and we wish to add more boundaries, we can surely do so, such as:</p> <pre><code>.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}).+ </code></pre> <h3><a href="htt...
python|regex
4
7,572
18,338,175
filling with zeros the list obtained from a comparison
<p>I have a function that receives 3 lists:</p> <p>doc1:</p> <pre><code>[['ser', 'VSIS3S0', 1], ['francisco_villa', 'NP00000', 2], ['norte', 'NCMS000', 1], ['revolucion_mexicana', 'NP00000', 1], ['nombrar', 'VMP00SM', 1], ['centauro', 'NCMS000', 1]] </code></pre> <p>doc2:</p> <pre><code>[['pintor', 'NCMS000', 1], [...
<p>Given the explanation you gave me in the comments, here is my attempt:</p> <pre class="lang-py prettyprint-override"><code>def vectores(doc1, doc2, consulta): thingies = doc1 + doc2 + consulta result = [0] * len(thingies) for index,value in enumerate([ item[2] for item in doc1 ]): result[index]...
python|list|python-2.7
0
7,573
69,475,881
Piping the output of a multiprocess program into multiple text files
<p>I have written a code that uses the multiprocessor library from python. It runs each script separately using <code>Pool</code>.</p> <pre><code>import os from multiprocessing import Pool process1 = ('myfirstfile.py', 'mysecondfile.py', 'mythirdfile.py', 'myfourthfile.py') def run...
<p>The <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow noreferrer"><code>subprocess</code> module</a> easily allows to capture your output. You can define a separate output file for each script, its filename based on the script name:</p> <pre class="lang-py prettyprint-override"><code>import s...
python-3.x|python-multiprocessing
1
7,574
55,552,298
Choose databits from combobox
<p>I have a simple GUI for serial communication with an Arduino UNO. First I list all databit in an <code>OrderedDict</code>, then I put them in a combobox:</p> <pre><code>self.databits = OrderedDict([ ('5', QtSerialPort.QSerialPort.Data5), ('6', QtSerialPort.QSerialPort.Data6), ('7...
<p>When you add data with <code>addItems()</code> method you only add text, so you will discard the second part. The solution is to iterate and separate each part:</p> <pre><code>databits = [ ('5', QtSerialPort.QSerialPort.Data5), ('6', QtSerialPort.QSerialPort.Data6), ('7', QtSerialPort.QSeria...
python|pyqt|pyqt5|qcombobox|qtserialport
2
7,575
57,672,780
how to use scipy tplquad properly?
<p>I am trying to do some simple triple integrals in physics using scipy's tplquad. As an example, I tried to integrate constant mass density of a unit ball(func d) over the unit cube. This doesn't work. However, if I integrate constant mass density of a unit cube(func f) over the unit cube, I get a result very quickly...
<p>Most numerical integration routines (such as <code>tplquad</code>) approximate the integral by using polynomials. This works well if the function is smooth. Unfortunately, characteristic functions are everything else <em>but</em> smooth since they have a discontinuous boundary. That's why <code>tplquad</code> fails....
python|scipy|numerical-integration
1
7,576
57,422,755
Entering a sequence of notes and have them played
<p>My son and I are trying to write a program that will allow a user to input a sequence of musical notes, and save them into a list to be played back. We've come up with the following:</p> <pre><code>import math #import needed modules import pyaudio #sudo apt-get install python-pyaudio def playnote(char):...
<p>If you are looking for other work for producing music using Python, you might find the following program be a helpful inspiration. It uses the <code>winsound</code> module on Windows to produce beeps of a certain duration and frequency. The program shown below is old and not maintained -- an experiment really but ma...
python|python-3.x|pyaudio
3
7,577
42,553,899
newbie - understanding Django's class-based views dynamic filtering
<p>I'm trying to follow and learning about dynamic filtering in Django from the docs. <a href="https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#dynamic-filtering" rel="nofollow noreferrer">https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#dynamic-filtering<...
<p>Setting <code>context['publisher'] = self.publisher</code> in <code>get_context_data</code> means you can display the publisher's details in the context. For example, you could display the publisher's name above the list of book titles with:</p> <pre><code>&lt;h2&gt;Books published by {{ publisher.name }}&lt;/h2&gt...
python|django|django-class-based-views
1
7,578
42,565,297
Precise loop timing in Python
<p>For <a href="http://www.samplerbox.org" rel="nofollow noreferrer">this project</a> I'm designing a sequencer/drummachine that should be able to send MIDI notes with a precise tempo. Example: 16 notes per 2 seconds (i.e. in music terminology sixteen 1/16-notes per bar at BPM 120), i.e. one note every 125 millisecond...
<p>As I showed <a href="https://stackoverflow.com/a/40496844/3579910">here</a></p> <pre><code>import time def drummer(): counter = 0 # time.sleep(time.time() * 8 % 1 / 8) # enable to sync clock for demo while counter &lt; 60 * 8: counter += 1 print time.time() time.sleep(.125 - time...
python|time|timer
4
7,579
58,602,225
Django urls.py: best way to not have a page number in the url for the first page in a list view?
<p>Right now I have a list view that displays 10 posts per page:</p> <p>The urls would be something like this:</p> <pre><code>www.example.com/posts/1 (First page with 10 results) www.example.com/posts/2 (Next page with 10 results) </code></pre> <p>and my urls.py looks something like this:</p> <pre><code>path('pos...
<p>you can set page a default value.In other worlds,if the class <strong>PostList</strong> don't get parameter <strong>page</strong>,and the value of <strong>page</strong> will be default 1.Hope can help you!</p>
python|html|django
1
7,580
45,555,352
I am trying to create Caesar Ciphers functions in Python, but they seem to work only with lower case letter, how to work with upper case?
<p>I am trying to create Caesar Ciphers functions in Python, but they seem to work only with lower case letter, how to work with upper case?</p> <pre><code>a = dict(zip("abcdefghijklmnopqrstuvwxyz",range(26))) b = dict(zip(range(26),"abcdefghijklmnopqrstuvwxyz")) key = int(input('Enter the key:')) plaintext = (input(...
<p>I believe you need to add the uppercase letters to the dictionary. Otherwise, the program doesn't know what number to map them to. I would recommend setting variable <code>letters = "abcd..."</code> and then adding <code>letters = letters + letters.upper()</code></p> <p>at the beginning of the program.</p> <p>Als...
python|math|caesar-cipher|letter
1
7,581
28,753,614
Check if file exists in list of directories
<p>I have a list of directories, and a file name. I'd like to check if this file name exists in <strong>any</strong> of the directories, if it does exist then the code passes, if not then we'll error out. I'm having some trouble with the next step though, here's what I have.</p> <pre><code>for value in d.values(): ...
<pre><code>import os print(any(os.path.exists(os.path.join(dirpath, filename)) for directories in d.values() for dirpath in directories)) </code></pre>
python
4
7,582
68,828,745
Which seed when using `pytorch.manual_seed(seed)`?
<p>I have trained a model with ImageNet. I got a new GPU and I also want to train the same model on a different GPU.</p> <p>I want to compare if the outcome is different and therefore I want to use <code>torch.manual_seed(seed)</code>.</p> <p>After reading the docs <a href="https://pytorch.org/docs/stable/generated/tor...
<blockquote> How to choose the seed parameter? Can I take 10, 100, or 1000 or even more or less and why? </blockquote> <p>The PyTorch doc page you are pointing to does not mention anything special, beyond stating that the seed is a 64 bits integer.</p> <p>So yes, 1000 is OK. As you expect from a modern pseudo-random nu...
python-3.x|random|pytorch|random-seed
0
7,583
41,387,122
ESP8266 NodeMCU Lua "Socket client" to "Python Server" connection not possible
<p>I was trying to connect a NodeMCU Socket client program to a Python server program, but I was not able to establish a connection.</p> <p>I tested a simple Python client server code and it worked well.</p> <p>Python Server Code</p> <pre><code>import socket # Import socket module s = socket.socket() ...
<p>After I revisited this for the second time it finally clicked. I must have scanned your Lua code too quickly the first time.</p> <p>You need to set up all event handlers (<code>srv:on</code>) <em>before</em> you establish the connection. They may not fire otherwise - depending on how quickly the connection is estab...
python-2.7|lua|esp8266|nodemcu
1
7,584
6,465,686
How to implement a Required Property in Python
<p>If I have a class such as below (only with many more properties), is there are clean way to note which fields are required before calling a particular method?</p> <pre><code>class Example(): def __init__(self): pass @property """Have to use property methods to have docstrings...""" def pro...
<p>Would it not be best to make sure that all the attributes are supplied when an object is initialised? Then all your properties will be defined when you try to acces them.</p> <p>For example,</p> <pre><code>class Example(object): def __init__(self, prop1, prop2): self.prop1 = prop1 self.prop2 = ...
python
8
7,585
56,888,145
jupyter notebook - problem no module named 'pandas'
<p>I am trying to learn pandas and I haven't been able to import it into my code. I have looked at other answers on this site and none of them have worked. jupyter notebook is not importing my module.</p>
<p>let's try: in jupiter</p> <ol> <li><code>!pip install pandas --upgrade</code></li> <li><code>import pandas as pd</code></li> <li><code>print(pd.__version__)</code></li> </ol> <p>what do you see</p>
python|pandas|numpy|jupyter-notebook|anaconda
0
7,586
57,230,172
Button grid shrinking vertically when adding a certain amount of images
<p>I'm making a chess board in Tkinter with chess piece images to get used to the module, and have success with placing the first N-1 images in a row in an NxN grid.</p> <p>However, upon coding an Nth image on any row, the row in question shrinks vertically. </p> <p>I'm trying to use an OOP approach and am thinking t...
<p>In empty <code>Button</code> (or with text) <code>height=5</code> means 5 lines of text. When you put image then it means 5 pixels. </p> <p>When you have empty button in row then it has size 5 lines and it is the highest widget in row so other buttons are resized to row size. When you add last button then all butto...
python|image|button|tkinter
1
7,587
57,045,756
How to do multi-objective optimization using neural networks?
<p>I have five decision variables, each having a specific range. I need to find a combination of these variables so as to maximize one of my objectives while minimizing the other at the same time. I have prepared a datasheet of randomly generated variables with respective values of the 2 objective functions. Please sug...
<p>There are many methods, but the easiest way is "linear scalarization".<br> You can add objectives to make single objective.<br> While doing this, you can weight objectives considering priority.<br> (Making linear combination of multiple objectives)</p> <p>See examples:<br> Variational AE loss (regularization loss +...
python|matlab|neural-network|artificial-intelligence
0
7,588
44,563,790
Can you SELECT the same column twice but one of them with a different alias? [Python, PostgreSQL]
<p>I'm working with this python function with the following description given (and my code below). I want to know if I can use the following column twice (`players.id, players.player_name' and 'players.id AS opponent, players.player_name AS opponent_name').</p> <pre><code>def swissPairings(): """Returns a list of ...
<p>Your question body doesn't appear to actually be asking anything? Though to answer the question in your title, you can do this with <a href="https://www.postgresql.org/docs/9.2/static/sql-select.html" rel="nofollow noreferrer">column aliases</a>:</p> <p>In short:</p> <pre><code>select Col1 as Alias1 ,Col1 a...
python|sql|postgresql
0
7,589
44,537,075
Image Orientation (python+openCV)
<p>Using Python and OpenCV, I try to read an image which size is (3264*2448), but the resulting size is always (2448*3264). That means the direction of the image is changed by 90 degrees. The code is following:</p> <pre><code>img1 = cv2.imread("C:\\Users\\test.jpg", 0) cv2.namedWindow("test", 0) cv2.imshow("test", i...
<p>I faced a similar issue in one program. In my case, the problem was due to the camera orientation data stored in the image.</p> <p>The problem was resolved after I used <code>CV_LOAD_IMAGE_COLOR</code> instead of <code>CV_LOAD_IMAGE_UNCHANGED</code> in OpenCV Java.</p>
python|image|opencv|direction|imread
12
7,590
61,762,513
Find duplicate objects in a dictionary list based on combination of values
<p>I have the following dictionary list</p> <pre><code>dict_list = [{"feed_id": 101, "query_id": 201, "bind_id": 301, "qname":"q1"}, {"feed_id": 101, "query_id": 201, "bind_id": 301, "qname":"q2"}, {"feed_id": 103, "query_id": 201, "bind_id": 301, "qnam...
<p>It's fairly straightforward:</p> <pre><code>dict_list = [{"feed_id": 101, "query_id": 201, "bind_id": 301}, {"feed_id": 101, "query_id": 201, "bind_id": 301}, {"feed_id": 103, "query_id": 201, "bind_id": 301}, {"feed_...
python|python-3.x
2
7,591
24,081,313
TkinterTable - SyntaxError: invalid syntax
<p>This is the error I am getting when I try to run the code.</p> <pre><code> from tkintertable.Tables import * File "C:\Python33\lib\site-packages\tkintertable\Tables.py", line 620 print 'found in',row,col ^ SyntaxError: invalid syntax </code></pre> <p>This is the code</p> <pre><code>from...
<p>In Python 3 the <code>print</code> has become a function rather than a statement:</p> <pre><code>print("hello") </code></pre> <p>instead of</p> <pre><code>print "hello" </code></pre> <p>See <a href="http://legacy.python.org/dev/peps/pep-3105/" rel="nofollow">http://legacy.python.org/dev/peps/pep-3105/</a> for de...
python|python-3.x|tkinter
1
7,592
20,639,534
Run shell commands as root and detect failed password attempts with python
<p>I have a python function I wrote that can run shell commands as root using subprocess. I'm trying to add functionality to that to detect incorrect password attempts. Here's the function.</p> <pre><code>local_pass = None def runShellCommandAsRoot(cmd): global local_pass if local_pass == None: print ...
<p>A friend helped me figure out a better solution to run shell commands and also cover error checking for user password! See below:</p> <pre><code>def run_shell_command_as_root(cmd): cmd[:0] = ['sudo'] if not authenticate(): print 'Unable to authenticate' sys.exit(1) sp = subprocess.Popen(...
python|shell
1
7,593
21,301,841
why does SWIG allow int pointer argument in place of void*, and how to do same for arrays?
<p>I have this class with an <code>int</code> and <code>int[2]</code> members, and I have a <code>getMember</code> accessor method that takes an index of a member and <code>void*</code> and fills the (pre-allocated) space after <code>void*</code> with the member:</p> <p>foobar.h:</p> <pre><code>class Foobar { public:...
<p>Well, I still can't answer Question 1, nevertheless I found the new "magic" way to answer Question 2:</p> <pre><code>%include &lt;carrays.i&gt; %array_functions(int, inta); </code></pre> <p>Now Question 1 is unchanged, and Question 2 becomes, why does it work?</p>
python|c++|swig
0
7,594
53,385,855
Python MQTT improving publish speed for image numpy array
<p>I currently have two scripts, one to capture footage and publish the numpy array values (servant.py) and the other script (master.py) to then process those values using opencv for later facial recognition implementations. Problem is that right now it is very slow since the internet packages being sent arrive very de...
<p>Use <code>WebcamVideoStream</code> from <code>imutils</code>, compress the image in jpg, publish it as base64:</p> <pre><code>import base64 import cv2 from imutils.video import WebcamVideoStream cap = WebcamVideoStream(0) cap.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) c...
python|mqtt
0
7,595
54,892,694
Nested while loops with scatter update in Tensorflow
<p>variable <code>v1=[[0,0],[0,0]]</code> Tensor <code>t1=[[-1,0],[1,1]]</code></p> <p>I want output <code>op=[[1,0],[0,2]]</code></p> <p><strong>Logic:</strong> If <code>t1==-1</code> then ignore. Else use <code>t1</code> value as index for <code>v1</code> and add 1 to that <code>v1</code> value.</p> <p><strong>Py...
<p>You may try <code>tf.map_fn</code>:</p> <pre><code>import tensorflow as tf v1 = tf.Variable([[0,0],[0,0]], dtype=tf.int32) t1 = tf.constant([[-1,0],[1,1]], dtype=tf.int32) result = tf.map_fn(lambda x: x[0]+tf.math.bincount(tf.gather_nd(x[1], tf.where(tf.not_equal(x[1],-1))),minlength=x[0].shape[0]) ...
tensorflow
1
7,596
33,175,525
Unable to install logging module (Python)
<p>I'm trying to install the logging module for Python 3.4. I'm using pip3 install logging. Both times I run into a SyntaxError at line 618 of the <strong>init</strong> method: "raise NotImplementedError, 'emit must be implemented '\".</p> <p>Someone posted the same question as me, and solved their problem by deleting...
<p><a href="https://docs.python.org/3/library/logging.html" rel="noreferrer"><code>logging</code></a> is part of the Python standard library, and has been since version 2.3. It's available as soon as you install Python. You don't need to <code>pip install</code> anything...</p>
python|python-3.x|logging|pip|python-3.4
64
7,597
33,157,558
Read python output from another python script
<p>I have two python files, one contains code which generates an output and the other needs to read it. The generation code is:</p> <pre><code>b=5 return b </code></pre> <p>The reading code is:</p> <pre><code>import os c= os.system("test.py") print (c) </code></pre> <p>When I run this, the output is 1. I don't unde...
<p>Put all the code in your first file into a function.</p> <pre><code>#Fred.py def frob(): b=5 return b </code></pre> <p>Then, you can import that function from any other Python file and see its return value.</p> <pre><code>#Barney.py from Fred import frob print frob() #result: 5 </code></pre>
python
1
7,598
24,835,286
How do I take the value of one variable and set it equal to another variable in a class?
<p>Here's the code I'm trying to use. Works just fine if I use getset_pos as a function instead of a method here. edit: correction to line 6 (getset_pos is now self.getset_pos); edit2: added call to class at end</p> <pre><code>class Main: def __init__(self): self.i = [5, 5] self.o = [] sel...
<p>You cannot perform assignments to a reference that is passed in as an argument, and expect that assignment to be reflected outside the method. The answers to <a href="https://stackoverflow.com/q/986006/391161">this question</a> go into the details of why.</p> <p>A more direct approach would be to simply use the <co...
python
3
7,599
41,169,616
Unable to pass argument from batch file to python file
<p>I am trying to pass an argument from batch file to my python file.<br> I followed the steps given in these two links:</p> <ul> <li><a href="https://stackoverflow.com/questions/27810974/passing-argument-from-batch-file-to-python">Passing Argument from Batch File to Python</a></li> <li><a href="https://stackoverflow....
<p>The issue is related on how python works with argv. In this scenario, when you run:</p> <pre><code>main(sys.argv[:1]) # (["C:\Users\abcd\Documents\automation\testsendemail.py"]) </code></pre> <p>you actually get <strong>only</strong> the first arguments passed to the python script, which is the current script loca...
python|windows|batch-file|python-2.x
4