title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to create lists from every item of an existing list in python 2.7.11?
37,633,841
<p>I am trying to generate lists from the elements of a list in python. For example: there is a list with the following information: <code>list=['AB4', 'AB3','AC3', 'BC4', 'BC5']</code> This is the exact format of the elements of the list. I suppouse to create list for every element, separate for the letters (consi...
3
2016-06-04T18:52:44Z
37,633,990
<p>How about this,</p> <pre><code>import itertools import operator l = ['AB4', 'AB3','AC3', 'BC4', 'BC5'] lists = [(s[:2], s[2]) for s in l] # [('AB', '4'), ('AB', '3'), ('AC', '3'), ('BC', '4'), ('BC', '5')] results = dict() for name, group in itertools.groupby(sorted(lists, key=operator.itemgetter(0)), key=o...
2
2016-06-04T19:06:42Z
[ "python", "list" ]
SQL Alchemy Filter rows based on the values contained in cells of other column
37,633,845
<p>I am new to python and SQLALCHEMY, and I came across this doubt, whether can we filter rows of the table based on cell values of the column of same table. example:</p> <pre><code>Sbranch=value result=Transaction.query.filter(Transaction.branch==Sbranch) .order_by(desc(Transaction.id)).lim...
1
2016-06-04T18:52:53Z
37,634,050
<p>You can optionally add the filter based on the value of <code>SBranch</code></p> <pre><code>query = Transaction.query if SBranch != 0: query = query.filter(Transaction.branch == SBranch) result = query.order_by(Transaction.id.desc()).limit(50).all() </code></pre>
3
2016-06-04T19:11:33Z
[ "python", "database", "flask", "sqlalchemy", "flask-sqlalchemy" ]
SQL Alchemy Filter rows based on the values contained in cells of other column
37,633,845
<p>I am new to python and SQLALCHEMY, and I came across this doubt, whether can we filter rows of the table based on cell values of the column of same table. example:</p> <pre><code>Sbranch=value result=Transaction.query.filter(Transaction.branch==Sbranch) .order_by(desc(Transaction.id)).lim...
1
2016-06-04T18:52:53Z
37,634,215
<p>I think i found the solution, it's not the best but will reduce the work for the developers(not the processor).</p> <pre><code>Sbranch=value branches=[] if Sbranch==0: # Append all the values into the array for which the rows are filtered # for example: branches=[1,2,4,7,3,8] else: branches.append(branc...
-1
2016-06-04T19:29:56Z
[ "python", "database", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Django Forms cannot render Radio Buttons
37,633,882
<p>Sorry I am very new to Django. I read a lot of answers but cannot make it work. I am missing something</p> <p>This is my forms.py</p> <pre><code> from django import forms from .models import Post from django.utils.translation import gettext as _ class EventsForm(forms.ModelForm): class Meta:...
1
2016-06-04T18:56:58Z
37,634,203
<p>This works for me!</p> <pre><code> class EventsForm(forms.ModelForm): CHOICES=(('select1','select 1'), ('select2','select 2')) type_id = forms.TypedChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model = Post fields = ('title', 'type_id', 'post_date', ) </code...
0
2016-06-04T19:28:22Z
[ "python", "django", "django-forms" ]
Django Forms cannot render Radio Buttons
37,633,882
<p>Sorry I am very new to Django. I read a lot of answers but cannot make it work. I am missing something</p> <p>This is my forms.py</p> <pre><code> from django import forms from .models import Post from django.utils.translation import gettext as _ class EventsForm(forms.ModelForm): class Meta:...
1
2016-06-04T18:56:58Z
37,634,274
<p>You're confusing form fields and widgets. The things you specify in the <code>widgets</code> dict have to actually be widgets.</p> <pre><code> widgets = { 'title': forms.TextInput(attrs={'placeholder': _('form-title')}), 'type_id': forms.RadioSelect(choices=CHOICES), } </code></pre>
1
2016-06-04T19:37:53Z
[ "python", "django", "django-forms" ]
pyodbc TypeError with Unicode connection string
37,633,914
<p>I am trying to connect to a SQL Server database with the following code:</p> <pre><code>import pyodbc path = 'DRIVER=(SQL Server); SERVER = СВЕТЛАНА-ПК\SQLEXPRESS; DATABASE = test_db; UID = sveta; PWD = 1111' connect = pyodbc.connect(path) </code></pre> <p>and I receive this error:</p> <blockquote> <p...
1
2016-06-04T18:59:26Z
37,643,641
<p>I was able to recreate your issue when using</p> <pre class="lang-none prettyprint-override"><code>DRIVER=(SQL Server) </code></pre> <p>in the connection string. When I changed it to use braces <code>{}</code> instead of parentheses <code>()</code> ...</p> <pre class="lang-none prettyprint-override"><code>DRIVE...
1
2016-06-05T15:34:47Z
[ "python", "typeerror", "connect", "pyodbc" ]
UnicodeEncodeError when reading a file
37,633,927
<p>I am trying to read from rockyou wordlist and write all words that are >= 8 chars to a new file.</p> <p>Here is the code - </p> <pre><code>def main(): with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w') as out_file: for line in in_file: if len(line.rstrip()) &lt; ...
1
2016-06-04T19:01:03Z
37,634,921
<p>Your <code>UnicodeEncodeError: 'charmap'</code> error occurs during <em>writing</em> to <code>out_file</code> (in <code>print()</code>).</p> <p>By default, <code>open()</code> uses <code>locale.getpreferredencoding()</code> that is ANSI codepage on Windows (such as <code>cp1252</code>) that can't represent all Unic...
0
2016-06-04T20:53:58Z
[ "python", "python-3.x", "unicode", "character-encoding" ]
Get list of parallel paths in a directed graph
37,633,941
<p>I'm in need of an algorithm to find sets of all parallel paths in a directed graph. Here is a visual representation of an example I use for testing.</p> <p><a href="http://i.stack.imgur.com/3FOza.png" rel="nofollow"><img src="http://i.stack.imgur.com/3FOza.png" alt="visual representation of example directed graph w...
2
2016-06-04T19:02:08Z
37,634,681
<p>If parallel paths with branches are considered, then this problem would be NP-complete (see <a href="http://assert-false.net/callcc/Guyslain/Works/disjoint_paths" rel="nofollow">vertex-disjoint paths problem</a>).</p> <p>However, since offshoots are not considered, the problem is straightforward:</p> <ol> <li>Loop...
2
2016-06-04T20:25:08Z
[ "python", "algorithm", "networkx", "directed-graph" ]
Get list of parallel paths in a directed graph
37,633,941
<p>I'm in need of an algorithm to find sets of all parallel paths in a directed graph. Here is a visual representation of an example I use for testing.</p> <p><a href="http://i.stack.imgur.com/3FOza.png" rel="nofollow"><img src="http://i.stack.imgur.com/3FOza.png" alt="visual representation of example directed graph w...
2
2016-06-04T19:02:08Z
37,634,890
<p>There's a built-in function to list all simple paths between two vertices. This uses it to list all sets of paths between any two vertices:</p> <pre><code>def get_parallel_paths(G): return [list(nx.all_simple_paths(G, i, j)) for i in G.nodes_iter() for j in G.nodes_iter() if i != j and nx.has_path(G, i, j)] </c...
2
2016-06-04T20:50:29Z
[ "python", "algorithm", "networkx", "directed-graph" ]
Python : Locking text file on NFS
37,633,951
<p>I have a file <code>results.txt</code> on a server which is accessed by multiple VMs through NFS. A process runs on each of these VMs which reads the <code>results.txt</code> file and modifies it. If two processes, <code>A</code> and <code>B</code>, read the file at the same time, then modification of either A or B ...
2
2016-06-04T19:03:02Z
38,239,456
<p>I found <a href="https://pythonhosted.org/flufl.lock/" rel="nofollow">flufl.lock</a> most suited for my requirement. </p> <p>Quoting the author from project <a href="https://launchpad.net/flufl.lock" rel="nofollow">page</a>:</p> <blockquote> <p>[...] O_EXCL is broken on NFS file systems, programs which rely on ...
0
2016-07-07T07:09:28Z
[ "python", "python-2.7", "nfs", "file-locking", "fcntl" ]
Why is not TextBlob using / detecting the negation?
37,634,016
<p>I am using TextBlob to perform a sentiment analysis task. I have noticed that TextBlob is able to detect the negation in some cases while in other cases not. </p> <p>Here are two simple examples</p> <pre><code>&gt;&gt;&gt; from textblob.sentiments import PatternAnalyzer &gt;&gt;&gt; sentiment_analyzer = PatternAn...
2
2016-06-04T19:08:33Z
37,634,362
<p><em>(edit: my old answer was more about general classifiers and not about PatternAnalyzer)</em></p> <p>TextBlob uses in your code the "PatternAnalyzer". Its behaviour is briefly discribed in that document: <a href="http://www.clips.ua.ac.be/pages/pattern-en#parser" rel="nofollow">http://www.clips.ua.ac.be/pages/pat...
1
2016-06-04T19:46:40Z
[ "python", "sentiment-analysis", "textblob" ]
How to verify if jpg shows on page using Selenium?
37,634,076
<p>Using python, selenium, and firefox. I am clicking a link on a homepage and it leads directly to a JPG file that loads. I just want to verify that the image loads. The HTML of the image is this:</p> <pre><code>&lt;img src="https://www.treasury.gov/about/organizational-structure/ig/Agency%20Documents/Organizational%...
2
2016-06-04T19:14:58Z
37,634,369
<p>Appending the <code>alt</code> value should work in xpath, would suggest you to change the dictionary to :</p> <pre><code>= dict(OrganizationalChartPictureXpath = "//img[@alt='https://www.treasury.gov/about/organizational-structure/ig/Agency%20Documents/Organizational%20Chart.jpg' and contains(@src, 'Chart.jpg')]" ...
1
2016-06-04T19:47:24Z
[ "python", "selenium", "firefox" ]
Approximating non-linear function with NN using Theano
37,634,110
<p>I have designed a neural network using Theano, to approximate mathematical multiple functions. But I, haven't been able to approximate non-linear functions such as: 2x/x+3, etc. But the network performs well on linear functions. </p> <p>I am using 1 hidden layer, with 2 neurons. I have tried increasing neurons in t...
2
2016-06-04T19:18:20Z
37,634,490
<p>Your code is not a neural network... at least not in the meaningfull sense - it is just a linear model. There is no point in having a hidden layer, when you do not have any nonlinear activation function, as everything you can model is just a linear function of your input. Add nonlinearities, add their respective gra...
2
2016-06-04T20:01:29Z
[ "python", "neural-network", "theano" ]
Summing datetime values from a flat file
37,634,356
<p>I am trying to sum then average time values that are stored in a flat file. I am getting an error when I loop through time values.</p> <p><strong>The error:</strong></p> <pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; File "/usr/lib64/python2.7/_strptime.py", l...
1
2016-06-04T19:46:10Z
37,638,409
<p>There was \r\n (carriage return and new line) appended in the <code>response_time</code> variable which caused this error. So I used <code>response_time.strip('\n\r')</code> to remove them. refer (1)</p> <p>Then there was a timedelta attribute error came. </p> <blockquote> <p>AttributeError: 'datetime.datetime'...
1
2016-06-05T04:19:09Z
[ "python", "python-2.7", "datetime" ]
Matplotlib scatterplot axis autoscale fails for small data values
37,634,370
<p>When using Matplotlib's <code>scatterplot</code>, sometimes autoscaling works, sometimes not.</p> <p>How do I fix it?</p> <p>As in the example provided in the bug report, this code works:</p> <pre><code>plt.figure() x = np.array([0,1,2,3]) x = np.array([2,4,5,9]) plt.scatter(x,y) </code></pre> <p>But when using ...
0
2016-06-04T19:47:24Z
37,634,371
<p>In at least Matplotlib 1.5.1, there is a bug where autoscale fails for small data values, as reported <a href="https://github.com/matplotlib/matplotlib/issues/6015" rel="nofollow">here</a>.</p> <p>The workaround is to use <code>.set_ylim(bottom,top)</code> (<a href="http://matplotlib.org/api/axes_api.html" rel="nof...
0
2016-06-04T19:47:24Z
[ "python", "matplotlib" ]
HttpResponseRedirect with reverse not passing parameters
37,634,486
<p>In one definition of my view I am doing this</p> <pre><code>return HttpResponseRedirect(reverse('home'),{"fail":"true"}) </code></pre> <p>then the destination receiving definition in a view does this</p> <pre><code>def Validate(request): rslt = request.GET.get("fail", "False") #---&gt;fail is always false ...
1
2016-06-04T20:00:49Z
37,634,596
<p>It it because you are asking for <code>fail</code> from <code>GET</code> but you are not passing anything in GET. </p> <p>you need: </p> <pre><code>return HttpResponseRedirect('%s?fail=%s' % (reverse('home'), True)) </code></pre> <p>then you can catch it like: </p> <pre><code>request.GET.get("fail", False) </cod...
0
2016-06-04T20:14:26Z
[ "python", "django" ]
HttpResponseRedirect with reverse not passing parameters
37,634,486
<p>In one definition of my view I am doing this</p> <pre><code>return HttpResponseRedirect(reverse('home'),{"fail":"true"}) </code></pre> <p>then the destination receiving definition in a view does this</p> <pre><code>def Validate(request): rslt = request.GET.get("fail", "False") #---&gt;fail is always false ...
1
2016-06-04T20:00:49Z
37,634,751
<p>The <code>args</code> and <code>kwargs</code> passed to the <code>HttpResponseRedirect</code> constructor</p> <pre><code>def __init__(self, redirect_to, *args, **kwargs): ... </code></pre> <p>are not being used to construct a <code>QueryDict</code> (get or post). You are initialising a response here, not a req...
1
2016-06-04T20:33:56Z
[ "python", "django" ]
HttpResponseRedirect with reverse not passing parameters
37,634,486
<p>In one definition of my view I am doing this</p> <pre><code>return HttpResponseRedirect(reverse('home'),{"fail":"true"}) </code></pre> <p>then the destination receiving definition in a view does this</p> <pre><code>def Validate(request): rslt = request.GET.get("fail", "False") #---&gt;fail is always false ...
1
2016-06-04T20:00:49Z
37,634,915
<p>You need give a second parameter at reverse function... as de arguments... this works well for me!!!</p> <pre><code> return reverse('home', args='true') </code></pre>
0
2016-06-04T20:53:09Z
[ "python", "django" ]
Apply function to an array of tuples
37,634,502
<p><strong>I have a function that I would like to apply to an array of tuples</strong> and I am wondering if there is a clean way to do it. </p> <p>Normally, I could use <code>np.vectorize</code> to apply the function to each item in the array, however, in this case "each item" is a tuple so numpy interprets the arra...
1
2016-06-04T20:03:34Z
37,634,742
<p><em>array_of_tuples1</em> and <em>array_of_tuples2</em> are not actually arrays of tuples, but just 3- and 2-dimensional arrays of integers:</p> <pre><code>In [1]: array_of_tuples1 = np.array([ ...: [(1,2,3),(2,3,4),(5,6,7)], ...: [(7,2,3),(2,6,4),(5,6,6)], ...: [(8,2,3),(2,5,4),(7,...
3
2016-06-04T20:32:52Z
[ "python", "arrays", "numpy", "vector" ]
Apply function to an array of tuples
37,634,502
<p><strong>I have a function that I would like to apply to an array of tuples</strong> and I am wondering if there is a clean way to do it. </p> <p>Normally, I could use <code>np.vectorize</code> to apply the function to each item in the array, however, in this case "each item" is a tuple so numpy interprets the arra...
1
2016-06-04T20:03:34Z
37,635,056
<p>The other answer above is certainly correct, and probably what you're looking for. But I noticed you put the word "clean" into your question, and so I'd like to add this answer as well. </p> <p>If we can make the assumption that all the tuples are <code>3</code> element tuples (or that they have some constant numbe...
3
2016-06-04T21:10:28Z
[ "python", "arrays", "numpy", "vector" ]
Apply function to an array of tuples
37,634,502
<p><strong>I have a function that I would like to apply to an array of tuples</strong> and I am wondering if there is a clean way to do it. </p> <p>Normally, I could use <code>np.vectorize</code> to apply the function to each item in the array, however, in this case "each item" is a tuple so numpy interprets the arra...
1
2016-06-04T20:03:34Z
37,636,191
<p>If you are serious about the <code>tuples</code> bit, you could define a structured dtype.</p> <pre><code>In [535]: dt=np.dtype('int,int,int') In [536]: x1 = np.array([ [(1,2,3),(2,3,4),(5,6,7)], [(7,2,3),(2,6,4),(5,6,6)], [(8,2,3),(2,5,4),(7,6,7)], ], dtype=dt) In [537]: x1 Out[537]: ...
1
2016-06-05T00:02:56Z
[ "python", "arrays", "numpy", "vector" ]
How to extract numbers from the website
37,634,539
<p>I've got a code: </p> <pre><code>import urllib.request from bs4 import * soup = BeautifulSoup(urllib.request.urlopen("http://biznes.pl/waluty/profile/fixing-nbp/jen-japonia,821,0,30,profile-waluta-nbp.html"), "lxml") price = soup.find_all("div", {"class":"cena"}) print(price) </code></pre> <p>The result is:</p> ...
0
2016-06-04T20:07:32Z
37,634,600
<p>In this case, you can do the following:</p> <pre><code>p = price[0].string.strip() </code></pre> <p>to get the string "3,6178"</p> <p>Note, however, that you will also want to get rid of the comma to do calculations:</p> <pre><code>p = int(p.replace(",", "")) </code></pre> <p>Edit: if (as pointed out by Padraic...
-1
2016-06-04T20:14:55Z
[ "python", "numbers", "beautifulsoup" ]
How to extract numbers from the website
37,634,539
<p>I've got a code: </p> <pre><code>import urllib.request from bs4 import * soup = BeautifulSoup(urllib.request.urlopen("http://biznes.pl/waluty/profile/fixing-nbp/jen-japonia,821,0,30,profile-waluta-nbp.html"), "lxml") price = soup.find_all("div", {"class":"cena"}) print(price) </code></pre> <p>The result is:</p> ...
0
2016-06-04T20:07:32Z
37,641,168
<p>You need to take the locale into account, <code>36178</code> is not necessarily <code>3,6178</code> depending on the locale, if you want a single element you should also use <code>find</code>:</p> <pre><code>In [1]: import urllib.request In [2]: import locale In [3]: locale.setlocale(locale.LC_ALL, 'de_DE') Out[...
0
2016-06-05T11:11:25Z
[ "python", "numbers", "beautifulsoup" ]
Python EOL issue in text file
37,634,553
<p>G'day all, I have a text file that was extracted from comments field of a Geographic Information Systems (GIS) app (name withheld). I need to parse this text and produce a pretty report. The text has individual lines that are terminated with Carriage Return/Linefeed (x0D/x0A). However, some of the lines contain a ne...
0
2016-06-04T20:09:37Z
37,635,621
<p>You can try to make a string out of a whole file and then split it by '\r\n':</p> <pre><code>input_data = original_file.read().split('\r\n') for line in input_data: ... </code></pre> <p>But remember it's not an efficient method for big files.</p>
1
2016-06-04T22:26:26Z
[ "python", "windows", "text", "eol", "linefeed" ]
Placing variables inside a python list comprehension
37,634,607
<p>the following two loop-constructs are basically the same. I just can't figure out how to insert two variables <code>start = start+2</code> and <code>end = end+2</code> inside the first syntax. Thank you</p> <p>FIRST CONSTRUCT (list comprehension):</p> <pre><code>start = 1 end = 3 clips = [ImageClip(os.path.jo...
2
2016-06-04T20:15:52Z
37,634,653
<p>There are many way to do it. For instance, you can do something such as: </p> <pre><code>clips = [ ImageClip(os.path.join(folder,pic)) .resize(width=w*9.3/16) .set_start(index*2+1) .set_end(index*2+3) .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center")) for index, pic i...
3
2016-06-04T20:21:59Z
[ "python" ]
How would I install numpy library on Coding Ground?
37,634,645
<p>I tried to install neurolab, termcolor libraries on Coding Ground for python into the working folder using</p> <pre><code>pip install --target=. neurolab pip install --target=. termcolor </code></pre> <p>and they both worked.<br> But when I tried:</p> <pre><code>pip install --target=. numpy </code></pre> <p>it d...
4
2016-06-04T20:20:45Z
37,693,072
<p>Regarding <strong>neurolab</strong> and <strong>termcolor</strong>, they both are pure python modules.</p> <p>Pure Python i.e. modules are written using only python. These libraries are platform independent and easily distributable.</p> <p>for <a href="https://pypi.python.org/pypi/numpy" rel="nofollow">numpy</a>, ...
6
2016-06-08T04:10:10Z
[ "python", "numpy", "libraries", "neurolab", "termcolor" ]
Converting binary to float
37,634,660
<p>I have a function which encode float number to binary. I split float number by "." and convert both parts to binary. After i concatenate results. Left part I encode by simple convert <code>bin(left_part)</code>. Right part I encode by next algorithm:</p> <pre><code> while count: val *= 2 if val &...
0
2016-06-04T20:22:44Z
37,635,115
<p>If you have your number in binary as a string and you only want to interpret it as the part to the right of the decimal point, you can use this function:</p> <pre><code>def binToFloatAfterPoint(b): exp = -1 result = 0 for digit in b: if digit != "0": result += math.pow(int(digit)*2,e...
1
2016-06-04T21:18:36Z
[ "python", "binary", "floating-point" ]
Converting binary to float
37,634,660
<p>I have a function which encode float number to binary. I split float number by "." and convert both parts to binary. After i concatenate results. Left part I encode by simple convert <code>bin(left_part)</code>. Right part I encode by next algorithm:</p> <pre><code> while count: val *= 2 if val &...
0
2016-06-04T20:22:44Z
37,635,180
<p>Here is a version which uses the built-in <code>int</code> function. It is based on the fact that in any base the decimal part of a decimal expansion is the numerator of a fraction where the denominator is a power of the base. The power in question is easily inferred from the length of the decimal part.</p> <pre><c...
0
2016-06-04T21:26:59Z
[ "python", "binary", "floating-point" ]
List Comprehension and "not in" keywords
37,634,691
<p>Working on some basic programming exercises but was somewhat confused to find that the following code snippets do not return the same values. The list comprehension syntax seems to almost ignore the "not in" keywords I used on the list being created from the list comprehension itself. Is this behavior not allowed? T...
1
2016-06-04T20:26:59Z
37,634,773
<p>In the list comprehensions version, <code>if num not in my_lst</code> always returns <code>True</code> because <code>my_lst</code> is <code>[]</code> at that time.</p> <pre><code># List Comprehension def array123(lst): my_lst = [] my_lst = [num for num in lst if num not in my_lst # always ...
1
2016-06-04T20:36:46Z
[ "python", "list-comprehension" ]
List Comprehension and "not in" keywords
37,634,691
<p>Working on some basic programming exercises but was somewhat confused to find that the following code snippets do not return the same values. The list comprehension syntax seems to almost ignore the "not in" keywords I used on the list being created from the list comprehension itself. Is this behavior not allowed? T...
1
2016-06-04T20:26:59Z
37,634,814
<p>Your condition <code>not in my_list</code> will be always <code>True</code>. Since you're creating unique elements you should use a <code>set</code> comprehension.</p> <pre><code>my_set = {num for num in lst if num == 1 or num == 2 or num == 3} </code></pre> <p>Your <code>if-or</code> conditions can be reduced to:...
1
2016-06-04T20:41:10Z
[ "python", "list-comprehension" ]
List Comprehension and "not in" keywords
37,634,691
<p>Working on some basic programming exercises but was somewhat confused to find that the following code snippets do not return the same values. The list comprehension syntax seems to almost ignore the "not in" keywords I used on the list being created from the list comprehension itself. Is this behavior not allowed? T...
1
2016-06-04T20:26:59Z
37,634,818
<p>Or use sets:</p> <pre><code>#!python3 _SET123 = {1,2,3} def array123(iterable): return set(i for i in iterable if i in _SET123) == _SET123 for x in "123", (1,2,2,2), [1,2,3], {1:"one", 3:"two", 2:"three"}: print(x, array123(x)) </code></pre>
1
2016-06-04T20:41:43Z
[ "python", "list-comprehension" ]
Python while loop not working as expected
37,634,760
<p>When I type "no" into the input I expected it to add 1 to "x", therefore ending the loop, but what happens is that it ignores it and does not add 1 x. Here is the code.</p> <pre><code>x = 1 password = "" while x == 1: # imagine there is some code here which works ans1 = input("\n\nTest a new passw...
2
2016-06-04T20:35:05Z
37,634,792
<p>You should use or that way. </p> <pre><code>if ans1 == ("Y" or "YES"): </code></pre> <p>Can be replaced with: </p> <pre><code>if ans1 == "Y" or ans1 == "YES": </code></pre> <p>Or: </p> <pre><code>if ans1 in ("Y", "YES"): </code></pre> <p>The bug comes from the definition of the <code>or</code> operator. When...
5
2016-06-04T20:38:42Z
[ "python", "loops", "while-loop" ]
Python while loop not working as expected
37,634,760
<p>When I type "no" into the input I expected it to add 1 to "x", therefore ending the loop, but what happens is that it ignores it and does not add 1 x. Here is the code.</p> <pre><code>x = 1 password = "" while x == 1: # imagine there is some code here which works ans1 = input("\n\nTest a new passw...
2
2016-06-04T20:35:05Z
37,634,808
<p>Well, there is a problem with this line: ans1 == ("Y" or "YES")</p> <p>It is not similar to this line:</p> <pre><code>ans1 == "Y" or ans1 == "YES" </code></pre> <p>The second one is right, the first one is called <code>null coalescing</code>. That's not what you want. Basically, the idiom <code>x or y</code> ...
1
2016-06-04T20:40:37Z
[ "python", "loops", "while-loop" ]
Python while loop not working as expected
37,634,760
<p>When I type "no" into the input I expected it to add 1 to "x", therefore ending the loop, but what happens is that it ignores it and does not add 1 x. Here is the code.</p> <pre><code>x = 1 password = "" while x == 1: # imagine there is some code here which works ans1 = input("\n\nTest a new passw...
2
2016-06-04T20:35:05Z
37,635,101
<p>You could also use "break" or "exit" to go out of the loop or the program. It's also generally better to use a larger condition that goes well in unexpected case (x&lt;=0 or ans1 isn't YES rather than x==0 or ans1 is YES or ans1 is NO). </p> <pre><code>while True: # Code if ans1 not in ["Y", "YES"]: break #...
2
2016-06-04T21:16:38Z
[ "python", "loops", "while-loop" ]
Running .py in PowerShell
37,634,772
<p>I am running a simple: <code>echo print "Hello!!" &gt; prog.py</code> on PowerShell (PS). It was all going well untill I set <code>.py</code> programs to run by default with <code>IDLE.bat</code>. As soon as I did that, when I type <code>.\prog.py</code>, PowerShell runs Idle, so I had the "brilliant idea" to set ...
3
2016-06-04T20:36:46Z
37,638,964
<p><code>ÿþ</code> is a byte order mark. You're looking at Windows Unicode, which is UCS-2 LE or UTF-16, which is the common encoding format that the .Net Framework uses. The "spaces" are happening because Python isn't interpreting the file as being encoded with multibyte characters, which is what it is.</p> <p>Tr...
1
2016-06-05T06:02:47Z
[ "python", "powershell" ]
Using first row in Pandas groupby dataframe to calculate cumulative difference
37,634,786
<p>I have the following grouped dataframe based on daily data</p> <pre><code>Studentid Year Month BookLevel JSmith 2015 12 1.4 2016 1 1.6 2 1.8 3 1.2 4 2.0 MBrown 2016 1 3.0 2 3.2 ...
0
2016-06-04T20:38:13Z
37,634,873
<p>OK, this should work, if we <code>groupby</code> on the first level and subtract BookLevel from the series returned by calling <code>transform</code> with <code>first</code> then we can add this as the new desired column:</p> <pre><code>In [47]: df['ProgressSinceStart'] = df['BookLevel'] - df.groupby(level='Student...
0
2016-06-04T20:48:39Z
[ "python", "pandas" ]
Using first row in Pandas groupby dataframe to calculate cumulative difference
37,634,786
<p>I have the following grouped dataframe based on daily data</p> <pre><code>Studentid Year Month BookLevel JSmith 2015 12 1.4 2016 1 1.6 2 1.8 3 1.2 4 2.0 MBrown 2016 1 3.0 2 3.2 ...
0
2016-06-04T20:38:13Z
37,639,035
<p>I don't quite know how to copy dataframe with multiple index. So I just form my own. FYI: it will be great you put the raw <code>dataframe</code> so I can just use <code>pd.read_clipboard()</code>. Below is how I form the df</p> <pre><code>df = pd.DataFrame({'BookLevel': [1.4, 1.6, 1.8, 1.2, 2.0, 3.0, 3.2, 3.6], '...
1
2016-06-05T06:14:09Z
[ "python", "pandas" ]
setting setting apps value in django for a new application
37,634,845
<p>So I've been following <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial02/" rel="nofollow">django tutorial</a> and things worked well, but then I decided to try and write my own apps following the tutorial. I created a view, and updated the /<code>pysent/settings.py</code> file with this section</p> <p...
1
2016-06-04T20:44:33Z
37,634,875
<p>Look into your app directory, and check if there's a module named <code>app</code> and in that module a class named <code>PressentConfig</code>. If there isn't, then the app config approach will not work unless you create a configuration for your app. Read more <a href="https://docs.djangoproject.com/en/1.9/ref/appl...
2
2016-06-04T20:49:07Z
[ "python", "django" ]
setting setting apps value in django for a new application
37,634,845
<p>So I've been following <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial02/" rel="nofollow">django tutorial</a> and things worked well, but then I decided to try and write my own apps following the tutorial. I created a view, and updated the /<code>pysent/settings.py</code> file with this section</p> <p...
1
2016-06-04T20:44:33Z
37,634,978
<p>I'm going to presume <code>pressent</code> is your django application name (project name I think is <code>pysent</code>), so there's a directory named <code>pressent</code> and inside it has a <code>apps.py</code> file, and finally that file has a class named <code>PressentConfig</code>.</p> <p>PressentConfig class...
2
2016-06-04T21:00:44Z
[ "python", "django" ]
Simple http server in Python 3.5.1 Shell
37,634,886
<p>I am trying to get a simple http server going, using the directory in my code below as the root. This is using Python 3.5.1 Shell:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import http.server &gt;&gt;&gt; import socketserver &gt;&gt;&gt; os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27') &gt;&gt;&gt;...
0
2016-06-04T20:50:06Z
37,634,955
<p>You're confusing Python commands and shells command.</p> <p><code>import os</code> etc are python lines (interpreted by Python), <code>python -m http.server 8000</code> is a shell line, interpreted by <code>bash</code>, <code>sh</code> or whatever Microsoft use for Windows. You may try something like this to run it...
4
2016-06-04T20:57:48Z
[ "python", "shell" ]
Simple http server in Python 3.5.1 Shell
37,634,886
<p>I am trying to get a simple http server going, using the directory in my code below as the root. This is using Python 3.5.1 Shell:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import http.server &gt;&gt;&gt; import socketserver &gt;&gt;&gt; os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27') &gt;&gt;&gt;...
0
2016-06-04T20:50:06Z
37,634,956
<p>The problem is that the <code>python -m</code> command is not a python command itself but should be used in the shell ;) </p> <p>You can use instead: </p> <pre><code>import http.server def start_server(port=8000, bind="", cgi=False): if cgi==True: http.server.test(HandlerClass=http.server.CGIHTTPReque...
0
2016-06-04T20:57:53Z
[ "python", "shell" ]
Simple http server in Python 3.5.1 Shell
37,634,886
<p>I am trying to get a simple http server going, using the directory in my code below as the root. This is using Python 3.5.1 Shell:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import http.server &gt;&gt;&gt; import socketserver &gt;&gt;&gt; os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27') &gt;&gt;&gt;...
0
2016-06-04T20:50:06Z
37,635,019
<p>The idea itself of running a Web server into the Python shell is wrong as a server is a system-level process supposed to run forever. You can try to run it using the <code>subprocess</code> library maybe?</p> <p>Furthermore, you cannot run <code>python</code> executable into the shell. Once you run the shell, you n...
0
2016-06-04T21:05:50Z
[ "python", "shell" ]
Using Python to populate a csv file
37,634,899
<p>The following piece of code creates a CSV file, but every other line is blank. How can I prevent these linebreaks from happening?</p> <pre><code>import datetime import time import csv i = 0 while i &lt; 10: TempProbe = "78.12" CurrentTime = time.strftime("%x") CurrentDate = time.strftime("%I:%M:%S") ...
1
2016-06-04T20:51:35Z
37,634,937
<p>This is probably because the default line terminator is <code>'\r\n'</code>. You can correct this by passing <code>lineterminator='\n'</code> to your <code>csv.writer</code> object, like so:</p> <pre><code>csvWriter = csv.writer(file, lineterminator='\n') </code></pre> <p>P.S. Move this line out of your <code>whil...
4
2016-06-04T20:55:18Z
[ "python", "csv" ]
Using Python to populate a csv file
37,634,899
<p>The following piece of code creates a CSV file, but every other line is blank. How can I prevent these linebreaks from happening?</p> <pre><code>import datetime import time import csv i = 0 while i &lt; 10: TempProbe = "78.12" CurrentTime = time.strftime("%x") CurrentDate = time.strftime("%I:%M:%S") ...
1
2016-06-04T20:51:35Z
37,635,020
<p>You need to set the lineterminator for your csvWriter, as in the code below.</p> <pre><code>csvWriter = csv.writer(file, lineterminator='\n') </code></pre> <p>For an explanation why, see: <a href="http://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row">CSV file wri...
1
2016-06-04T21:06:02Z
[ "python", "csv" ]
Using Python to populate a csv file
37,634,899
<p>The following piece of code creates a CSV file, but every other line is blank. How can I prevent these linebreaks from happening?</p> <pre><code>import datetime import time import csv i = 0 while i &lt; 10: TempProbe = "78.12" CurrentTime = time.strftime("%x") CurrentDate = time.strftime("%I:%M:%S") ...
1
2016-06-04T20:51:35Z
37,635,109
<p>You can simply use the <code>open</code> function to write a csv file:</p> <pre><code>file = open("outFile.csv", "a") file.write(stringAll+'\n') </code></pre> <p>Also, you should take the file <code>open</code> and <code>close</code> functions out of the loop.</p>
0
2016-06-04T21:18:03Z
[ "python", "csv" ]
Using Python to populate a csv file
37,634,899
<p>The following piece of code creates a CSV file, but every other line is blank. How can I prevent these linebreaks from happening?</p> <pre><code>import datetime import time import csv i = 0 while i &lt; 10: TempProbe = "78.12" CurrentTime = time.strftime("%x") CurrentDate = time.strftime("%I:%M:%S") ...
1
2016-06-04T20:51:35Z
37,635,198
<p>Use this: 'ab' vs 'a',writes binary should fix the problem </p> <pre><code>file = open("outFile.csv", "ab") csvWriter = csv.writer(file, lineterminator='\n' ) </code></pre> <p>or this you dont need to open/close on every write : </p> <pre><code>file = open("outFile.csv", "ab") csvWriter = csv.writer(file...
0
2016-06-04T21:29:39Z
[ "python", "csv" ]
Django: How do I create a view to update multiple records on an intermediate model with a Many-to-Many-through relationship?
37,634,959
<p>I am a beginner to Django, and am creating an RSVP site to handle multiple events and keep track of guests to those events. I have a model for <em>Guest</em>, for <em>Event</em>, and an intermediate model for <em>GuestEvent</em>. I would like a page to loop through every <em>GuestEvent</em> for a <em>Guest</em> an...
0
2016-06-04T20:58:20Z
37,638,146
<p>I think I have this mostly working now with Django-Extra-Views. My view looks like this:</p> <pre><code>class GuestEventInline(InlineFormSet): model = GuestEvent fields = [ 'attending', 'adults', 'children' ] extra = 0 can_delete=False class Invite2View(UpdateWithInlinesView): template_name = "...
0
2016-06-05T03:22:51Z
[ "python", "django", "many-to-many", "django-intermediate-table" ]
Which portions of code execute in Tensorflow vs. Python interpreter?
37,635,051
<p>In Tensorflow we typically have one block of code to set up the computation graph and a second block to run the session, e.g.:</p> <pre><code>graph = tf.Graph() with graph.as_default(): ...Computation graph code here... ... with tf.Session(graph=graph) as session: ... code to run the graph here... ....
1
2016-06-04T21:09:46Z
37,635,555
<p>As far as I understand TensorFlow, the first part where you define the graph should be written only with TensorFlow functions. If you want to add some python it should be separated from the graph and added via placeholders (<code>tf.placeholder</code>).</p> <p>On the other side, in the <code>tf.Session()</code> par...
2
2016-06-04T22:17:37Z
[ "python", "tensorflow" ]
Flask: don't redirect to a url()
37,635,086
<p>I am working on a web app which is built on flask,postgreSQL. It is used to collect lab data and manage the data collected. There are two pages in this app, which I have attached are used to show lab data of some labs chosen by the user by querying from a database. <br><br> One page(admin_select_lab_for_data.html) e...
0
2016-06-04T21:14:15Z
37,635,126
<p>You can never achieve a page redirect as a result of an Ajax post request. </p> <p>You either have to submit a regular form post and do the redirect or you need to return a result from the Ajax call and change the page using window.location in the browser.</p>
2
2016-06-04T21:20:15Z
[ "javascript", "jquery", "python", "flask" ]
Parse json from mysql in flask to get a field from record
37,635,090
<p>Mind that I am new to flask and python for that matter, I appreciate any help that anyone gives. I'm looking to access one of the fields of my JSON response(just the field not the entire response), how should I go about parsing the response. Image of the response attached below,thanks. <br></p> <h1>This is my main ...
0
2016-06-04T21:15:00Z
37,764,137
<p>Use "fetchedData = json.dumps(fetchedData)" instead of "fetchedData = jsonify(fetchedData)" then create a json decoder and parse the response, refer to below :</p> <pre><code>def displayQuery(self,query): try: connection = mysql.connect() cursor = connection.cursor() cu...
0
2016-06-11T13:11:47Z
[ "python", "mysql", "json" ]
Cannot install python interface for shogun
37,635,177
<p>I am trying to install a python interface for Machine Learning toolbox "Shogun". I have downloaded <code>shogun-4.1.0.tar.bz2</code>, extracted it, went there and (according to <a href="http://shogun-toolbox.org/doc/en/latest/install.html" rel="nofollow">http://shogun-toolbox.org/doc/en/latest/install.html</a>) exec...
0
2016-06-04T21:26:24Z
37,636,431
<p>Sorry to bother you, I have found that the files are moved and the text at the link above is out of date. If anyone would have such problem - look here: <a href="https://github.com/shogun-toolbox/shogun/issues/3110" rel="nofollow">https://github.com/shogun-toolbox/shogun/issues/3110</a></p>
1
2016-06-05T00:56:36Z
[ "python", "python-2.7", "machine-learning", "shogun" ]
Update changes smoothly of a PyQt widget
37,635,205
<p>I have a PyQt5 application that looks like this <a href="http://i.stack.imgur.com/AELLR.png" rel="nofollow">This</a>. Now, with the "bailar" button I want the character on the grid to look left and right a couple of times. I do this in the following method:</p> <pre><code>def dance(self): """ Make the P1 da...
0
2016-06-04T21:31:07Z
37,639,781
<p>You see only the last frame of your animation because the UI isn't updated by Qt until the <code>dance</code> function terminates. If you add <code>QtGui.qApp.processEvents()</code> just before the <code>time.sleep(0.2)</code> statement, the UI will be updated for every frame of the animation. </p> <p>Note that the...
0
2016-06-05T08:10:46Z
[ "python", "multithreading", "python-2.7", "pyqt", "pyqt5" ]
Flask / Jinja - render user input jinja template inside parent template with scope/context from parent
37,635,309
<p>The title is a mess, so let me be as clear as possible. How can I implement <code>do_magic</code>?</p> <p><strong>In this template.html</strong></p> <pre><code>{% set x = 1 %} {{ do_magic(subtemplate) }}, {{ x }}, {{ y }} </code></pre> <p><strong>Called from this method</strong></p> <pre><code>@app.route('/') de...
0
2016-06-04T21:44:40Z
37,635,774
<p>I think I figured it out!</p> <pre><code>from jinja2 import contextfunction, Markup @contextfunction def do_magic(context, subtemplate): ''' Renders string subtemplate with variables from the active context. ''' template_object = app.jinja_env.from_string(subtemplate) html = template_object.render(**context)...
0
2016-06-04T22:48:40Z
[ "python", "flask", "jinja2" ]
How can I implement a summatory with a cycle and recurssion
37,635,384
<p>If i had this function</p> <pre><code>def P(n): iterador = 0 while ( iterador &lt;= n ): print(iterador) iterador = iterador + 1 P(8) </code></pre> <p>Which prints </p> <pre><code>1 2 3 4 5 6 7 8 </code></pre> <p>What would I have to do, in order to add each number, like this</p> <pre><c...
1
2016-06-04T21:53:47Z
37,635,413
<p>You have to use recursion like here:</p> <pre><code>def recursive_sum(n): if n &gt;= 1: return recursive_sum(n-1) + n else: return n print recursive_sum(0) # 0 print recursive_sum(8) # 36 </code></pre>
0
2016-06-04T21:57:59Z
[ "python", "recursion", "add", "cycle" ]
How can I implement a summatory with a cycle and recurssion
37,635,384
<p>If i had this function</p> <pre><code>def P(n): iterador = 0 while ( iterador &lt;= n ): print(iterador) iterador = iterador + 1 P(8) </code></pre> <p>Which prints </p> <pre><code>1 2 3 4 5 6 7 8 </code></pre> <p>What would I have to do, in order to add each number, like this</p> <pre><c...
1
2016-06-04T21:53:47Z
37,635,438
<p>The first step in recursion is using recursion. That means the function has to call itself somewhere. The next step in using recursion is stopping the recursion. That means providing a way for the function to stop calling itself when it's time to return a result. For this function, you'll want to start at the given ...
1
2016-06-04T22:00:48Z
[ "python", "recursion", "add", "cycle" ]
How can I implement a summatory with a cycle and recurssion
37,635,384
<p>If i had this function</p> <pre><code>def P(n): iterador = 0 while ( iterador &lt;= n ): print(iterador) iterador = iterador + 1 P(8) </code></pre> <p>Which prints </p> <pre><code>1 2 3 4 5 6 7 8 </code></pre> <p>What would I have to do, in order to add each number, like this</p> <pre><c...
1
2016-06-04T21:53:47Z
37,635,833
<p>Ok, thanks for your help, everybody. I applied the aforementioned, this is the result:</p> <pre><code>def P(n): if ( (n == 0) ): resultado = 0 if ( ( n==1 ) ): resultado = 1 if ( (n&gt;1) ): resultado = P(n-1) + n return resultado def Q(n): resultado = ( n*(n+1) // 2) ...
0
2016-06-04T22:58:15Z
[ "python", "recursion", "add", "cycle" ]
Cant understand why this url mapping is working?
37,635,420
<p>I am currently going through various Django tutorials in order to understand how url mapping is working . I came across an example which is something like this</p> <p>this is in my urls.py</p> <pre><code>url(r'admin_page_edit$',"adminApp.views.showClientDetails",name="admin_page_edit"), </code></pre> <p>this is ...
0
2016-06-04T21:58:43Z
37,635,615
<p>Query strings (parts following <code>?</code>) are not processed by the Django url parser. Why? Because they don't have to be processed. You can just about append any query string to any url:</p> <p>Like: <a href="https://www.facebook.com/?request=pleasedonotwork" rel="nofollow">https://www.facebook.com/?request=pl...
2
2016-06-04T22:25:36Z
[ "python", "django", "url", "url-mapping" ]
Print output of "time" shell command without losing formating
37,635,424
<p>For some reason, when I run "time ./" from the terminal, I get this format:</p> <pre> real&#x09;0m0.090s user&#x09;0m0.086s sys&#x09;0m0.004s </pre> <p>But when I execute the same command in Python 2.7.6:</p> <pre><code>result = subprocess.Popen("time ./&lt;binary&gt;", shell = True, stdout = subprocess.PIPE) </c...
3
2016-06-04T21:59:17Z
37,635,450
<p>From the <code>man time</code> documentation:</p> <blockquote> <p>After the utility finishes, time writes the total time elapsed, the time consumed by system overhead, and the time used to execute utility <strong>to the standard error stream.</strong></p> </blockquote> <p>Bold emphasis mine. You are capturing th...
3
2016-06-04T22:01:55Z
[ "python", "bash", "time" ]
Print output of "time" shell command without losing formating
37,635,424
<p>For some reason, when I run "time ./" from the terminal, I get this format:</p> <pre> real&#x09;0m0.090s user&#x09;0m0.086s sys&#x09;0m0.004s </pre> <p>But when I execute the same command in Python 2.7.6:</p> <pre><code>result = subprocess.Popen("time ./&lt;binary&gt;", shell = True, stdout = subprocess.PIPE) </c...
3
2016-06-04T21:59:17Z
37,635,742
<p>First: <a href="https://stackoverflow.com/questions/37635424/4116239">Martijn Pieters' answer</a> is correct about needing to capture <code>time</code>'s <code>stderr</code> instead of <code>stdout</code>.</p> <p>Also, at least on older versions of Python like 3.1, a <a href="https://docs.python.org/2/library/subpr...
3
2016-06-04T22:43:43Z
[ "python", "bash", "time" ]
How do I manipulate data in a list that has been read in from a file using Python 2.x?
37,635,429
<p>I am trying to create a program that will tally the cost of ingredients within a recipe and return a total cost for said recipe. I am teaching myself Python and have set this as a personal, but practical, challenge. However, I have hit a wall. Hard.</p> <p>My idea was to read a file into a list. Multiply the ingred...
0
2016-06-04T22:00:20Z
37,635,553
<p>If I understand you correctly, you have to parse your file. For this you need to know the format in which the ingredients are being stored. Since this program is for your personal use you may just choose the most simple.</p> <p>So let's assume you have your ingredients in CSV format:</p> <pre><code>sugar 10g flou...
0
2016-06-04T22:17:11Z
[ "python", "python-2.x" ]
How do I manipulate data in a list that has been read in from a file using Python 2.x?
37,635,429
<p>I am trying to create a program that will tally the cost of ingredients within a recipe and return a total cost for said recipe. I am teaching myself Python and have set this as a personal, but practical, challenge. However, I have hit a wall. Hard.</p> <p>My idea was to read a file into a list. Multiply the ingred...
0
2016-06-04T22:00:20Z
37,635,567
<p>Part of your difficulty is knowing how to split your input on the comma -- use <code>split()</code>. Another problem is converting the string to a float -- use <code>float()</code>.</p> <p>Your last problem is mapping input strings to values. You could write a function that maps strings to costs:</p> <pre><code>...
0
2016-06-04T22:19:30Z
[ "python", "python-2.x" ]
Cython code : Python.h no such file or directory
37,635,481
<p>when I generate C code from python3 code with <code>cython3</code> and try to compile with gcc the resulting code, I get this error : <code>test.c:4:20: fatal error: Python.h: Aucun fichier ou dossier de ce type</code> .</p> <p>I looked over the web for this error, and all the answer were about installing <code>pyt...
0
2016-06-04T22:07:16Z
37,635,869
<p>You should compile using the appropriate paths, like this...</p> <pre><code>$ gcc -o test test.c `pkg-config --cflags --libs python3` </code></pre> <p>What happened before is that you weren't including the appropiate include paths (retrieved by <code>pkg-config --cflags</code>) and library/linking paths (retrieved...
2
2016-06-04T23:06:23Z
[ "python", "c", "linux", "ubuntu", "cython" ]
Generate system of equations
37,635,530
<p>I'm trying to make a function that can generate a system of equations that are solved in a separate program. The equations are generated from a tree of isotope decays, but for simplicity I have the following tree: </p> <p><a href="http://i.stack.imgur.com/MJWqv.png" rel="nofollow"><img src="http://i.stack.imgur.com...
1
2016-06-04T22:14:51Z
37,673,930
<p>Use <a href="http://www.sympy.org/en/index.html" rel="nofollow">SymPy</a>. SymPy is a symbolic computation toolbox, and very well suited for this use case. You can create a symbol using <code>A = sympy.Symbol("A")</code>, and then use <code>A</code> in an expression like you'd use any variable. For example, if <code...
4
2016-06-07T08:13:36Z
[ "python" ]
Converting dictionary values in python from str to int in nested dictionary
37,635,549
<p>I currently have a nested dictionary which looks like this:</p> <pre><code>series = { 'a': {'foo':'2', 'bar':'3', 'baz':'7', 'qux':'1'}, 'b': {'foo':'6', 'bar':'4', 'baz':'3', 'qux':'0'}, 'c': {'foo':'4', 'bar':'5', 'baz':'1', 'qux':'6'} } </code></pre> <p>And I'm trying to convert the values from strings into i...
0
2016-06-04T22:16:31Z
37,635,608
<p>You have to go deeper in this case:</p> <pre><code>In [4]: {k: {kk: int(vv) for kk, vv in v.items()} for k, v in series.items()} Out[4]: {'a': {'bar': 3, 'baz': 7, 'foo': 2, 'qux': 1}, 'b': {'bar': 4, 'baz': 3, 'foo': 6, 'qux': 0}, 'c': {'bar': 5, 'baz': 1, 'foo': 4, 'qux': 6}} </code></pre> <p>Your ow...
3
2016-06-04T22:24:58Z
[ "python", "dictionary" ]
Converting dictionary values in python from str to int in nested dictionary
37,635,549
<p>I currently have a nested dictionary which looks like this:</p> <pre><code>series = { 'a': {'foo':'2', 'bar':'3', 'baz':'7', 'qux':'1'}, 'b': {'foo':'6', 'bar':'4', 'baz':'3', 'qux':'0'}, 'c': {'foo':'4', 'bar':'5', 'baz':'1', 'qux':'6'} } </code></pre> <p>And I'm trying to convert the values from strings into i...
0
2016-06-04T22:16:31Z
37,635,634
<p>int(v) -- <em>v is a dictionary!</em></p> <p><strong>this line here, you are trying to convert a dictionary to an integer.</strong></p> <p>you'll need to nest another dictionary comprehension inside</p> <p>basically if you replace [int(v)] with something like</p> <pre><code>[dict((a,int(b) for (a,b) in v.items...
0
2016-06-04T22:28:04Z
[ "python", "dictionary" ]
Converting dictionary values in python from str to int in nested dictionary
37,635,549
<p>I currently have a nested dictionary which looks like this:</p> <pre><code>series = { 'a': {'foo':'2', 'bar':'3', 'baz':'7', 'qux':'1'}, 'b': {'foo':'6', 'bar':'4', 'baz':'3', 'qux':'0'}, 'c': {'foo':'4', 'bar':'5', 'baz':'1', 'qux':'6'} } </code></pre> <p>And I'm trying to convert the values from strings into i...
0
2016-06-04T22:16:31Z
37,635,655
<p>In your example <code>v</code> is the internal dictionary, not the internal values. What you want to do is turn all values in the internal dict into an int.</p> <pre><code>{k1: {k2: int(v2) for k2, v2 in series[k1].items()} for k1 in series} </code></pre>
0
2016-06-04T22:30:21Z
[ "python", "dictionary" ]
Converting dictionary values in python from str to int in nested dictionary
37,635,549
<p>I currently have a nested dictionary which looks like this:</p> <pre><code>series = { 'a': {'foo':'2', 'bar':'3', 'baz':'7', 'qux':'1'}, 'b': {'foo':'6', 'bar':'4', 'baz':'3', 'qux':'0'}, 'c': {'foo':'4', 'bar':'5', 'baz':'1', 'qux':'6'} } </code></pre> <p>And I'm trying to convert the values from strings into i...
0
2016-06-04T22:16:31Z
37,635,679
<p>As stated by Ilja Everilä, if you want a generic solution for all kinds of nested <code>dict</code>, you can use a recursive function.</p> <p>I guess something like the following would work (will test it when I have some more time).</p> <pre><code>def series_to_int(series): for k,v in series.items(): ...
0
2016-06-04T22:33:08Z
[ "python", "dictionary" ]
Adding a space before every other letter in a for loop with a string
37,635,569
<p>I apologize beforehand if this has already been covered, but I've been unable to find an answer.</p> <p>I want a for loop to produce an output with every other letter having a space before it. Should look something like this:</p> <pre><code>&gt;&gt;&gt;everyOther('banana') b a n a n a </code></pre> <p>I unders...
3
2016-06-04T22:19:45Z
37,635,643
<p>You can use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> to return an incrementing index number for each letter in the string, along with the letter itself.</p> <p>You can then check to see if the number is divisible by 2, using the <a href="https:...
1
2016-06-04T22:29:02Z
[ "python", "for-loop" ]
Adding a space before every other letter in a for loop with a string
37,635,569
<p>I apologize beforehand if this has already been covered, but I've been unable to find an answer.</p> <p>I want a for loop to produce an output with every other letter having a space before it. Should look something like this:</p> <pre><code>&gt;&gt;&gt;everyOther('banana') b a n a n a </code></pre> <p>I unders...
3
2016-06-04T22:19:45Z
37,636,305
<p>I would try something like this. It checks the index of the character, and puts a space in front if it's odd. Otherwise, it just prints like normal.</p> <pre><code>def everyOther(word): final="" for i in word: index=word.index(i) if index%2!=0: final+=i else: ...
0
2016-06-05T00:27:35Z
[ "python", "for-loop" ]
Adding a space before every other letter in a for loop with a string
37,635,569
<p>I apologize beforehand if this has already been covered, but I've been unable to find an answer.</p> <p>I want a for loop to produce an output with every other letter having a space before it. Should look something like this:</p> <pre><code>&gt;&gt;&gt;everyOther('banana') b a n a n a </code></pre> <p>I unders...
3
2016-06-04T22:19:45Z
37,638,399
<pre><code>is_odd = True for each in word: if is_odd: print(' ',) #use print(' ', end="") in py 3.x print(each) is_odd = not is_odd </code></pre> <p>using <code>word.index(i)</code> iterates <em>all</em> over the list and slows down. So, if there are <code>n</code> letters in word, there are <code>n**2</co...
0
2016-06-05T04:17:06Z
[ "python", "for-loop" ]
Minify all CSS and Javascript in a directory
37,635,640
<p>I am trying to make a python script that will package the contents of a directory and minify all of the JavaScript and CSS scripts.</p> <p>If I used the code below (bottom of the post), and the directory structure inside of <code>theme_files</code> was such:</p> <pre><code>\ |-assets\ | |-css\ | |...
0
2016-06-04T22:28:38Z
37,635,901
<p>As stated by @Squall, </p> <blockquote> <p>rcssmin.cssmin() and rjsmin.jsmin() expect the first element to be the CSS respectively JS code to minify as string. You have to open and read the CSS and JS files by yourself.</p> </blockquote> <hr> <pre><code>if filename.endswith(".css"): with open(os.path.join(d...
0
2016-06-04T23:12:45Z
[ "javascript", "python", "html", "css", "python-3.x" ]
circular reference in class in python
37,635,705
<p>I have a problem with below design. I am looking for a vectorized solution for below circular reference problem. <code>Value</code> (calculated by func1) uses the content from <code>number</code> (calculated by func2), <code>number</code> gets increased by <code>Value</code> afterwards and everything will be produce...
0
2016-06-04T22:36:53Z
37,638,579
<p>Based on what you describe, I think you are trying to implement some sorts of class which construct the list "dynamically". While I think it is better to separate the task into two: one is form the <code>DataFrame</code>; second is to <code>update</code> it.</p> <p>Below is my implementation of the class to form th...
1
2016-06-05T04:52:04Z
[ "python", "class", "pandas", "methods" ]
Extracting information from a table except header of the table using bs4
37,635,847
<p>I am trying to extracting information from a table using bs4 and python. when I am using the following code to extract information from header of the table: </p> <pre><code> tr_header=table.findAll("tr")[0] tds_in_header = [td.get_text() for td in tr_header.findAll("td")] header_items= [data.encode('utf...
0
2016-06-04T23:01:49Z
37,636,137
<p>For Your first question,</p> <pre><code>import bs4 text = """ &lt;table class="codes"&gt;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Code&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;b&gt;Display&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;Definition&lt;/b&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt;&lt;td&gt;active&lt;a name="active"&gt; &lt;/a&gt;&l...
1
2016-06-04T23:52:06Z
[ "python", "html", "bs4" ]
Extracting information from a table except header of the table using bs4
37,635,847
<p>I am trying to extracting information from a table using bs4 and python. when I am using the following code to extract information from header of the table: </p> <pre><code> tr_header=table.findAll("tr")[0] tds_in_header = [td.get_text() for td in tr_header.findAll("td")] header_items= [data.encode('utf...
0
2016-06-04T23:01:49Z
37,636,511
<p>JustMe answered this question correctly. Another equivalent variant would be:</p> <pre><code>import bs4 text = """ &lt;table class="codes"&gt;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Code&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;b&gt;Display&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;Definition&lt;/b&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt...
0
2016-06-05T01:10:49Z
[ "python", "html", "bs4" ]
counting entries in big data with pandas
37,635,867
<p>I am working with a tab separated file:</p> <pre><code>A B C D a d ii do a d g do a h g do a i k mo c i k mo c g ii mo v g p do </code></pre> <p>I want to count each entry in first column and all related entries to it in second, third, and four...
4
2016-06-04T23:06:06Z
37,636,326
<pre><code>import pandas as pd df = pd.DataFrame({'A': ['a', 'a', 'a', 'a', 'c', 'c', 'v'], 'B': ['d', 'd', 'h', 'i', 'i', 'g', 'g'], 'C': ['ii', 'g', 'g', 'k', 'k', 'ii', 'p'], 'D': ['domain', 'domain', 'domain', 'motif', 'motif', 'moti...
4
2016-06-05T00:33:25Z
[ "python", "pandas" ]
counting entries in big data with pandas
37,635,867
<p>I am working with a tab separated file:</p> <pre><code>A B C D a d ii do a d g do a h g do a i k mo c i k mo c g ii mo v g p do </code></pre> <p>I want to count each entry in first column and all related entries to it in second, third, and four...
4
2016-06-04T23:06:06Z
37,638,225
<pre><code>import pandas as pd df = pd.DataFrame({'A': ['a', 'a', 'a', 'a', 'c', 'c', 'v'], 'B': ['d', 'd', 'h', 'i', 'i', 'g', 'g'], 'C': ['ii', 'g', 'g', 'k', 'k', 'ii', 'p'], 'D': ['domain', 'domain', 'domain', 'motif', 'motif', 'moti...
1
2016-06-05T03:38:37Z
[ "python", "pandas" ]
Removing single quotes if they aren't in the middle of a word
37,635,909
<p>I want to be able to remove all punctuation and single quotes ' from a string, unless the single quote ' is in the middle of a word. </p> <p>At this point I have the following code:</p> <pre><code>with open('test.txt','r') as f: for line in f: line = line.lower() line = re.sub('[^a-z\ \']+', " ...
1
2016-06-04T23:13:20Z
37,635,933
<p>Split the string, use <code>strip()</code> on each word to remove leading and trailing characters on it, then join it all back together.</p> <pre><code>&gt;&gt;&gt; s = "'here is some stuff 'now there are quotes' now there's not'" &gt;&gt;&gt; print(' '.join(w.strip("'") for w in s.split()).lower()) here is some st...
1
2016-06-04T23:16:15Z
[ "python", "string" ]
Removing single quotes if they aren't in the middle of a word
37,635,909
<p>I want to be able to remove all punctuation and single quotes ' from a string, unless the single quote ' is in the middle of a word. </p> <p>At this point I have the following code:</p> <pre><code>with open('test.txt','r') as f: for line in f: line = line.lower() line = re.sub('[^a-z\ \']+', " ...
1
2016-06-04T23:13:20Z
37,636,043
<p>Here is complete solution to remove whatever you don't want in a string:</p> <pre><code>def istext (text): ok = 0 for x in text: ok += x.isalnum() return ok&gt;0 def stripit (text, ofwhat): for x in ofwhat: text = text.strip(x) return text def purge (text, notwanted="'\"!#$%&amp;/()=?*+-.,;:_&...
-1
2016-06-04T23:38:13Z
[ "python", "string" ]
Removing single quotes if they aren't in the middle of a word
37,635,909
<p>I want to be able to remove all punctuation and single quotes ' from a string, unless the single quote ' is in the middle of a word. </p> <p>At this point I have the following code:</p> <pre><code>with open('test.txt','r') as f: for line in f: line = line.lower() line = re.sub('[^a-z\ \']+', " ...
1
2016-06-04T23:13:20Z
37,636,052
<p>Using regular expressions, you could first remove <code>'</code>s that don't follow a letter, then remove <code>'</code>s that don't precede a letter (thus only keeping ones that both follow and precede a letter):</p> <pre><code>line = "Here is some stuff. 'Now there are quotes.' Now there's not." print re.sub(r"'(...
0
2016-06-04T23:39:27Z
[ "python", "string" ]
Removing single quotes if they aren't in the middle of a word
37,635,909
<p>I want to be able to remove all punctuation and single quotes ' from a string, unless the single quote ' is in the middle of a word. </p> <p>At this point I have the following code:</p> <pre><code>with open('test.txt','r') as f: for line in f: line = line.lower() line = re.sub('[^a-z\ \']+', " ...
1
2016-06-04T23:13:20Z
37,636,340
<p>Here's another solution using regular expressions with <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookarounds</a>. This method will preserve any whitespace your string may have.</p> <pre><code>import re rgx = re.compile(r"(?&lt;!\w)\'|\'(?!\w)") # Regex explanation: # (?&lt;!\w)\'...
0
2016-06-05T00:37:12Z
[ "python", "string" ]
Django - templatedoesnotexist
37,635,931
<p>I'm creating a project named "crepes_bretonnes". In this project, I have an application blog. I created a template date.html. Here is the structure of my folders : </p> <pre><code>crepes_bretonnes/ blog/ __init__.py admin.py migrations/ __init__.py models.py t...
0
2016-06-04T23:15:35Z
37,635,976
<p>I assume <code>'INSTALLED_APP'</code> is a typo and it really says <code>'INSTALLED_APPS'</code> in your settings. Anyway, you need to set <code>APP_DIRS = True</code> for templates to be found in <code>app/templates</code> folders:</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.dj...
0
2016-06-04T23:23:59Z
[ "python", "django" ]
What is the proper way to plot spectrum of a complex signal sampled in a narrow range?
37,636,017
<p>I have some complex data (small bandwidth around a set frequency) that I'm curious to plot, but I am slightly lost as to how should I proceed about interpreting a complex signal sampled in a particular range.</p> <p>So, for instance, here is the code (and my rather poor attempt at the problem) that I wrote so I hav...
0
2016-06-04T23:33:15Z
37,640,180
<h3>Nyquist Frequency and Aliasing</h3> <p>Your signal should be a (complex) exponential oscillation at +78 kHz, sampled at 100 kHz. <a href="https://en.wikipedia.org/wiki/Nyquist_frequency" rel="nofollow">This doesn't work</a>. What you see instead is an alias frequency at -22 kHz (78 kHz - 100 kHz). You have to make...
3
2016-06-05T09:04:01Z
[ "python", "numpy", "scipy", "signal-processing", "fft" ]
How do I implement a web crawler that scrapes ad links?
37,636,060
<p>To get training data, I wrote a crawler to follow the top 500 websites on Alexa with a depth of 2 and write all links found to a file. Right now, it looks for all the links in the html and writes them to a file. The problem is, the crawler misses all links to ads, some of which are located in iframes or located in C...
-3
2016-06-04T23:41:21Z
37,636,155
<p>A lot of advertising is delivered via asynchronous javascript executed on the page. If you're just scraping the server initial output you won't be able to obtain those others links. One method would be to use a headless browser like PhantomJS to render the html to a file then use your script on that. There are other...
0
2016-06-04T23:55:26Z
[ "python", "web-crawler" ]
Python: Remove html tag including content if next sibling is identical
37,636,084
<p>If I have something like this:</p> <pre><code>&lt;div&gt; &lt;a&gt;Link&lt;/a&gt; &lt;/div&gt; &lt;div&gt; &lt;a&gt;Link&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I would like to remove one of the div tags (including all content and child tags), because the two div tags, including their content, are the same. Only t...
1
2016-06-04T23:44:52Z
37,645,900
<p>My code was working slow because I assumed that <code>.findChildren()</code> only gets direct children (first level below), but it actually gets all children (from all levels). Because of that, the solution was to remove the following lines from my code:</p> <pre><code> else: children = item.findChildren...
0
2016-06-05T19:27:36Z
[ "python", "tags", "beautifulsoup" ]
Filtering and Then Summing Groupby Data in Pandas
37,636,108
<p>I want to find the sum of all the survived values in the Pandas data series when the 'Fare' is >100. The Panda data series was created using the <code>.groupby('Fare')</code>.</p> <pre><code> Name: Survived, dtype: int64 Fare 0.0000 1 4.0125 0 5.0000 0 6.2375 0 6.4375 0 6.4500 0 6.4958...
1
2016-06-04T23:48:39Z
37,636,166
<p>Try this code, but without your data I can not verify the result:</p> <pre><code>fare_df.loc[fare_df["Fare"] &gt; 100].sum()['Survived'] </code></pre>
0
2016-06-04T23:56:59Z
[ "python", "pandas", "filtering" ]
Filtering and Then Summing Groupby Data in Pandas
37,636,108
<p>I want to find the sum of all the survived values in the Pandas data series when the 'Fare' is >100. The Panda data series was created using the <code>.groupby('Fare')</code>.</p> <pre><code> Name: Survived, dtype: int64 Fare 0.0000 1 4.0125 0 5.0000 0 6.2375 0 6.4375 0 6.4500 0 6.4958...
1
2016-06-04T23:48:39Z
37,636,234
<p>This will get you the <code>sum()</code> you're looking for:</p> <pre><code>fare_df[fare_df.Fare &gt; 100]['Survived'].sum() </code></pre>
0
2016-06-05T00:11:25Z
[ "python", "pandas", "filtering" ]
Why text attachment sent using Flask Mail is empty?
37,636,148
<p>I am attempting to send an email with Flask-Mail with a .txt file attachment. Thus far either I get an error or the email sends but the .txt. file is blank I've tried it two ways:</p> <p>One way following the documentation:</p> <pre><code>with current_app.open_resource("sample.txt") as fp: msg.attach("sample.t...
2
2016-06-04T23:53:35Z
38,198,586
<p>According to <a href="https://pythonhosted.org/Flask-Mail/" rel="nofollow">Flask-Mail documentation</a>, this should perfectly do it:</p> <pre><code>with current_app.open_resource("sample.txt") as fp: msg.attach("sample.txt","text/plain", fp.read()) mail.send(msg) </code></pre> <ul> <li>Where <code>current_app...
0
2016-07-05T08:25:28Z
[ "python", "email", "flask", "flask-mail" ]
json converter only takes last key value for last dictionary instead of all
37,636,157
<p>Ok so I have the following list of dictionarys that I am trying to convert to a json file:</p> <pre><code>geojson_list = [ {'name': 'Parallelogram1', 'coordinates': [[115.67097179583487, -32.36672530921233], [115.96656222999665, -32.36672530921233], [115.90410905434761, -32.49580085924758], [115.60851862018583, ...
-1
2016-06-04T23:55:49Z
37,636,601
<p>You are having a problem caused by variable reuse.</p> <p>Every run through the <code>for d in mylist:</code> modifies <code>property_dict</code>, which then gets added to the <code>feature_list</code>. The next time through the loop, you modify the <strong>same <code>property_dict</code></strong>, which overwrites...
1
2016-06-05T01:32:11Z
[ "python", "json", "converter" ]
How to find find a grouping of upper and lower case characters in a string in python 3
37,636,263
<p>I'm working on Python Challenges, and the level I'm on asks us to find a lower case letter surrounded on both sides by exactly three upper case letters. I've written the following code, which seems pretty crude but I feel should work. However, all I get is an empty string.</p> <pre><code>source="Hello there" #the s...
0
2016-06-05T00:19:18Z
37,636,313
<p>This is far, far easier with a regular expression.</p> <pre><code>re.findall(r'(?&lt;![A-Z])[A-Z]{3}([a-z])(?=[A-Z]{3}(?:\Z|[^A-Z]))', text) </code></pre> <p>Here's how it works:</p> <ul> <li><p><code>(?&lt;![A-Z])</code> is a <em>negative lookbehind assertion</em> which makes sure that we are not preceded by an ...
0
2016-06-05T00:29:02Z
[ "python", "string" ]
How to find find a grouping of upper and lower case characters in a string in python 3
37,636,263
<p>I'm working on Python Challenges, and the level I'm on asks us to find a lower case letter surrounded on both sides by exactly three upper case letters. I've written the following code, which seems pretty crude but I feel should work. However, all I get is an empty string.</p> <pre><code>source="Hello there" #the s...
0
2016-06-05T00:19:18Z
37,636,673
<p>I would suggest using the <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> method with a <code>keyfunc</code> to distinguish lowercase from capital letters.</p> <p>First you need a helper function to refactor the check logic:</p> <pre><c...
0
2016-06-05T01:45:53Z
[ "python", "string" ]
Pycharm does not see files in relative path with ../
37,636,268
<p>I am developing a python project using pycharm. However, the problem is that it refuses to load files in which the relative path includes <code>../</code>. When I try </p> <pre><code>self.image = pygame.image.load("../resources/img/prey.png").convert_alpha() </code></pre> <p>I get:</p> <pre><code>self.image = pyg...
1
2016-06-05T00:19:54Z
37,655,658
<p>Go to <code>Run - Edit Configurations</code>, select your configuration</p> <p><a href="http://i.stack.imgur.com/bwoEn.png" rel="nofollow"><img src="http://i.stack.imgur.com/bwoEn.png" alt="Run Configuration editing"></a></p> <p>and change <code>Working directory</code> to <code>/media/Storage/System and dev/Code/...
2
2016-06-06T10:58:51Z
[ "python", "path", "pycharm", "filepath", "relative-path" ]
Python social auth steam avatar
37,636,300
<p>I'm using python-social-auth in my project. Account successfully created. And how can i get steam user avatar and save it in database?</p> <p>I am trying to use pipeline like this</p> <pre><code>def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs): url = None if backend.name == ...
1
2016-06-05T00:27:02Z
37,638,321
<p>Looking at the <a href="https://github.com/omab/python-social-auth/blob/master/social/backends/steam.py#L32" rel="nofollow">code</a>, this information is stored in a <code>player</code> key inside the <code>details</code> dict. </p> <p>I'm not sure where the arguments to your <code>get_avatar</code> function are co...
0
2016-06-05T04:01:25Z
[ "python", "django" ]
Fill_Between is incorrect
37,636,435
<p>Without the problematic bit of code the image is nearly correct, I am getting: <a href="http://i.stack.imgur.com/KeExB.png" rel="nofollow"><img src="http://i.stack.imgur.com/KeExB.png" alt="enter image description here"></a></p> <p>Now as you will see I want to fill the final circle in 5.67 and 7.33 on Row '5' but ...
1
2016-06-05T00:57:00Z
37,636,628
<p>Your <code>fill_between</code> works correct. But you think it is wrong. The problem occurs in axes cycle in <code>__init__</code>. You have several axes and try to apply <code>fill_between</code> for every axis.</p> <p>For the first and seconds <code>fill_between</code> this method produces correct filling because...
0
2016-06-05T01:37:38Z
[ "python", "matplotlib" ]
No Ident Response Python IRC
37,636,494
<p>I'm not getting a "Ident" Response with this IRC Connection</p> <pre><code>import sys import time import socket server="irc.freenode.net" botnick="Hidden" channel="Hidden" #Establish connection irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) irc.connect((server,6667)) irc.setblocking(False) time.slee...
0
2016-06-05T01:07:31Z
38,549,534
<p>identd <a href="http://www.faqs.org/rfcs/rfc1413.html" rel="nofollow">RFC1413</a> is a service used to associate connections coming from multiuser hosts with the users who "own" those connections. It used to be more widely used, with older SMTP and NNTP servers frequently configured to log identd responses, but toda...
0
2016-07-24T06:57:39Z
[ "python", "sockets", "irc" ]
Determine if a python program is running on WINE
37,636,509
<p>I can check for Linux/Windows/cygwin/etc. with sys.platform, but on WINE it just reports 'win32'. </p> <p>I am attempting to write a multi-platform application that uses pyserial, and I am using WINE to test setup of a Windows environment. On Windows serial ports are named COMxx, but on Linux they are /dev/ttyxxx...
0
2016-06-05T01:10:44Z
37,960,529
<p>First of all, and this is untested, try creating a symlink from .wine/dosdevices/COM1 to /dev/ttyS0. It should simply allow you to open the com port the Windows way.</p> <p>If, however, you are determined to know whether you are running on Wine, the "official" way is to check whether the registry has the key "HKEY_...
0
2016-06-22T06:50:14Z
[ "python", "pyserial", "wine" ]
Join lists with repeated values
37,636,607
<p>First, this is what I have on the code so far, I'll give the explanation in a bit:</p> <pre><code>ll1 = [ 'A', 'B', 'C', 'D' ] l2 = [ ['A', 10], ['B', 20], ['D', 5], ['A', 15], ['B', 30], ['C', 10], ['D', 15] ] dc = dict(l2) l3 = [[k, dc.get(k, 0)] for k in l1] </code></pre> <p>The result is this:</p> <pre><cod...
1
2016-06-05T01:33:07Z
37,637,873
<p>I would use a generator to fill in the missing values, just keep a <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow"><code>cycle</code></a> of the keys and when the next needed key is not the one in the data just produce the empty value:</p> <pre><code>import itertools def fi...
3
2016-06-05T02:28:20Z
[ "python", "list", "python-3.x" ]
Join lists with repeated values
37,636,607
<p>First, this is what I have on the code so far, I'll give the explanation in a bit:</p> <pre><code>ll1 = [ 'A', 'B', 'C', 'D' ] l2 = [ ['A', 10], ['B', 20], ['D', 5], ['A', 15], ['B', 30], ['C', 10], ['D', 15] ] dc = dict(l2) l3 = [[k, dc.get(k, 0)] for k in l1] </code></pre> <p>The result is this:</p> <pre><cod...
1
2016-06-05T01:33:07Z
37,637,999
<p>Here's a <strong><em>dirty</em></strong> way:</p> <pre><code>l1 = [ 'A', 'B', 'C', 'D', ] l2 = [ ['A', 10], ['B', 20], ['D', 5], ['A', 15], ['B', 30], ['C', 10], ['D', 15], ['A', 8], ] # Assuming elements in l2 are ordered, try to make groups # of the same length of l1. l_aux = l1[:] l3 = [[]] for x in l2: ...
1
2016-06-05T02:56:44Z
[ "python", "list", "python-3.x" ]
Join lists with repeated values
37,636,607
<p>First, this is what I have on the code so far, I'll give the explanation in a bit:</p> <pre><code>ll1 = [ 'A', 'B', 'C', 'D' ] l2 = [ ['A', 10], ['B', 20], ['D', 5], ['A', 15], ['B', 30], ['C', 10], ['D', 15] ] dc = dict(l2) l3 = [[k, dc.get(k, 0)] for k in l1] </code></pre> <p>The result is this:</p> <pre><cod...
1
2016-06-05T01:33:07Z
37,638,279
<p>The problem here with how dictionaries store values. A dictionary will take your key, use the <code>__hash__</code> function on it, then store that value. When it comes to strings, two strings with the same value will have the same output when <code>__hash__</code>ed. For example</p> <pre><code>&gt;&gt;&gt; a = "fo...
1
2016-06-05T03:49:42Z
[ "python", "list", "python-3.x" ]
How to print hex table with loops?
37,636,695
<p>I'm trying to print a hex table I though using this:</p> <pre><code>for i in range(0,1,1): for j in range(0,1,1): for k in range (0,1,1): for m in range (0,1,1): print(i,j,k,m) </code></pre> <p>But I only get this</p> <pre><code>0000 </code></pre> <p>I think is (start,end,...
0
2016-06-05T01:49:04Z
37,636,714
<p><code>range(0,1,1)</code> iterates from 0 up to <em>but not including</em> 1; that is, it only has a single value (0). So you have 4 nested loops, each of which only has 1 iteration: hence the <code>0000</code>. </p>
0
2016-06-05T01:53:48Z
[ "python", "loops" ]
How to print hex table with loops?
37,636,695
<p>I'm trying to print a hex table I though using this:</p> <pre><code>for i in range(0,1,1): for j in range(0,1,1): for k in range (0,1,1): for m in range (0,1,1): print(i,j,k,m) </code></pre> <p>But I only get this</p> <pre><code>0000 </code></pre> <p>I think is (start,end,...
0
2016-06-05T01:49:04Z
37,636,758
<p>Ohh thanks people. Yes, now work with this:</p> <pre><code>for i in range(0,2): for j in range(0,2): for k in range (0,2): for m in range(0, 2): print(i,j,k,m) </code></pre> <p>Got his output:</p> <pre><code>0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 ...
0
2016-06-05T02:01:39Z
[ "python", "loops" ]