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
100
51,093,232
Increase a variable up to a maximum size
<p>I'm working on a simple game that you put the number of enemies and you hit them or cure yourself. But, the player has a maximum amount of 500 of life. The cure uses <code>random.randint(10,14)</code>.</p> <pre><code>if player_sp &gt;= 10: if player_vida &lt; 500: cura = random.randint(10,14) pl...
<p>How about replacing:</p> <pre><code>player_vida += cura </code></pre> <p>with:</p> <pre><code>player_vida = min(500, player_vida + cura) </code></pre>
python|pygame
4
101
42,471,299
How to create a data structure in a Python class
<pre class="lang-python prettyprint-override"><code>class CD(object): def __init__(self,id,name,singer): self._id = id self.n = name self.s = singer def get_info(self): info = 'self._id'+':'+ ' self.n' +' self.s' return inf...
<p>You can use simple loop with <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow noreferrer"><code>enumerate</code></a> for this.</p> <pre><code># I don't know what you mean by 'file has list of tuples', # so I assume you loaded it somehow tuples = [("Shape of you", "Ed Sheeran"), ("S...
python|class
1
102
58,455,350
Memory leak using fipy with trilinos
<p>I am currently trying to simulate a suspension flowing around a cylindrical obstacle using fipy. Because I'm using fine mesh and my equations are quite complicated, the simulations take quite a long time to converge. Which is why I want to run them in parallel. However, when I do that the program keeps using more an...
<p>This is an <a href="https://github.com/trilinos/Trilinos/issues/2327" rel="nofollow noreferrer">issue we have reported against PyTrilinos</a></p>
python|fipy|trilinos
0
103
58,524,100
My Tensorflow lite model accuracy and Image Classification issues
<p>First off, I've succeed in deploying my fine tuned Xception model to my android application, it working fine, except some harsh image that it predicted wrong, however, on my computer, with that image, it's predicted correct even though the accuracy was around 50-60%. So, is converting to tensorflow lite model reduce...
<p>Conversion to TensorFlow Lite <em>is</em> expected to reduce accuracy, especially for outlier inputs such as the one you describe.</p> <p>If you provide an input from a class that the model was not trained on, the output is 'undefined' - the logits will essentially be garbage.</p> <p>If you want a model that has m...
android-studio|image-processing|deep-learning|tensorflow-lite
0
104
41,253,942
How do you get a field related by OneToOneField and ManyToManyField in Django?
<p>How do you get a field related by OneToOneField and ManyToManyField in Django?</p> <p>For example,</p> <pre><code>class A(models.Model): myfield = models.CharField() as = models.ManyToManyField('self') class B(models.Model): a = models.OneToOneField(A) </code></pre> <p>If I want to get a 'myfield' and...
<p><strong>Models.py</strong></p> <pre><code>class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): # __unicode__ on Python 2 return "%s the place" % self.name class Restaurant(models.Model): place = models.O...
python|django|django-models|django-orm
0
105
24,047,017
SWF file loads a new url, how to grab it using Python?
<p>I'll start with saying I'm not very familiar with AS3 coding at all, which I'm pretty sure SWF files are coded with (someone can correct me if I'm wrong)</p> <p>I have a SWF file which accepts an ID parameter, within the code it takes the ID and performs some hash routines on it, eventually produces a new 'token' a...
<p>Looks like I was making things too complicated</p> <p>I was able to just use python hashlib.md5 to produce the same results as the AS3 code</p> <pre><code>m = hashlib.md5() m.update('test') m.hexdigest() </code></pre>
python|actionscript-3|flash
0
106
20,683,655
Why the two threading implementation behaves differently?
<p>Why the two threading implementations in python are behaving differently ?</p> <p>I have two codes:</p> <p>1.</p> <pre><code>from threading import Thread import pdb import time def test_var_kwargs(**kwargs): time.sleep(5) print kwargs['name'] for key in kwargs: print "another keyword arg: %s: %s" % (...
<p>It took me a little while to figure the problem out... </p> <p>This line:</p> <pre><code>thr = Thread(target=test_var_kwargs(name='xyz', roll=12)) </code></pre> <p>Is incorrect. Try:</p> <pre><code>thr = Thread(target=test_var_kwargs, kwargs={'name':'xyz', 'roll': 12}) </code></pre> <p>The first example is bloc...
python|multithreading
2
107
53,439,796
Selecting Rows with DateTimeIndex without referring to date
<p>Is there a way to select rows with a DateTimeIndex without referring to the date as such e.g. selecting row index 2 (the usual Python default manner) rather than "1995-02-02"?</p> <p><a href="https://i.stack.imgur.com/gp3PH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gp3PH.png" alt="enter ima...
<p>Yes, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-integer" rel="nofollow noreferrer">.iloc</a>, the positional indexer:</p> <pre><code>df.iloc[2] </code></pre> <p>Basically, it indexes by actual position starting from <code>0</code> to <code>len(df)</code>, allowing slic...
python|python-3.x|pandas
1
108
21,420,868
How to fix the false positives rate of a linear SVM?
<p>I am an SVM newbie and this is my use case: I have a lot of unbalanced data to be binary classified using a linear SVM. I need to fix the false positives rate at certain values and measure the corresponding false negatives for each value. I am using something like the following code making use of scikit-learn svm im...
<p>The <code>class_weights</code> parameter allows you to push this false positive rate up or down. Let me use an everyday example to illustrate how this work. Suppose you own a night club, and you operate under two constraints:</p> <ol> <li>You want as many people as possible to enter the club (paying customers)</li>...
python|svm|scikit-learn
18
109
52,128,289
Python - Split PDF based on list
<p>I'm trying to split a PDF into separate PDF files into new files based on a list. Code as follows:</p> <pre><code>import sys import os from PyPDF2 import PdfFileReader, PdfFileWriter def splitByStudent(file, group): inputPdf = PdfFileReader(open(file,"rb")) output = PdfFileWriter() path = os.path.dirna...
<p>The line <code>output = PdfFileWriter()</code> should be inside the for loop:</p> <pre><code>def splitByStudent(file, group): inputPdf = PdfFileReader(open(file,"rb")) path = os.path.dirname(os.path.abspath(file)) os.chdir(path) numpages = int(inputPdf.numPages/len(group)) for s in group: ...
python|python-3.x|pdf
0
110
54,556,450
How to find the rows having values between -1 and 1 in a given numpy 2D-array?
<p>I have a <code>np.array</code> of shape <code>(15,3)</code>.</p> <pre><code>final_vals = array([[ 37, -84, -143], [ 29, 2, -2], [ -18, -2, 0], [ -3, 6, 0], [ 361, -5, 2], [ -23, 4, 8], [ 0, -1, 0], [ -1, 1, 0], [ 6...
<p>You could take the absolute value of all elements, and check which rows's elements are smaller or equal to <code>1</code>. Then use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.flatnonzero.html" rel="nofollow noreferrer"><code>np.flatnonzero</code></a> to find the indices where all colu...
python|numpy
2
111
31,731,863
From JSON to JSON-LD without changing the source
<p>There are 'duplicates' to my question but they don't answer my question.</p> <p>Considering the following JSON-LD example as described in paragraph 6.13 - Named Graphs from <a href="http://www.w3.org/TR/json-ld/" rel="nofollow">http://www.w3.org/TR/json-ld/</a>:</p> <pre><code>{ "@context": { "generatedAt"...
<p>No, unfortunately that's not possible. There exist, however, libraries and tools that have been created exactly for that reason. <a href="https://github.com/antoniogarrote/json-ld-macros" rel="nofollow">JSON-LD Macros</a> is such a library. It allows declarative transformations of JSON objects to make them usable as...
python|json|rdf|json-ld
4
112
32,007,291
What is the best manner to run many Scrapy with multiprocessing?
<p>currently I use Scrapy with multiprocessing. I made a POC, in order to run many spider. My code look like that:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Lock, Process, Queue, current_process def worker(work_queue, done_queue): try: for url in iter(work_queue...
<blockquote> <p>It would be better to launch a Scrapy instance for each URL or launch a spider with x URL (ex: 1 spider with 100 links) ?</p> </blockquote> <p>Launching an instance of Scrapy is definitely a bad choice, because for every URL you would be suffering from the overhead of Scrapy itself.</p> <p>I think i...
python|python-2.7|web-scraping|scrapy|multiprocessing
0
113
47,058,742
Appending and formatting a new SubElement via ElementTree
<p>Using the following code, I can successfully add a subElement where I want, and functionally it works. For readability, I want to format the way <code>item.append</code> inserts the new sub elements. My Code:</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse(file.xml) root = tree.getroot() for ite...
<p>Consider using <code>.find()</code> to walk down to your needed node and then simply use <code>SubElement</code> to add. No need for string versions of markup when working with DOM libraries like <code>etree</code>:</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse("input.xml") root = tree.getroot(...
python|xml|python-3.x|elementtree
2
114
71,843,912
Is there a way to make a function run after a specified amount of time in Python without the after method?
<p>I am trying to create a simple program that tracks a user's clicks per second in Tkinter, but I have no idea how to make the program wait without freezing the program using the after method. The problem is that I need to log the high score after the time finishes, but using this method, the score logs before the cli...
<p>Give it a try</p> <pre><code>from tkinter import * root = Tk() root.geometry('600x410') screen = Canvas(root) h = 6 # button height w = 12 # button width c = 0 # counts amount of times clicked start_btn = 0 # logs clicks of the start button high_score = 0 # logs the highest score time = 0 def count_hs(): ...
python|tkinter
0
115
15,424,895
Creating Lexicon and Scanner in Python
<p>I'm new here in the world of coding and I haven't received a very warm welcome. I've been trying to learn python via the online tutorial <a href="http://learnpythonthehardway.org/book/" rel="noreferrer">http://learnpythonthehardway.org/book/</a>. I've been able to struggle my way through the book up until exercise ...
<p>I wouldn't use a list to make the lexicon. You're mapping words to their types, so make a dictionary.</p> <p>Here's the biggest hint that I can give without writing the entire thing:</p> <pre><code>lexicon = { 'north': 'directions', 'south': 'directions', 'east': 'directions', 'west': 'directions',...
python|lexicon
3
116
46,464,857
Removing rows that are similar in Python
<p>My data looks something like this:</p> <pre><code> Source Target Value 1 Charlie Mac 0.6530945 2 Dennis Fank 0.7296234 3 Charlie Frank 0.4750875 4 Mac Dennis 0.3961787 5 Charlie Dennis 0.6213751 6 Mac Frank 0.9727454 7 Frank Charlie 0.4750875 8 Mac Charlie 0.6530945 9 ...
<pre><code>df[~pd.DataFrame(np.sort(df[['Source', 'Target']], 1), df.index).duplicated()] Source Target Value 1 Charlie Mac 0.653095 2 Dennis Frank 0.729623 3 Charlie Frank 0.475087 4 Mac Dennis 0.396179 5 Charlie Dennis 0.621375 6 Mac Frank 0.972745 </code></pre>
python|pandas|dataframe
5
117
46,351,322
Pandas - moving average grouped by multiple columns
<p>New to Pandas, so bear with me.</p> <p>My dataframe is of the format</p> <pre><code>date,name,country,tag,cat,score 2017-05-21,X,US,free,4,0.0573 2017-05-22,X,US,free,4,0.0626 2017-05-23,X,US,free,4,0.0584 2017-05-24,X,US,free,4,0.0563 2017-05-21,X,MX,free,4,0.0537 2017-05-22,X,MX,free,4,0.0640 2017-05-23,X,MX,fre...
<p>IIUC:</p> <pre><code>(df.assign(moving_score=df.groupby(['name','country','tag'], as_index=False)[['score']] .rolling(2, min_periods=2).mean().fillna(0) .reset_index(0, drop=True))) </code></pre> <p>Output:</p> <pre><code> date name country tag cat ...
python|pandas|moving-average
6
118
49,489,500
Find a word in a line no matter how it's written
<p>I'm trying to find a word in a simple string no matter how it's written. For example:</p> <p>'Lorem ipsum dolor sit amet lorem.'</p> <p>Let's say I search for 'lorem' written in lowercase and I'd like to replace both 'lorem' and 'Lorem' with 'example'. The thing is, I want to search and replace the word no matter ...
<pre><code>import re sentence = "Lorem ipsum dolor sit amet lorem." search_key = "Lorem" print(re.sub(r'%s' % search_key.lower(), 'example', sentence.lower())) &gt;&gt;&gt; example ipsum dolor sit amet example. </code></pre>
python|python-3.x
1
119
49,590,870
How can I pass JSON of flask to Javascript
<p>I have an index page, which contains a form, fill in the form and sends the data to a URL, which captures the input, and does the search in the database, returning a JSON. How do I get this JSON, and put it on another HTML page using Javascript?</p> <p>Form of index:</p> <pre><code>&lt;form action="{{ url_for('ret...
<p>Your HTML page after you submit the form. let's call it <code>response.html</code></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;hello&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p id="test"&gt;&lt;/p&gt; &lt;p id="test1"&gt;&lt;/p&gt; &lt;script&gt; var b = ...
javascript|python|flask
4
120
21,113,349
Is subclasing django base classes to intermediate ones a bad idea?
<p>I have subclassed ModelForm to an intermediate ModelForm2 to make sure some form elements have certain css classes / widgets and to remove the label suffix. My question is: Is this a bad idea since it makes the code less portable in case they drop ModelForm classes? This is the code:</p> <pre><code>class ModelForm2...
<p>No, this is <em>not</em> a bad idea, this is very normal 'best practice' Django.</p> <p><code>ModelForm</code> is a core part of Django, it is pretty unthinkable they would drop it.</p> <p>Typical Django project will have many sub-classes from Django base classes.</p> <p>I will often have an app in my project I c...
python|django|django-forms
2
121
62,573,223
What is the meaning of `[[[1,2],[3,4]],[[5,6],[7,8]]]` in Python?
<pre><code>x=[[[1,2],[3,4]],[[5,6],[7,8]]] print(x[1][0][1]) </code></pre> <p><em><strong>could you please tell me the output and how's it obtained</strong></em></p>
<p><code>list[i]</code> takes the (i+1)-th element of the list, so <code>[0]</code> means the first element and <code>[1]</code> the second element from the list. Counting in computer science always starts at 0.</p> <p><code>x[1]</code> = <code>[[5,6],[7,8]]</code></p> <p><code>x[1][0]</code> = <code>[5,6]</code></p> <...
python|python-3.x|python-2.7|python-requests
2
122
53,513,063
How to convert dictionary of tuple coordinates keys to sparse matrix
<p>I stored the non-zero values of a sparse matrix in a dictionary. How would I this into an actual matrix?</p> <pre><code>def sparse_matrix(density,order): import random matrix = {} for i in range(density): matrix[(random.randint(0,order-1), random.randint(0,order-1))] = 1 return matri...
<p><strong>Option 1 :</strong> Instead of keeping values in list and later creating the matrix, you can directly create the matrix and update the values in it. Please note you can have less number of non zero values than "order" as randint can return same number again.</p> <p>Sample code : </p> <pre><code>import rand...
python|python-3.x|sparse-matrix
0
123
53,466,909
Python use curl with subprocess, write outpute into file
<p>If I use the following command in the Git Bash, it works fine. The Output from the curl are write into the file output.txt</p> <pre><code>curl -k --silent "https://gitlab.myurl.com/api/v4/groups?page=1&amp;per_page=1&amp;simple=yes&amp;private_token=mytoken&amp;all?page=1&amp;per_page=1" &gt; output.txt </code></pr...
<p>You cannot use redirection directly with subprocess, because it is a shell feature. Use <code>check_output</code>:</p> <pre><code>import subprocess command = ["curl", "-k", "--silent", "https://gitlab.myurl.com/api/v4/groups?page=1&amp;per_page=1&amp;simple=yes&amp;private_token=mytoken&amp;all?page=1&amp;per_page=...
python|curl
1
124
46,063,345
Python - How to create a tunnel of proxies
<p>I asked this question: <a href="https://stackoverflow.com/questions/46021477/wrap-packets-in-connect-requests-until-reach-the-last-proxy/46023292#46023292">Wrap packets in connect requests until reach the last proxy</a></p> <p>And I learnt that to create a chains of proxies I have to:</p> <ul> <li>create a socket<...
<p>There is no Host header with CONNECT. I.e. to request HTTP proxy A to create a tunnel to HTTP proxy B you just use:</p> <pre><code>&gt;&gt;&gt; CONNECT B_host:B_port HTTP/1.0 &gt;&gt;&gt; &lt;&lt;&lt; 200 connections established &lt;&lt;&lt; </code></pre> <p>And then you have this tunnel to proxy B via proxy A. In...
python|python-3.x|sockets|proxy|tunnel
1
125
55,102,133
Replace the first characters if the object contain the symbol Python Pandas
<p>I have the string objects in the pandas Dataframe: </p> <pre><code>['10/2014', '2014','9/2013'] </code></pre> <p>How to replace them to get this result:</p> <pre><code>['2014','2014','2013'] </code></pre>
<p>If you want the last set of characters separated by <code>'/'</code>, try this :</p> <pre><code>[k.split('/')[-1] for k in ['10/2014', '2014','9/2013']] </code></pre> <p><strong>OUTPUT</strong> :</p> <pre><code>['2014', '2014', '2013'] </code></pre>
python|pandas
3
126
55,053,618
SQLAlchemy - Return filtered table AND corresponding foreign table values
<p>I have the following SQLAlchemy mapped classes: </p> <pre><code>class ShowModel(db.Model): __tablename__ = 'shows' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) episodes = db.relationship('EpisodeModel', backref='episode', lazy='dynamic') class EpisodeModel(db.Mo...
<p>Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:</p> <pre><code>shows = session.query(ShowModel) .join(EpisodeModel) .join(InfoModel) .filt...
python|sql|sqlalchemy
2
127
33,382,305
PyAudio IOError: [Errno Invalid input device (no default output device)] -9996
<p>I am attempting to run a simple python file that uses pyaudio to record input. However whenever I run this file I end up with this error. I had it working once and I have no idea what changed. I have tried </p> <pre><code>import pyaudio pa = pyaudio.PyAudio() print(pa.get_device_count()) 0 </code></pre> <p>So I...
<p>I got this error because I accidentally ran</p> <pre><code># p = pyaudio.PyAudio() # ... p.terminate() </code></pre> <p>and then tried to open another stream.</p>
python|portaudio|pyaudio
4
128
24,871,188
Watershed Transform of Distance Image with OpenCV
<p>In Matlab, we can perform a watershed transform on the distance transform to separate two touching objects: </p> <p><img src="https://i.stack.imgur.com/tpA9p.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/PyB2z.png" alt="enter image description here"></p> <p>The first image above is t...
<p>You'd berrer get to know what readlly happen in the function of watershed. it starts flooding with its seeds and put the coordinate and the gradient of their neighbours in a priority queue.</p> <p>As you know, when you apply distanceTransform on img, the gradient of circles becomes 0 or 1, but the background always ...
python|opencv|distance|image-segmentation|watershed
3
129
38,220,821
Regex replace conditional character
<p>I need to remove any 'h' in a string if it comes after a vowel.</p> <pre><code>E.g. John -&gt; Jon Baht -&gt; Bat Hot -&gt; Hot (no change) Rhythm -&gt; Rhythm (no change) </code></pre> <p>Finding the words isnt a problem, but removing the 'h' is as I still need the original vowel. Can this be done...
<p>The regex for matching <code>h</code> after a vowel would be a positive lookbehind one</p> <pre><code>(?&lt;=a|e|y|u|o|a)h </code></pre> <p>And you can do</p> <pre><code>re.sub(r"([a-zA-Z]*?)(?&lt;=a|e|y|u|o|a)h([a-zA-Z]*)",r"\1\2",s) </code></pre> <p>However, if you can have more than one <code>h</code> after a...
java|python|regex
2
130
38,441,079
Python sum and then multiply values of several lists
<p>Is there way to write following code in one line?</p> <pre><code>my_list = [[1, 1, 1], [1, 2], [1, 3]] result = 1 for l in list: result = result * sum(l) </code></pre>
<p>Use <code>reduce</code> on the <em>summed</em> sublists gotten from <code>map</code>.</p> <p>This does it:</p> <pre><code>&gt;&gt;&gt; from functools import reduce &gt;&gt;&gt; reduce(lambda x,y: x*y, map(sum, my_list)) 36 </code></pre> <hr> <p>In python 2.x, the <code>import</code> will not be needed as <code>r...
python
5
131
38,231,521
What should be the size of input and hidden state in GRUCell of tensorflow (python)?
<p>I am new to tensorflow (1 day of experience).</p> <p>I am trying following small code to create a simple GRU based RNN with single layer and hidden size of 100 as follows:</p> <pre><code>import pickle import numpy as np import pandas as pd import tensorflow as tf # parameters batch_size = 50 hidden_size = 100 # ...
<p>Input to the <code>GRUCell</code>'s call operator are expected to be 2-D tensors with <code>tf.float32</code> type. The following ought to work :</p> <pre><code>input_data = tf.placeholder(tf.float32, [batch_size, input_size]) cell = tf.nn.rnn_cell.GRUCell(hidden_size) initial_state = cell.zero_state(batch_size, ...
python|tensorflow|recurrent-neural-network|gated-recurrent-unit
0
132
38,372,786
python qt float precision from boost-python submodule
<p>I have made a cpp submodule with boost-python for my PyQt program that among others extracts some data from a zip data file.</p> <p>It works fine when testing it in python:</p> <pre><code>import BPcmods BPzip = BPcmods.BPzip() BPzip.open("diagnostics/p25-dev.zip") l=BPzip.getPfilenames() t=BPzip.getTempArray([l[1]...
<p>Well it was related to using std::stod to convert my strings of data from my datafile to doubles. I don't know why, but changing to:</p> <pre><code>boost::algorithm::trim(s); double val = boost::lexical_cast&lt;double&gt;(s); </code></pre> <p>made it work as it was supposed to, also in pyqt.</p>
python|c++|boost|pyqt4|precision
0
133
38,295,363
Difference between tuples (all or none)
<p>I have two sets as follows:</p> <pre><code>house_1 = {('Gale', '29'), ('Horowitz', '65'), ('Galey', '24')} house_2 = {('Gale', '20'), ('Horowitz', '65'), ('Gale', '29')} </code></pre> <p>Each tuple in each set contains attributes that represent a person. I need to find a special case of the symmetric set differenc...
<p>You could count the occurences of names in the result and print only tuples that correspond to the names with the count of 1:</p> <pre><code>from collections import defaultdict count = defaultdict(list) for x in house_1 ^ house_2: count[x[0]].append(x) for v in count.values() if len(v) == 1: print...
python|set|tuples
1
134
31,094,159
How do I tell lxml which charset to use?
<p>I'm working with html and using lxml to parse it. For testing purposes I have an html document saved as a string in a python file with encoding=utf-8 at the top.</p> <p>Whenever I try to parse the html using lxml I get weird html encodings if the html does not have the <code>&lt;meta charset="utf-8"&gt;</code> tag....
<p>Turns out I just need to pass in a custom parser to the <code>fromstring</code> method. So this fixes it:</p> <pre><code>parser = html.HTMLParser(encoding="utf-8") t = lxml.html.fromstring(page_html, parser=parser) print lxml.html.tostring(t) </code></pre>
python|lxml
0
135
30,952,575
How to get real quotient in python 2
<p>Since the division operator "/" only returns floor quotient. When numerator or denominator is a minus number, operator "/" will not return the real quotient. Like -1/3 returns -1 rather than 0. How can i get the real quotient? </p>
<p>Try like this,</p> <pre><code>a = 1 b = 3 print -(a / b) </code></pre>
python-2.7
0
136
40,159,812
Passing a class's "self" to a function outside it such that the class's variables are accessible and modifiable?
<p>Can I pass the <code>self</code> instance variable of the class from within the class to some helper function outside the class? For example, will the following work when an object of SomeClass is initialized? Isn't there any type casting required? Is this coding style reliable? Is there any possibility of this feat...
<p>The easiest way would have been to try it out :) yes, it works, as you expect</p> <pre><code>class SomeClass(): var1 = 7 def __init__(self): some_func(self) # passing self instead of self.var1 def some_func(instance): instance.var1 += 1 x = SomeClass() print x.var1 </code></pre> <p>But in mos...
python|python-2.7|oop
4
137
19,131,736
Zip a folder on S3 using Django
<p>I have an application where in I need to zip folders hosted on S3.The zipping process will be triggered from the model save method.The Django app is running on an EC2 instance.Any thoughts or leads on the same?</p> <p>I tried django_storages but haven't got a breakthrough</p>
<p>from my understanding you can't zip files directly on s3. you would have to download the files you'd want to zip, zip them up, then upload the zipped file. i've done something similar before and used s3cmd to keep a local synced copy of my s3bucket, and since you're on an ec2 instance network speed and latency will ...
python|django|amazon-s3|amazon-ec2|zip
0
138
62,102,978
How to display y-bar values in the bar chart?
<p>Hello friends I am creating a bar chart using <code>seaborn</code> or <code>matplotlib</code>. I make a successful graph, but I don't know how to display y bar values on the plot. Please give me suggestion and different techniques to display y-bar values on the plot.</p> <p>Please help me to solve the question.</p> ...
<p><strong>Short answer:</strong> You need customized auto label mechanism.</p> <p>First let's make it clear. If you mean by</p> <blockquote> <p>I don't know how to display y bar values on the plot</p> </blockquote> <ul> <li><p>that <em>on bars</em> (inner), then this <a href="https://stackoverflow.com/a/19919397/10452...
python|matplotlib|seaborn|data-science
0
139
62,440,669
How to get parameters from strings in Python?
<p>How can I get some parameters from a string in Python.</p> <p>Let's say the string contains two words which I want to use as parameters. These are of course separated by spaces. Example:</p> <pre class="lang-py prettyprint-override"><code>string = "Lorem Ipsum" def funct(hereLorem, hereIpsum) </code></pre>
<p>You can try a string.split(optional delimiter). This returns a list.</p> <p>Example:</p> <pre><code>l = string.split() </code></pre> <p>and if you're expecting a certain pattern</p> <pre><code>arg1 = l[0] arg2 = l[1] ... </code></pre>
python|python-3.x|string|parameters|arguments
0
140
67,558,573
telegram doesn't show the image preview link always with my amazon afiliates
<p>I have a telegram channel and since yesterday it does not show <strong>the image preview of the links</strong> that I send with a <strong>bot</strong>.</p> <p>I send links with my ID of <strong>amazon afiliates</strong> and it doesn't work.</p> <p>Anyone knows how to solve it?</p> <pre><code>bot = telegram.Bot(bot_t...
<p>If your goal is to create a link preview and not using <code>html</code> markup, then this might help you:</p> <pre class="lang-py prettyprint-override"><code>bot = telegram.Bot(bot_token) bot.send_message( bot_chatID, text='''*Hello* [https://www.amazon.es/dp/B076MMCQWW?psc=1](https://www.amazon.es/dp/B07...
python|telegram|python-telegram-bot
0
141
36,560,829
How to create a seaborn.heatmap() with frames around the tiles?
<p>I rendered a heatmap with seaborn.heatmap() works nicely. However, for a certain purpose I need frames around the plot. </p> <p><code>matplotlib.rcParams['axes.edgecolor'] = 'black'</code><br> <code>matplotlib.rcParams['axes.linewidth'] = 1</code></p> <p>both don't work.</p>
<pre><code>ax = sns.heatmap(x) for _, spine in ax.spines.items(): spine.set_visible(True) </code></pre>
python|matplotlib|seaborn
16
142
19,800,454
processing a set of unique tuples
<p>I have a set of unique tuples that looks like the following. The first value is the name, the second value is the ID, and the third value is the type.</p> <blockquote> <p>('9', '0000022', 'LRA')<br> ('45', '0000016', 'PBM')<br> ('16', '0000048', 'PBL')<br> ('304', '0000042', 'PBL')<br> ('7', '0000014', 'I...
<p><a href="http://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> with some additional processing of what it outputs will do the job:</p> <pre><code>from itertools import groupby data = { ('9', '0000022', 'LRA'), ('45', '0000016', 'PBM'), ('16...
python|tuples
3
143
22,265,689
Python the whole Module
<p>Normally when you execute a python file you do python <em>*</em>.py</p> <p>but if the whole Module which contain many .py files inside</p> <p>for example MyModule contain many .py file and if I do </p> <p><code>python -m MyModule $*</code> what would happen as oppose python individual python file?</p>
<p>I think you may be confusing <em>package</em> with <em>module</em>. A python module is always a single .py file. A package is essentially a folder which contains a special module always named <code>__init__.py</code>, and one or more python modules. Attempting to execute the package will simply run the <code>__init_...
python
2
144
43,678,408
How to create a conditional task in Airflow
<p>I would like to create a conditional task in Airflow as described in the schema below. The expected scenario is the following:</p> <ul> <li>Task 1 executes</li> <li>If Task 1 succeed, then execute Task 2a</li> <li>Else If Task 1 fails, then execute Task 2b</li> <li>Finally execute Task 3</li> </ul> <p><a href="htt...
<p>Airflow has a <a href="https://airflow.apache.org/docs/stable/_api/airflow/operators/python_operator/index.html?highlight=branchpythonoperator#airflow.operators.python_operator.BranchPythonOperator" rel="noreferrer">BranchPythonOperator</a> that can be used to express the branching dependency more directly.</p> <p>...
python|conditional-statements|airflow
83
145
43,785,228
Analyzing the probability distribution of nodes in a network through networkx
<p>I am using python's networkx to analyze the attributes of a network, I want to draw a graph of power law distribution.This is my code.</p> <pre><code>degree_sequence=sorted(nx.degree(G).values(),reverse=True) plt.loglog(degree_sequence,marker='b*') plt.show() </code></pre> <p>This is my graph:<a href="https://i.s...
<p>You just need to construct a histogram of the degrees, i.e. hist[x] = number of nodes with degree x, and then normalize hist to sum up to one.</p> <p>Alternatively flip your axes and normalize such that the values sum to one.</p>
python|networkx
0
146
43,730,137
Tkinter PIR sensor
<p>I'm trying to create a smart mirror that displays different information such as the weather, 3 day forecast, news feed, and a tweet. I have all of this information printing in a window arranged how I want, but the final piece of the program I need to get to function with the rest of the program is a PIR sensor.</p> ...
<p>You can't have a tkinter program with an infinate while loop and expect the tkinter mainloop to run.</p> <p>Suggest that you make use of the callbacks in gpiozero to call a function to enable the screen when motion is detected and perhaps a tkinter.after method to turn the screen off after a specified time period.<...
python-3.x|tkinter|motion-detection
0
147
54,272,461
Keras Neural Network accuracy only 10%
<p>I am learning how to train a keras neural network on the MNIST dataset. However, when I run this code, I get only 10% accuracy after 10 epochs of training. This means that the neural network is predicting only one class, since there are 10 classes. I am sure it is a bug in data preparation rather than a problem w...
<p>Here is the list of some weird points that I see :</p> <ul> <li>Not rescaling your images -> <code>ImageDataGenerator(rescale=1/255)</code></li> <li>Batch Size of 1 (You may want to increase that)</li> <li>MNIST is grayscale pictures , therefore <code>color_mode</code> should be <code>"grayscale"</code>.</li> </ul>...
python|tensorflow|keras|conv-neural-network|mnist
1
148
71,301,069
How can I create a user in Django?
<p>I am trying to create a user in my Django and React application (full-stack), but my views.py fails to save the form I give it. Can someone explain me the error or maybe give me other ways to create an user? Below there is the code:</p> <pre><code># Form folder def Registration(request): if request.method == 'PO...
<p>In your module where you call <code>User</code> in the django server you want to call something like</p> <pre><code>user = User.objects.create_user(username, email, password) if not user: raise Exception(&quot;something went wrong with the DB!&quot;) </code></pre> <p>It may be helpful to read the <a href="https:...
python|django
1
149
71,414,133
how to find if any character in a string is a number in python? .isnumeric and .isdigit isn't working
<p>I need to determine if there are alphabetic and numeric characters in a string. My code for testing the alphabetic one seems to work fine, but numeric is only working if all of the characters are a digit, not if any.</p> <p>The alphabetic code that works:</p> <pre><code>from curses.ascii import isalnum, isalpha, isd...
<p>As the comments have pointed out, both your <code>contains_alphabetic</code> and <code>contains_numeric</code> functions don't do what you think they're doing, because they terminate prematurely - during the very first iteration. You start a loop, inspect the current character (which will be the first character of t...
python
0
150
39,404,033
Is it possible to name a variable 'in' in python?
<p>I am making a unit converter for a homework assignment, and I am using abbreviations for the various units of measurement as variable names, but when I try to define 'in' as a variable, it thinks I mean to use the word 'in' as if I wanted to say 'for x in y' or something like that, and I get the following error:</p>...
<p><code>in</code> is a python keyword, so no you cannot use it as a variable or function or class name.</p> <p>See <a href="https://docs.python.org/2/reference/lexical_analysis.html#keywords" rel="nofollow">https://docs.python.org/2/reference/lexical_analysis.html#keywords</a> for the list of keywords in Python 2.7.1...
python|python-2.7|units-of-measurement|unit-conversion
4
151
55,471,260
How can I reduce a tensor's last dimension in PyTorch?
<p>I have tensor of shape <code>(1, 3, 256, 256, 3)</code>. I need to reduce one of the dimensions to obtain the shape <code>(1, 3, 256, 256)</code>. How can I do it? </p> <p>Thanks!</p>
<p>If you intend to apply mean over the last dimension, then you can do so with:</p> <pre><code>In [18]: t = torch.randn((1, 3, 256, 256, 3)) In [19]: t.shape Out[19]: torch.Size([1, 3, 256, 256, 3]) # apply mean over the last dimension In [23]: t_reduced = torch.mean(t, -1) In [24]: t_reduced.shape Out[24]: torch....
arrays|python-3.x|numpy|pytorch|tensor
1
152
52,452,524
Searching for a key in python dictionary using "If key in dict:" seemingly not working
<p>I'm iterating through a csv file and checking whether a column is present as a key in a dictionary.</p> <p>This is an example row in the CSV file</p> <pre><code>833050,1,109,B147599,162560,0 </code></pre> <p>I'm checking whether the 5th column is a key in this dictionary</p> <pre><code>{162560: True, 165121: Tru...
<pre><code>{162560: True} # {int:bool} {'162560': True} # {str:bool} </code></pre> <p>So, <code>mt_budgets</code> does not contain <code>'162560'</code> (str), it contains <code>162560</code> (int)</p> <p>Your code should be:</p> <pre><code>def check(self, mt_budgets): present = {} cwd = os.getcwd() path...
python|csv|dictionary
4
153
47,842,388
Read text files from website with Python
<p>Hello I have got problem I want to get all data from the web but this is too huge to save it to variable. I save data making it like this:</p> <pre><code>r = urlopen("http://download.cathdb.info/cath/releases/all-releases/v4_2_0/cath-classification-data/cath-domain-list-v4_2_0.txt") r = BeautifulSoup(r, "lxml") r =...
<p>I think the code below can do what you want. Like mentioned in a comment by @alecxe, you don't need to use BeautifulSoup. This problem should be a problem to retrieve content from text files online and is answered in this <a href="https://stackoverflow.com/questions/1393324/in-python-given-a-url-to-a-text-file-what...
python-3.x|web-scraping|beautifulsoup
1
154
37,573,759
How to format print outputs of a text file?
<p>I have a text file called animal.txt.</p> <pre><code>1.1 Animal Name : Dog Animal Type : Mammal Fur : Yes Scale : No 1.2 Animal Name : Snake Animal Type : Reptile Fur : No Scale : Yes 1.3 Animal Name : Frog Animal Type : Amphibian Fu...
<p>Use <code>\t</code> between the items you are printing. So print <code>animal_name\t,</code> then so on through the rest of your code.</p> <p><code>with open('animal.txt', 'r') as fp: for line in fp: header = line.split(':')[0] if 'Animal Name' in header: animal_name = line.split(':')[1].strip() ...
python|python-2.7|python-3.x
-1
155
34,408,304
Django - How to filter a ListView by user without using CBV?
<p>Is it possible to do this? I've been looking for quite a while, but every solution I've seen involves subclassing <code>ListView</code> which I don't want to do. I'm sure there's a way to filter results by user without having to resort to class-based views, I just can't seem to find good information on it, am I mi...
<p>When you send a request to view you have already instance of the current user in the request:</p> <p><strong>views.py</strong></p> <pre><code>def my_not_cb_view(request): user = request.user games = Game.objects.filter(user=User.user) context = {'games': games, 'user': user} render_to_response(req...
python|django|listview|django-class-based-views
1
156
66,288,017
Fitting Log-normal distribution (Python plot)
<p>I am trying to fit a log-normal distribution to the histogram data. I've tried to follow examples of other questions here on the Stack Exchange but I'm not getting the fit, because in this case I have a broken axis. I already put the broken axis on that plot, I tried to prevent the numbers from overlapping on the ax...
<p>You're trying at the same time to do fancy graphs and fit. you help you with fit, graphs are secondary problem.</p> <p>First, use NumPy arrays for data, helps a lot. Second, your histogram function is denormalized.</p> <p>So if in the first of your programs I'll normalize freqs array</p> <pre><code>x=np.asarray([0.1...
python|matplotlib|graphics|distribution
1
157
7,583,022
Looking for method / module to determine the compiler which was used for building the CPython interpreter
<p>When I start the Python interpreter in command line mode I get a message saying which compiler was used for building it. Is there a way to get this information in Python ? I know I could start the interpreter with <code>subprocess.Popen</code> and parse the output, but I'm looking for an easier and more elegant meth...
<p>Use <a href="http://docs.python.org/library/platform.html#platform.python_compiler" rel="nofollow"><code>platform.python_compiler()</code></a>.</p>
python|cmake
6
158
16,405,881
Google AppEngine images API suddenly corrupting images
<p>We have been using AppEngine's images API with no problem for the past year. Suddenly in the last week or so the images API seems to be corrupting the image. We use the images API to do a few different operations but the one that seems to be causing the problem is that we do an images.rotation(0) on TIFF data to c...
<p>This turned out to be due to a recent change to the images API that introduced a bug which affected operations involving TIFF files, which has since been reverted. More information is in the original bug report.</p> <p><a href="https://code.google.com/p/googleappengine/issues/detail?id=9284" rel="nofollow">https://...
python|image|api|google-app-engine
1
159
31,801,400
Single line commands from Python
<p>I am trying to change certain entries in a file using python, which is possible in Perl with the command below , do we have anything similar in python, here the string in the file is replaced successfully. </p> <pre><code>[root@das~] perl -pi -w -e 's/unlock_time=1800/#unlock_time=1900/g;' /etc/pam.d/common-auth </...
<p>you need to add a print statement (with surrounding brackets for python 3.4; without for python 2.7).</p> <pre><code>[root@das~] python -c 'import os ; print(os.uname()[1])' </code></pre> <p>the other line could then be programmed this way (this will replace the input file!):</p> <pre><code>import fileinput for ...
perl|python-2.7
1
160
31,972,012
iMacros script questions timeout/errormsg/popupignore etc
<p>I have 1000+ URLs that I want to scrape to retrieve the title info from. After trying different things, I ultimately used iMacros scripts, which I don't know anything about. Nonetheless, I managed to make a script after reading guides.</p> <p>My script is working perfectly but has few problem and have some queries<...
<pre><code>SET !DATASOURCE urls.txt SET !DATASOURCE_LINE {{!LOOP}} SET !TIMEOUT_STEP 1 SET !TIMEOUT_PAGE 10 SET !ERRORIGNORE YES URL GOTO={{!COL1}} SET !ERRORIGNORE NO SET !EXTRACT_TEST_POPUP NO TAG POS=1 TYPE=TITLE ATTR=* EXTRACT=TXT SET dblSP " " SET !EXTRACT {{!COL1}}{{dblSP}}{{!EXTRACT}} SAVEAS TYPE=EXTRACT FOLDE...
javascript|php|python|url|imacros
1
161
31,706,090
Counting the number of men and women from a CSV file
<p>I want to count the number of male and female riders (which are coded as 1 or 2) in a CSV file, but my code does not seem to be working. This is my code:</p> <pre><code>Men = 0 Women = 0 import csv with open('dec2week.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: ...
<p>Use a Counter dict to do the counting:</p> <pre><code>import csv from collections import Counter from itertools import chain with open('dec2week.csv') as csvfile: next(csvfile) counts = Counter(chain.from_iterable(csv.reader(csvfile))) </code></pre> <p>Then just get the count using the key:</p> <pre><code...
python|csv
2
162
31,960,583
efficiency of Python's itertools.product()
<p>So I'm looking at different ways to compute the Cartesian product of <em>n</em> arrays, and I came across the rather elegant solution (here on SO) of using the following code:</p> <pre><code>import itertools for array in itertools.product(*arrays): print array </code></pre> <p>Looking at the <a href="h...
<p>You are absolutely right. That is, in the special case of two arrays input, both of the size <em>n</em>. In the general case of <em>k</em> arrays of the sizes <em>n</em>[<em>i</em>] for <em>i</em> in 1..<em>k</em> it will be O(Product of all <em>n</em>[<em>i</em>]).</p> <p>Why is this the case and why is there no...
python|algorithm|time-complexity|cartesian-product
2
163
32,003,294
Sentence tokenization for texts that contains quotes
<p>Code:</p> <pre><code>from nltk.tokenize import sent_tokenize pprint(sent_tokenize(unidecode(text))) </code></pre> <p>Output:</p> <pre><code>[After Du died of suffocation, her boyfriend posted a heartbreaking message online: "Losing consciousness in my arms, your breath and heartbeat became weaker and w...
<p>I'm not sure what is the desired output but I think you might need some paragraph segmentation before <code>nltk.sent_tokenize</code>, i.e.:</p> <pre><code>&gt;&gt;&gt; text = """After Du died of suffocation, her boyfriend posted a heartbreaking message online: "Losing consciousness in my arms, your breath and hear...
python|nlp|nltk|tokenize
6
164
40,656,103
TypeError for cookielib CookieJar cookie in requests Session
<p>I'm trying to use a cookie from a mechanize browser that I use to log in to a site in a requests Session, but whenever I make a request from the session I get a TypeError.</p> <p>I've made a convenience class for using an api exposed by the site (most of the actually useful code is removed, this is a small example)...
<p>You don't want to set the value of a single cookie in <code>cookies</code> to a <code>CookieJar</code>: it already <em>is</em> a <code>CookieJar</code>:</p> <pre><code>&gt;&gt;&gt; s = requests.Session() &gt;&gt;&gt; type(s.cookies) &lt;class 'requests.cookies.RequestsCookieJar'&gt; </code></pre> <p>You'll probabl...
python|cookies|python-requests
1
165
9,839,606
Region finding based on VTK polylines
<p>I have the following domain that is made up of VTK poly lines -- each line starts and ends at a 'x', may have many points, and is assigned a left and right flag to denote the region on the left and right of that line, determined if you we walking down the line from start to end.</p> <p><a href="https://i.stack.imgur...
<p>Every line on the perimeter of the sub-domain of interest (SDOI) must have the SDOI as one of its bordering domains. </p> <ul> <li>So you can flood fill (or expand a circle) in the domain that <code>rp</code> is in.</li> <li>Find what is the common domain neighboured by of all these lines.</li> <li>That is you SDOI...
python|vtk|raytracing
0
166
25,975,690
Python while loop not breaking when conditions are met
<p>I'm just wondering why the loop doesn't break when it meets those conditions and filters over into my other functions? I fixed it by doing a while true loop and just breaking in each if statement, but I'd like to know what is wrong with doing this way.</p> <p>def main_entrance():</p> <pre><code>print "\n\tYou are ...
<p>Of course it doesn't break, your condition can never be false</p> <pre><code>(choice != 1) or (choice != 2) or (choice != 3) </code></pre> <p>Think about it for a minute, any selection of choice cannot make this expression false.</p> <p>choice = 1</p> <pre><code>False or True or True --&gt; True </code></pre> <...
python
10
167
1,938,898
IronPython: Trouble building a WPF ShaderEffect
<p>I'm trying to build an extensible program where users, among other things, can build their own shader effects.</p> <p>Google searching got me this far;</p> <pre><code>class Test(ShaderEffect): inputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", type(Test()), 0) </code></pre> <p>But I stil...
<p>You will need to use Reflection to access protected memeber of .NET class - you don't have a Python subclass where you can access such member directly.</p> <p>Try somethink like this (I have't tested it):</p> <pre><code>inputPropertyType = ShaderEffect.GetType().GetMember( 'RegisterPixelShaderSamplerProperty',...
wpf|ironpython|shader
0
168
2,176,511
How do I convert a string to a buffer in Python 3.1?
<p>I am attempting to pipe something to a <code>subprocess</code> using the following line:</p> <pre><code>p.communicate("insert into egg values ('egg');"); TypeError: must be bytes or buffer, not str </code></pre> <p>How can I convert the string to a buffer?</p>
<p>The correct answer is:</p> <pre><code>p.communicate(b"insert into egg values ('egg');"); </code></pre> <p>Note the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:</p> <pre><code>value = open('thefile', 'rt').read() p.communicate(va...
python|python-3.x
12
169
1,667,341
Python: Removing characters from beginnings of sequences in fasta format
<p>I have sequences in fasta format that contains primers of 17 bp at the beginning of the sequences. And the primers sometimes have mismatches. I therefore want to remove the first 17 chars of the sequences, except from the fasta header.</p> <p>The sequences look like this:</p> <pre><code>&gt; name_name_number_etc S...
<p>If I understand correctly, you have to remove the primer only from the first 17 characters of a potentially multiline sequence. What you ask is a bit more difficult. Yes, a simple solution exists, but it can fail in some situations.</p> <p>My suggestion is: use <a href="http://biopython.org" rel="nofollow noreferre...
python|extract|character|sequences|fasta
1
170
32,274,199
Python ternary invalid syntax
<p>Writing a very simply function to mask all but the last 4 digits of a string with "#" characters. This is what I have so far:</p> <pre><code>def maskify(cc): res = "#" * (len(cc) - 4) if len(cc) &gt; 4 else return cc res += cc[len(cc) - 4:] return res print(maskify("12355644")) </code></pre> <p>If...
<p>You don't need a ternary expression at all here, just slice and use the length minus 4 times <code>"#'</code> to generate the prefix:</p> <pre><code>def maskify(cc): return "#" * (len(cc) - 4) + cc[-4:] </code></pre> <p>If the <code>len(cc) - 4</code> value is 0 or smaller the multiplication produces an empty ...
python|ternary-operator
3
171
32,334,516
ValueError: invalid literal for float(): Reading in Latitude and Longitude Data
<p>Given the following script to read in latitude, longitude, and magnitude data:</p> <pre><code>#!/usr/bin/env python # Read in latitudes and longitudes eq_data = open('lat_long') lats, lons = [], [] for index, line in enumerate(eq_data.readlines()): if index &gt; 0: lats.append(float(line.split(',')[0...
<p>It appears you have one or more lines of corrupt data in your input file. Your traceback says as much:</p> <pre><code>ValueError: invalid literal for float(): -18.381 -172.320 5.9 </code></pre> <p>Specifically what is happening:</p> <ol> <li>The line <code>-18.381 -172.320 5.9</code> is read in from eq_data.<...
python|matplotlib
5
172
13,953,639
check carriage return is there in a given string
<p>i,m reading some lines from a file and i'm checking whether each line has windows type of CRLF or not. If either '\n' or '\r' is absent in any line, it has to report an error. I tried with the below code, even if the line doesnt have '\r', it is not reporting any error</p> <pre><code>Open_file = open(File_Name,'r')...
<p>This isn't working because <code>Loop_Counter</code> is never adjusted at all; whatever the initial value is, it's not changing and the <code>while</code> loop either runs indefinitely or never passes. Your code is pretty unclear here; I'm not sure why you'd structure it that way.</p> <p>What you're suggesting wou...
python|python-2.7
8
173
34,429,694
Joining data sets in Spark
<p>What are different ways to join data in Spark?</p> <p>Hadoop map reduce provides - distributed cache, map side join and reduce side join. What about Spark?</p> <p>Also it will be great if you can provide simple scala and python code to join data sets in Spark.</p>
<p>Spark has two fundamental distributed data objects. Data frames and RDDs.</p> <p>A special case of RDDs in which case both are pairs, can be joined on their keys. This is available using <code>PairRDDFunctions.join()</code>. See: <a href="https://spark.apache.org/docs/1.5.2/api/scala/index.html#org.apache.spark.rdd...
python|scala|apache-spark
1
174
41,890,311
Dividing into sentences based on pattern
<p>I would like to divide a text into sentences based on a delimiter in python. However, I do not want to split them based on decimal points between numbers, or comma between numbers. How do we ignore them. </p> <p>For example, I have a text like below. </p> <pre><code>I am xyz.I have 44.44$. I would like, to give 44...
<p>This works for your example, although there's a trailing full stop (period) on the last part if that matters.</p> <pre><code>import re s = 'I am xyz. I have 44.44$. I would like, to give 44,44 cents to my friend.' for part in re.split('[.,]\s+', s): print(part) </code></pre> <p><strong>Output</strong></p> <...
python|regex
4
175
41,810,021
Downloading file using multithreading in python
<p>I am trying to put multiple files(ard 25k) into a zip file using multithreading in python cgi. I have written the script below, but somehow the response I get has content length 0 and there is no data in the response. This is my first time using multithreading in python. Is there anything I am missing in the code. D...
<p>The problem should be that <code>ZipFile.write()</code> (<code>ZipFile</code> in general) is not thread safe.</p> <p>You must somehow serialize thread access to the zip file. This is one way to do it (in Python 3):</p> <pre><code>ziplock = threading.Lock() def read_file(link): fname = link.split('/') fnam...
python|multithreading|python-2.7|cgi|python-multiprocessing
1
176
47,205,568
Mitmproxy, push own WebSocket message
<p>I inspect a HTTPS WebSocket traffic with <strong>Mitmproxy</strong>. Currently I can read/edit WS messages with:</p> <pre><code>class Intercept: def websocket_message(self, flow): print(flow.messages[-1]) def start(): return Intercept() </code></pre> <p>.. as attached script to Mitmproxy.</p> <p>...
<p>You can do this with <code>inject.websocket</code>:</p> <pre class="lang-py prettyprint-override"><code>from mitmproxy import ctx class Intercept: def websocket_message(self, flow): print(flow.messages[-1]) to_client = True ctx.master.commands.call(&quot;inject.websocket&quot;, flow, to_...
python|websocket|mitmproxy
1
177
57,532,917
Librosa Constant Q Transform (CQT) contains defects at the beginning and ending of the spectrogram
<p>Consider the following code</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from librosa import cqt s = np.linspace(0,1,44100) x = np.sin(2*np.pi*1000*s) fmin=500 cq_lib = cqt(x,sr=44100, fmin=fmin, n_bins=40) plt.imshow(abs(cq_lib),aspect='auto', origin='lower') plt.xlabel('Time Steps') plt.yl...
<p>I think you might want to try out <code>pad_mode</code> which is supported in <a href="https://librosa.github.io/librosa/generated/librosa.core.cqt.html" rel="nofollow noreferrer">cqt</a>. If you checkout the np.pad <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow noreferr...
python-3.x|signal-processing|librosa
4
178
57,327,277
ImportError when importing tensorflow
<p>I've recently installed TensorFlow using <code>pip install --upgrade tensorflow</code> then when I import it, I get the following error:</p> <pre><code>ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. Failed to load the native TensorFlow runtime. </code></pre>
<p>try this:</p> <pre><code>pip install setuptools </code></pre> <p>if wont change anything uninstall tensorflow and try (if you have conda env):</p> <pre><code>conda install tensorflow </code></pre>
python|tensorflow
0
179
11,626,793
How to run an attribute value through a regular expression after extracting via BeautifulSoup?
<p>I have a URL that I want to parse a part of, particularly the widgetid:</p> <pre><code>&lt;a href="http://www.somesite.com/process.asp?widgetid=4530"&gt;Widgets Rock!&lt;/a&gt; </code></pre> <p>I've written this Python (I'm a bit of a newbie at Python -- version is 2.7):</p> <pre><code>import re from bs4 import B...
<p>This question doesn't have anything to do with BeautifulSoup.</p> <p>The problem is that, as <a href="http://docs.python.org/library/re.html#re.match" rel="noreferrer">the documentation explains</a>, <code>match</code> only matches at the beginning of the string. Since the digits you want to find are at the end of ...
python|regex|url|unicode|beautifulsoup
5
180
11,681,014
Python Detect Alert
<p>I am trying to make my python script detect an alert box on a page</p> <pre><code>import urllib2 url = raw_input("Please enter your url: ") if urllib2.urlopen(url).read().find("&lt;script&gt;alert('alert');&lt;/script&gt;") == 0: print "Alert Detected!" </code></pre> <p>How can I make it detect the alert?</p>
<p><code>urllib2.urlopen(url).read().find("&lt;script&gt;alert('alert');&lt;/script&gt;") == 0</code> to <code>urllib2.urlopen(url).read().find("&lt;script&gt;alert('alert');&lt;/script&gt;") &gt;= 0</code></p>
python|urllib2
1
181
33,906,408
Count only the words in a text file Python
<p>I have to count all the words in a file and create a histogram of the words. I am using the following python code.</p> <pre><code>for word in re.split('[,. ]',f2.read()): if word not in histogram: histogram[word] = 1 else: histogram[word]+=1 </code></pre> <p>f2 is the file I am reading.I tr...
<pre><code>from collections import Counter from nltk.tokenize import RegexpTokenizer from nltk import bigrams from string import punctuation # preparatory stuff &gt;&gt;&gt; tokenizer = RegexpTokenizer(r'[^\W\d]+') &gt;&gt;&gt; my_string = "this is my input string. 12345 1-2-3-4-5. this is my input" # single words &g...
python|file|histogram
1
182
47,034,655
Python extract elements from Json string
<p>I have a Json string from which I'm able to extract few components like <code>formatted_address</code>,<code>lat</code>,<code>lng</code>, but I'm unable to extract feature(values) of other components like <strong>intersection, political, country, ...
<p>I would go for <code>json_normalize</code>, thought of one line answer but I dont think its possible i.e (Here I did only for px_val and py_val you can do similar things for other columns) </p> <pre><code>from pandas.io.json import json_normalize import pandas as pd import json with open('dat.json') as f: dat...
python|json|pandas|for-loop|dataframe
2
183
37,753,578
Interpreting numpy array obtained from tif file
<p>I need to work with some greyscale tif files and I have been using PIL to import them as images and convert them into numpy arrays:</p> <pre><code> np.array(Image.open(src)) </code></pre> <p>I want to have a transparent understanding of exactly what the values of these array correspond to and in particular, it ...
<p>A <a href="https://en.wikipedia.org/wiki/Tagged_Image_File_Format" rel="nofollow noreferrer">TIFF</a> is basically a computer file format for storing raster graphics images. It has a lot of <a href="https://reference.wolfram.com/language/ref/format/TIFF.html" rel="nofollow noreferrer">specs</a> and quick search on t...
python|image|numpy|tiff
1
184
37,919,319
Python reading Popen continuously (Windows)
<p>Im trying to <code>stdout.readline</code> and put the results (i.e each line, at the time of printing them to the terminal) on a <code>multiprocessing.Queue</code> for us in another .py file. However, the call:</p> <pre><code>res = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1 ) with res.stdout: f...
<p>As explained by @eryksun, and confirmed by your comment, the cause of the buffering is the use of <code>printf</code> by the C application.</p> <p>By default, printf buffers its output, but the output is flushed on newline or if a read occurs <strong>when the output is directed to a terminal</strong>. When the outp...
python|windows|io|subprocess
1
185
36,805,339
Django POST form validation to an another page
<p>I'm trying to make a TV show manager with Django and I have a problem with form validation and redirection. I have a simple page with a form where people can search a Tv show, and an other page where the result of the query is displaying. (for the query I'm using the API of TVDB I don't know if its useful) What I wa...
<p>Base on your description and views.py, you stay on step 2 that's why:</p> <ol> <li>User is on page '/step_1/'</li> <li>He submit form</li> <li>Because action param in form is point to '/step_2/', it's going to that url</li> <li>In view request.method == 'POST' is True, but form is not valid.</li> <li>You are render...
python|django|forms
1
186
36,919,825
Pandas dataframe in pyspark to hive
<p>How to send a pandas dataframe to a hive table?</p> <p>I know if I have a spark dataframe, I can register it to a temporary table using </p> <pre><code>df.registerTempTable("table_name") sqlContext.sql("create table table_name2 as select * from table_name") </code></pre> <p>but when I try to use the pandas dataFr...
<p>I guess you are trying to use pandas <code>df</code> instead of <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#module-pyspark.sql.functions" rel="noreferrer">Spark's DF</a>.</p> <p>Pandas DataFrame has no such method as <code>registerTempTable</code>.</p> <p>you may try to create Spark D...
python-2.7|pandas|hive|pyspark
5
187
48,766,723
Import error "No module named selenium" when returning to Python project
<p>I have a python project with Selenium that I was working on a year ago. When I came back to work on it and tried to run it I get the error <code>ImportError: No module named selenium</code>. I then ran <code>pip install selenium</code> inside the project which gave me <code>Requirement already satisfied: selenium in...
<p>Is it possible that you're using e.g. Python 3 for your project, and selenium is installed for e.g. Python 2? If that is the case, try <code>pip3 install selenium</code></p>
python|selenium|import
0
188
48,842,722
Python Virtualenv : ImportError: No Module named Zroya
<p>I was trying to work with python virtualenv on the <a href="https://github.com/malja/zroya" rel="nofollow noreferrer">Zroya python wrapper around win32 API</a>. Although I did installed the modules using pip, and although they are shown in cli using the command</p> <pre><code> pip freeze </code></pre> <p>,when ...
<p>Installing <code>zroya</code> should solve your problem.</p> <p>Installation instructions: <a href="https://pypi.python.org/pypi/zroya" rel="nofollow noreferrer">https://pypi.python.org/pypi/zroya</a></p>
python|virtualenv
0
189
66,972,885
Package and module import in python
<p>Here is my folder structure:</p> <pre><code>|sound |-__init__.py |-model |-__init__.py |-module1.py |-module2.py |-simulation |-sim.py </code></pre> <p>The file module1.py contains the code:</p> <pre><code>class Module1: def __init__(self,mod): self.mod = mod </code></pre> <p>The file module2.py ...
<h3>The simple FIX :</h3> <ul> <li>Move <code>sim.py</code> one folder up into sound</li> <li>Try <code>import module2</code></li> <li><code>sound_1 = module2.Module2()</code></li> </ul>
python|python-3.x|module|package
1
190
4,496,882
Error while trying to parse a website url using python . how to debug it?
<pre><code>#!/usr/bin/python import json import urllib from BeautifulSoup import BeautifulSoup from BeautifulSoup import BeautifulStoneSoup import BeautifulSoup def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;%s' % query ...
<blockquote> <p>What is the wrong in this code ?</p> </blockquote> <p>Your indentation is all wonky in the for loop, and this line:</p> <pre><code>import BeautifulSoup </code></pre> <p>should be deleted, as it masks this earlier import:</p> <pre><code>from BeautifulSoup import BeautifulSoup </code></pre>
python
1
191
69,492,040
Calculating length between 2 dates using Tkinter calendar
<p>I am trying to create a Tkinter application where the user selects a date in a calendar and then presses a <kbd>button</kbd> and a <code>label</code> then displays the number of days between the current date and the date they have selected. I have figured out how to calculate the number of days between 2 set dates h...
<p>Add <code>date_pattern=&quot;m/d/y&quot;</code> to <code>Calender(...)</code>:</p> <pre class="lang-py prettyprint-override"><code>cal = Calendar(root, date_pattern=&quot;m/d/y&quot;, background=&quot;#99cbd8&quot;, disabledbackground=&quot;blue&quot;, bordercolor=&quot;#99cbd8&quot;, headersbackground=&quot;light b...
python|date|datetime|tkinter
1
192
73,641,447
How to modify single object inside dict values stored as a set?
<p>I have a dictionary which represents graph. Key is Node class and values are set of Nodes. So it has this structure: <code>dict[Node] = {Node, Node, Node}</code></p> <pre><code>class Node: def __init__(self, row, column, region): self.id = f'{str(row)}-{str(column)}' self.region = region self.visited = ...
<p>I've figured it out. I was storing <strong>different</strong> Node objects as key and what was in values set in my dictionary. I created context of all Nodes and get Node from there by its id.</p> <pre><code>def get_node_from_context(self, row, column, region): node = Node(row, column, region) if no...
python|python-3.x|dictionary|set
0
193
73,623,323
I wrote a code that should identify which of the elements of the sequence are equal to the sum of the elements of two different arrays, but it's wrong
<p>I am given two int arrays of different lentgh. Also I'm given a sequence of integers. I need to write a code, that prints &quot;YES&quot; for each element of the sequence if it can be obtained as a result of the sum of any element from first array and any element in second one. Otherwise it must print &quot;NO&quot;...
<p>To make your solution work you have to break out of the second <code>for</code> loop as well:</p> <pre><code>for c in C: flag = False for a in A: for b in B: if c == a + b: flag = True break if flag: break print('YES' if flag else 'N...
python
0
194
64,329,580
How to add samesite=None in the set_cookie function django?
<p>I want to add <code>samesite</code> attribute as <code>None</code> in the <code>set_cookie function</code></p> <p>This is the code where I call the <code>set_cookie function</code></p> <pre><code>redirect = HttpResponseRedirect( '/m/' ) redirect.set_cookie( 'access_token', access_token, max_age=60 * 60 ) </code></pr...
<p>You can use this library to change the flag if you're using django2.x or older: <a href="https://pypi.org/project/django-cookies-samesite/" rel="nofollow noreferrer">https://pypi.org/project/django-cookies-samesite/</a></p> <p>If you're using django3.x, it should be built-in</p>
python|django|cookies|django-views|middleware
1
195
49,936,387
NotImplementedError: data_source='iex' is not implemented
<p>I am trying to get some stock data through pandas_datareader in jupyter notebook. I was using google, but that does not work anymore, so I am using iex.</p> <pre><code>import pandas_datareader.data as web import datetime start = datetime.datetime(2015,1,1) end = datetime.datetime(2017,1,1) facebook = web.DataReader...
<p>Many DataReader sources are deprecated, see updated list <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#remote-data-access" rel="nofollow noreferrer">here</a>.</p> <p>Many now require API key, IEX is one of them: </p> <blockquote> <p>Usage of all IEX readers now requires an <a href=...
pandas|pandas-datareader|elixir-iex
1
196
66,613,380
Downloading QtDesigner for PyQt6 and converting .ui file to .py file with pyuic6
<p>How do I download QtDesigner for PyQt6? If there's no QtDesigner for PyQt6, I can also use QtDesigner of PyQt5, but how do I convert this .ui file to .py file which uses PyQt6 library instead of PyQt5?</p>
<p>As they point out you can use pyuic6:</p> <pre><code>pyuic6 -o output.py -x input.ui </code></pre> <p>but in some cases there are problems in that the command is not found in the CMD/console, so the command can be used through python:</p> <pre><code>python -m PyQt6.uic.pyuic -o output.py -x input.ui </code></pre>
python|pyqt5|qt-designer|pyqt6
7
197
64,847,851
Reading a text file and replacing it to value in dictionary
<p>I have a dictionary made in python. I also have a text file where each line is a different word. I want to check each line of the text file against the keys of the dictionary and if the line in the text file matches the key I want to write that key's value to an output file. Is there an easy way to do this. Is this ...
<p>you can try:</p> <pre><code>for line in all_lines: for val in dic: if line.count(val) &gt; 0: print(dic[val]) </code></pre> <p>this will look through all lines in the file and if the line contains a letter from dic, then it will print the items associated with that letter in the dictionary (y...
python|dictionary
0
198
65,287,582
How to move just two columns of pandas dataframe to specific positions?
<p>I have a dataset of 100 columns like follows:</p> <pre><code>citycode AD700 AD800 AD900 ... AD1980 countryname cityname </code></pre> <p>I want the output dataframe to have columns as follows:</p> <pre><code>citycode countryname cityname AD700 AD800 AD900 ... AD1980 </code></pre> <p>I can't use code like</p> <pre><...
<p>One of possible solutions is:</p> <pre><code>df = df[['citycode', 'countryname', 'cityname'] + list(df.loc[:, 'AD700':'AD1980'])] </code></pre> <p>Note that you compose the list of column names from:</p> <ul> <li>a &quot;by name&quot; list (first 3),</li> <li>a &quot;by range&quot; list (all other columns).</li> </u...
python|python-3.x|pandas|numpy|dataframe
1
199
72,051,927
How to search via Enums Django
<p>I'm trying to a write a search function for table reserving from a restaurant, I have a restaurant model:</p> <pre><code>class Restaurant(models.Model): &quot;&quot;&quot; Table Restaurant ======================= This table represents a restaurant with all necessary information. &quot;&quot;&quo...
<p>Instead of using a list of tuples I would recommend extending the <code>IntegerChoices</code> or <code>TextChoices</code> classes provided by Django. Here's an example of how you can use <code>IntegerChoices</code>:</p> <pre><code>&gt;&gt;&gt; class KitchenType(models.IntegerChoices): ... TURKISH = 1 ... ITA...
python|django
1