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 use Anaconda Python to execute a .py file? | 39,995,380 | <p>I just downloaded and installed Anaconda on my Windows computer. However, I am having trouble executing .py files using the command prompt. How can I get my computer to understand that the python.exe application is in the Anaconda folder so it can execute my .py files?</p>
| 0 | 2016-10-12T09:40:36Z | 39,995,712 | <p>Anaconda should add itself to the PATH variable so you can start any .py file with "python yourpythonfile.py" and it should work from any folder. </p>
<p>Alternatively download pycharm community edition, open your python file there and run it. Make sure to have python.exe added as interpreter in the settings.</p>
| 0 | 2016-10-12T09:55:38Z | [
"python",
"windows",
"anaconda"
] |
how to call a method on the GUI thread? | 39,995,447 | <p>I am making a small program that gets the latest revenue from a webshop, if its more than the previous amount it makes a sound, I am using Pyglet but I get errors because its not being called from the main thread. I would like to know how to call a method on the main thread. see error below:</p>
<blockquote>
<p>'... | 0 | 2016-10-12T09:43:24Z | 39,999,168 | <p>It's not particularly strange. <code>work</code> is being executed as a separate thread from where <code>pyglet</code> was imported.</p>
<p><code>pyglet.app</code> when imported sets up a lot of context variables and what not. I say what not because I actually haven't bothered checking deeper into what it actually ... | 0 | 2016-10-12T12:55:33Z | [
"python",
"multithreading",
"audio",
"pyglet"
] |
Set different color to specifc items in QListWidget | 39,995,688 | <p>I have a <code>QListWidget</code> and I want to add border bottom to each item of the list and set a background color to items and I want to set to specific items a different background color.
So I used <code>my_list.setStyleSheet("QListWidget::item { border-bottom: 1px solid red; background-color: blue;}")</code> a... | 2 | 2016-10-12T09:54:42Z | 39,998,051 | <p>You can't use a combination of stylesheets and style settings on a widget â the stylesheet will override any settings on individual items. For example, the following code uses <code>setBackground</code> on each item to change the background colour.</p>
<pre><code>from PyQt5.QtGui import *
from PyQt5.QtWidgets imp... | 1 | 2016-10-12T11:59:07Z | [
"python",
"pyqt",
"pyqt5"
] |
Pandas find first nan value by rows and return column name | 39,995,707 | <p>I have a dataframe like this </p>
<pre><code>>>df1 = pd.DataFrame({'A': ['1', '2', '3', '4','5'],
'B': ['1', '1', '1', '1','1'],
'C': ['c', 'A1', None, 'c3',None],
'D': ['d0', 'B1', 'B2', None,'B4'],
'E': ['A', None, 'S', None,'S'],
'F': ['... | 1 | 2016-10-12T09:55:28Z | 39,996,080 | <p>I think you can create boolean dataframe by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="nofollow"><code>DataFrame.isnull</code></a>, then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean i... | 2 | 2016-10-12T10:15:01Z | [
"python",
"pandas"
] |
Pandas find first nan value by rows and return column name | 39,995,707 | <p>I have a dataframe like this </p>
<pre><code>>>df1 = pd.DataFrame({'A': ['1', '2', '3', '4','5'],
'B': ['1', '1', '1', '1','1'],
'C': ['c', 'A1', None, 'c3',None],
'D': ['d0', 'B1', 'B2', None,'B4'],
'E': ['A', None, 'S', None,'S'],
'F': ['... | 1 | 2016-10-12T09:55:28Z | 39,996,092 | <p>I would use a combination of <code>itertools</code> and <code>numpy.where</code>, along with <code>pd.DataFrame.isnull</code>:</p>
<pre><code>>>> df1.isnull()
A B C D E F G
0 False False False False False False False
1 False False False False True False F... | 0 | 2016-10-12T10:15:36Z | [
"python",
"pandas"
] |
gis calculate distance between point and polygon / border | 39,995,839 | <p>I want to calculate the distance between a point and the border of a country using python / <code>shapely</code>. It should work just fine point.distance(poly) e.g. demonstrated here <a href="http://stackoverflow.com/questions/33311616/find-coordinate-of-closest-point-on-polygon-shapely">Find Coordinate of Closest P... | 0 | 2016-10-12T10:03:01Z | 39,999,017 | <p>According to <a href="http://geopandas.org/reference.html" rel="nofollow">geopandas</a> documentation, a GeoSeries is a vector of geometries (in your case, <code>0 (POLYGON...</code> tells that you have just one object, but it is still a vector). There should be a way of getting the first geometry element. GeoSeries... | 2 | 2016-10-12T12:49:15Z | [
"python",
"gis",
"distance",
"shapely",
"geopandas"
] |
pyschools square root approximation | 39,995,912 | <p>I am new to Python and stackoverflow. I have been trying to solve Pyschools 'while loop' example for square root approximation (Topic 5: Question 9). However I am unable to get the desired output. I am not sure if this issue is related to the loop or the formula. Here is the question:</p>
<blockquote>
<p>Create a... | 1 | 2016-10-12T10:06:37Z | 39,996,916 | <p>This is why your code does what it does:</p>
<p>After the line <code>maxsq = minsq</code> is executed, both of those values are 1.</p>
<p>When we come to the loop</p>
<pre><code>while i*i<=num: # set 'while' termination condition
if i*i<=num and i >=minsq: # complete inequality c... | 0 | 2016-10-12T10:59:48Z | [
"python"
] |
Draw a closed and filled contour | 39,996,028 | <p>I am trying to draw a closed contour an fill it up with (transparent or whatever) color with <code>folium</code>. The lacking docs are not helpful, any ideas how to do that ?</p>
<p>This is my current code</p>
<pre><code>m = folium.Map(location=[46, 2], zoom_start=5)
pts = [
[43.601795137863135, 1.451673278566412... | 0 | 2016-10-12T10:12:17Z | 40,113,212 | <p>This is not documented (nothing is really documented ATM), but this works</p>
<pre><code>m = folium.Map(location=[46, 2], zoom_start=5)
pts = [
[43.601795137863135, 1.451673278566412],
[43.61095574264419, 1.437239509310642],
[43.60999839038903, 1.45630473303456],
[43.60607351937904, 1.438762676051137],
[43.5972552... | 0 | 2016-10-18T16:13:01Z | [
"python",
"folium"
] |
How to run python + google app engine application locally but pointing to live google datastore? | 39,996,067 | <p>I am developing an application using python and google app engine. It is using local database. I want to run my code which points to google live datastore. Will you please guide how to configure my app to point to live google datastore instead of local so that I can check my code against live datastore?</p>
| 1 | 2016-10-12T10:14:13Z | 40,010,133 | <p>There's a tool available called the Remote API that should provide the functionality you're asking about. The documentation there should provide you with what you need to interact with the actual datastore. It's available for other languages as well, but here is the link to the Python documentation:</p>
<p><a href=... | 1 | 2016-10-12T23:51:18Z | [
"python",
"google-app-engine"
] |
Remove special characters (in list) in string | 39,996,097 | <p>I have a bunch of special characters which are in a list like:</p>
<pre><code>special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''', r''' ''']
</code></pre>
<p>... | -1 | 2016-10-12T10:15:54Z | 39,996,232 | <p>This can be solved with a simple generator expression:</p>
<pre><code>>>> ''.join(ch for ch in stringer if ch not in special)
'M\xc3\xbcllermystringiscool'
</code></pre>
<p><strong>Note that this also removes the spaces</strong>, since they're in your <code>special</code> list (the last element). If you d... | 1 | 2016-10-12T10:23:14Z | [
"python",
"regex"
] |
Remove special characters (in list) in string | 39,996,097 | <p>I have a bunch of special characters which are in a list like:</p>
<pre><code>special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''', r''' ''']
</code></pre>
<p>... | -1 | 2016-10-12T10:15:54Z | 39,996,288 | <p>If you remove the space from your specials you can do it using <code>re.sub()</code> but note that first you need to escape the special regex characters.</p>
<pre><code>In [58]: special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
r'''[''', r''']'''... | 0 | 2016-10-12T10:26:36Z | [
"python",
"regex"
] |
Share python source code files between Azure Worker Roles in the same project | 39,996,098 | <p>I have a single Azure Cloud Service as a project in Visual Studio 2015, which contains 2 Python Worker Roles.</p>
<p>They each have their own folder with source code files, and they are deployed to separate VMs. However, they both rely on some identical pieces of code. Right now my solution is to just include a cop... | 0 | 2016-10-12T10:15:54Z | 39,997,193 | <p>Likely many ways to solve your problem, but specifically from a worker role standpoint: Worker (and web) roles have definable startup tasks, allowing you to execute code/script during role startup. This allows you to do things like copying content from blob storage to local disk on your role instance. In this scenar... | 0 | 2016-10-12T11:15:00Z | [
"python",
"azure",
"azure-worker-roles",
"azure-cloud-services"
] |
Pass argument to flask from javascript | 39,996,133 | <p>When pressing a button i call a javascript function in my html file which takes two strings as parameters (from input fields). When the function is called i want to pass these parameters to my flask file and call another function there. How would i accomplish this?</p>
<p>The javascript:</p>
<pre><code><script&... | 0 | 2016-10-12T10:17:34Z | 39,996,313 | <p>From JS code, call (using GET method) the URL to your flask route, passing parameters as query args:</p>
<pre><code>/list?freesearch=value1,limit_content=value2
</code></pre>
<p>Then in your function definition:</p>
<pre><code>@app.route('/list')
def alist():
freesearch = request.args.get('freesearch')
li... | 0 | 2016-10-12T10:27:49Z | [
"javascript",
"python",
"flask",
"jinja2"
] |
How to dynamically print list values? | 39,996,254 | <p>This Code Works Fine.....But it's like static.
I don't know what to do to make it work in dynamic way?
I want:-
When user inputs 3 number of cities it should give</p>
<blockquote>
<p>a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city
2 and "+li[2]+" as city 3 on your trip"</p>
</blockquote>
... | 0 | 2016-10-12T10:24:25Z | 39,996,385 | <p>You should do something like this</p>
<pre><code>a = 'You would like to visit ' + ' and '.join('{0} as city {1}'.format(city, index) for index, city in enumerate(li, 1)) + ' on your trip'
</code></pre>
| 2 | 2016-10-12T10:30:51Z | [
"python"
] |
How to dynamically print list values? | 39,996,254 | <p>This Code Works Fine.....But it's like static.
I don't know what to do to make it work in dynamic way?
I want:-
When user inputs 3 number of cities it should give</p>
<blockquote>
<p>a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city
2 and "+li[2]+" as city 3 on your trip"</p>
</blockquote>
... | 0 | 2016-10-12T10:24:25Z | 39,996,412 | <p>You can build the string with a combination of <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">string formatting</a>, <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>str.join</code></a> and <a href="https://docs.python.org/2/library/function... | 0 | 2016-10-12T10:32:06Z | [
"python"
] |
How to dynamically print list values? | 39,996,254 | <p>This Code Works Fine.....But it's like static.
I don't know what to do to make it work in dynamic way?
I want:-
When user inputs 3 number of cities it should give</p>
<blockquote>
<p>a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city
2 and "+li[2]+" as city 3 on your trip"</p>
</blockquote>
... | 0 | 2016-10-12T10:24:25Z | 39,996,508 | <p>create another for loop and save your cities to an array. afterwords, concat the array using "join" and put put everything inside the string:</p>
<pre><code>cities = []
for i in range(0,len(li), 1):
cities.append("%s as city %i" % (li[i], i))
cities_str = " and ".join(cities)
a = "You would like to visit %s on... | 0 | 2016-10-12T10:37:43Z | [
"python"
] |
Correct way to get allowed arguments from ArgumentParser | 39,996,295 | <p><strong>Question:</strong> What is the intended / official way of accessing possible arguments from an existing <code>argparse.ArgumentParser</code> object?</p>
<p><strong>Example:</strong> Let's assume the following context:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--... | 7 | 2016-10-12T10:26:59Z | 39,997,213 | <p>I don't think there is a "better" way to achieve what you want.</p>
<hr>
<p>If you really don't want to use the <code>_option_string_actions</code> attribute, you could process the <code>parser.format_usage()</code> to retrieve the options, but doing this, you will get only the short options names.</p>
<p>If you ... | 3 | 2016-10-12T11:15:54Z | [
"python",
"argparse"
] |
Correct way to get allowed arguments from ArgumentParser | 39,996,295 | <p><strong>Question:</strong> What is the intended / official way of accessing possible arguments from an existing <code>argparse.ArgumentParser</code> object?</p>
<p><strong>Example:</strong> Let's assume the following context:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--... | 7 | 2016-10-12T10:26:59Z | 39,997,271 | <p>I have to agree with Tryph's answer.</p>
<p>Not pretty, but you can retrieve them from <code>parser.format_help()</code>:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', type=str)
goal = parser._option_string_actions.keys()
def get_allowed_arguments(parser):
... | 0 | 2016-10-12T11:19:22Z | [
"python",
"argparse"
] |
Correct way to get allowed arguments from ArgumentParser | 39,996,295 | <p><strong>Question:</strong> What is the intended / official way of accessing possible arguments from an existing <code>argparse.ArgumentParser</code> object?</p>
<p><strong>Example:</strong> Let's assume the following context:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--... | 7 | 2016-10-12T10:26:59Z | 40,007,285 | <p>First a note on the <code>argparse</code> docs - it's basically a how-to-use document, not a formal API. The standard for what <code>argparse</code> does is the code itself, the unit tests (<code>test/test_argparse.py</code>), and a paralyzing concern for backward compatibility.</p>
<p>There's no 'official' way of... | 0 | 2016-10-12T19:58:25Z | [
"python",
"argparse"
] |
Correct way to get allowed arguments from ArgumentParser | 39,996,295 | <p><strong>Question:</strong> What is the intended / official way of accessing possible arguments from an existing <code>argparse.ArgumentParser</code> object?</p>
<p><strong>Example:</strong> Let's assume the following context:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--... | 7 | 2016-10-12T10:26:59Z | 40,032,361 | <p>This started as a joke answer, but I've learned something since - so I'll post it.</p>
<p>Assume, we know the maximum length of an option allowed. Here is a nice answer to the question in this situation:</p>
<pre><code>from itertools import combinations
def parsable(option):
try:
return len(parser.par... | 1 | 2016-10-13T22:58:45Z | [
"python",
"argparse"
] |
Pykwalify: YAML Schema validation error | 39,996,464 | <p>I am writing a config file in <code>YAML</code> and its corresponding schema in <code>PyKwalify</code>.</p>
<p>when I compile with <code>pykwalify</code>, I get this error</p>
<pre><code>NotMappingError: error code 6: Value: None is not of a mapping type: Path: '/'
</code></pre>
<p>what does this error imply? </... | 0 | 2016-10-12T10:35:22Z | 40,005,476 | <p>It implies that instead of providing a mapping, which could have the form of a block style:</p>
<pre><code>a: 1
b: 2
</code></pre>
<p>of a flow style:</p>
<pre><code>{a: 1, b: 2}
</code></pre>
<p>you provided the null scalar (<code>null</code>, <code>~</code>) or no scalar:</p>
<pre><code>x:
</code></pre>
<p>... | 0 | 2016-10-12T18:07:11Z | [
"python",
"yaml"
] |
Find a specific word from a list in python | 39,996,485 | <p>So I have a list like below-</p>
<pre><code>list = [scaler-1, scaler-2, scaler-3, backend-1, backend-2, backend-3]
</code></pre>
<p>I want to create another list from it with the words which starts with 'backend'.How can i do that ?</p>
<p>Please note the content of the list will change from system to system, I w... | -3 | 2016-10-12T10:36:49Z | 39,996,548 | <p>First off, do not use the name <code>list</code> for assignment to your objects, you'll shadow the builtin list type.</p>
<p>Then, you can use a <em>list comprehension</em> with <a href="https://docs.python.org/2/library/stdtypes.html#str.startswith" rel="nofollow"><code>str.startswith</code></a> in a filter:</p>
... | 3 | 2016-10-12T10:40:01Z | [
"python"
] |
handling a lot of parameters in luigi | 39,996,544 | <p>In a lot of my projects I use <a href="http://luigi.readthedocs.io/en/stable/" rel="nofollow">luigi</a> as a pipelining tool. This made me think of employing it to implement a parameter search. The standard <code>luigi.file.LocalTarget</code> has a very naive approach to deal with parameters, which is also shown in ... | 0 | 2016-10-12T10:39:48Z | 40,075,143 | <p>You might get a better response to this sort of proposal on the mailing list. The Luigi task code already does generate an MD5 hash of the parameters to generate a unique task identifier which you could grab.</p>
<p><a href="https://github.com/spotify/luigi/blob/master/luigi/task.py#L79-L82" rel="nofollow">https://... | 0 | 2016-10-16T20:33:21Z | [
"python",
"parameter-passing",
"luigi"
] |
Is it possible to consume from every queue with pika? | 39,996,583 | <p>I'm trying to set up a program that will consume from every queue in RabbitMQ and depending on certain messages it will run certain scripts. Unfortunately while adding consumers if it runs into a single error (i.e. timeout or queue not found) the entire channel is dead. Additionally queues come and go so it has to r... | 0 | 2016-10-12T10:41:48Z | 40,007,113 | <p>It possible to consume from every queue in any language. It's also wrong and if this is something that is required, then the whole design/setup should be re-thought.</p>
<p>EDIT after comments:</p>
<p>Basically, you'd need to get the names of all existing queues which can be programmatically done via the <a href="... | 4 | 2016-10-12T19:48:21Z | [
"python",
"rabbitmq",
"pika"
] |
Python Minimum Skew function | 39,996,632 | <p>I used following code to find MinimumSkew:</p>
<pre><code>genome = "TAAAGACTGCCGAGAGGCCAACACGAGTGCTAGAACGAGGGGCGTAAACGCGGGTCCGAT"
def Skew(genome):
Skew = {}
Skew[0] = 0
for i in range(1, len(genome)+1):
if genome[i - 1] == "G":
Skew[i] = Skew[i - 1] + 1
elif genome[i - 1] == "C":
Skew... | 0 | 2016-10-12T10:44:40Z | 39,998,275 | <p>There are much easier solutions to calculate skew. Here is one approach:</p>
<pre><code>def skew(genome):
res = []
cntr = 0
res.append(cntr)
for i in genome:
if i == 'C':
cntr -= 1
if i == "G":
cntr += 1
res.append(cntr)
return [str(i) for i, j in ... | 0 | 2016-10-12T12:10:20Z | [
"python"
] |
Scraping HTML data from website in Python | 39,996,721 | <p>I'm trying to scrape certain pieces of HTML data from certain websites, but I can't seem to scrape the parts I want. For instance I set myself the challenge of scraping the number of followers from <a href="http://freelegalconsultancy.blogspot.co.uk/" rel="nofollow">this blog</a>, but I can't seem to do so. </p>
<p... | 0 | 2016-10-12T10:49:32Z | 39,996,983 | <p>You can't grab the followers as it's a widget loaded by javascript. You need to grab parts of the html by css class or id or by the element.</p>
<p>E.g:</p>
<pre><code>from bs4 import BeautifulSoup
from urllib import urlopen
html = urlopen('http://freelegalconsultancy.blogspot.co.uk/')
soup = BeautifulSoup(html)... | 1 | 2016-10-12T11:02:46Z | [
"python",
"html"
] |
How to get a list of all of a database's secondary indixes in RethinkDB | 39,996,756 | <p>In Python, how can I get a list of all a database's secondary indixes?</p>
<p>For example, in the web UI under "Tables" you can see the list of "Secondary indexes" (in this case only <code>timestamp</code>); I would like to get this in the Python environment.</p>
<p><a href="https://i.stack.imgur.com/jky7D.png" re... | 0 | 2016-10-12T10:51:34Z | 39,997,277 | <p>Check <a href="https://www.rethinkdb.com/docs/secondary-indexes/python/" rel="nofollow">this</a> doc about secondary indexes in RethinkDB.</p>
<p>You can get list of all indexes on table (e.x. "users") using this query:</p>
<pre><code>r.table("users").index_list()
</code></pre>
<p>If you want to get all secondary... | 1 | 2016-10-12T11:19:33Z | [
"python",
"rethinkdb"
] |
Opening two webservers via one ps1 script | 39,996,792 | <p>I've tried running the following, via PowerShell, in a single ps1 script in the hope of two localservers opening on different ports - only 8080 is opened:</p>
<pre><code>cd "\\blah\Statistics\Reporting\D3\walkthroughs\letsMakeABarChart"
python -m http.server 8080
cd "\\foo\data_science\20161002a_d3js\examples"
p... | 1 | 2016-10-12T10:53:24Z | 39,996,864 | <p>The first python invoke probably <em>doesn't return</em> so you could use the <code>Start-Job</code> cmdlet:</p>
<pre><code>$job1 = start-job -scriptblock {
cd "\\blah\Statistics\Reporting\D3\walkthroughs\letsMakeABarChart"
python -m http.server 8080
}
$job2 = start-job -scriptblock {
cd "\\foo\d... | 1 | 2016-10-12T10:56:53Z | [
"python",
"powershell"
] |
Generate random numbers in range from INPUT (python) | 39,996,814 | <p>This is a question close to some others I have found but they don't help me so I'm asking specifically for me and my purpose this time. </p>
<p>I'm coding for a bot which is supposed to ask the user for max and min in a range, then generating ten random numbers within that range. When validating I'm told both <code... | 3 | 2016-10-12T10:54:41Z | 39,996,891 | <p>No. <code>random.randint</code> is not a builtin function. You'll have to <em>import</em> the <code>random</code> module to use the function.</p>
<p>On another note, <code>i</code> was evidently not used in the loop, so you'll conventionally use the underscore <code>_</code> in place of <code>i</code></p>
<pre><co... | 6 | 2016-10-12T10:58:40Z | [
"python"
] |
Generate random numbers in range from INPUT (python) | 39,996,814 | <p>This is a question close to some others I have found but they don't help me so I'm asking specifically for me and my purpose this time. </p>
<p>I'm coding for a bot which is supposed to ask the user for max and min in a range, then generating ten random numbers within that range. When validating I'm told both <code... | 3 | 2016-10-12T10:54:41Z | 39,997,027 | <p>A couple of points worth mentioning with your original function:</p>
<ul>
<li>the <code>random</code> module is not built-in, you have to explicitly import it.</li>
<li><code>input</code> always returns strings, so you have to convert them to integers, before passing them to <code>random.randint</code></li>
<li><co... | 2 | 2016-10-12T11:04:56Z | [
"python"
] |
How to create a mapping to execute python code from Vim? | 39,996,852 | <p>Here's the steps I follow to execute python code from Vim:</p>
<ol>
<li>I write a python source code using Vim</li>
<li>I execute it via <code>:w !python</code></li>
</ol>
<p>and I'd like a shorter way to execute the code, so I searched the Internet for a shortcut key such as this map:</p>
<pre><code>autocmd File... | 0 | 2016-10-12T10:56:21Z | 39,996,978 | <p>Interacting with command-line through vim, the much preferred way would be with exclamation.<br>Instead of:</p>
<pre><code>:exec '!python' shellescape(@%, 1)<cr>
</code></pre>
<p>Try doing the easy way:</p>
<pre><code>:update<bar>!python %<CR>
</code></pre>
<p>here in the above code:<br>
<code>... | 1 | 2016-10-12T11:02:36Z | [
"python",
"vim",
"compilation",
"shortcut"
] |
Need Help on Python | 39,997,053 | <p>I just wrote the code below, and the problem is when I write BANKISGADZARCVA, it still shows a print of WESIERIMUSHAOBA.</p>
<pre><code>print("Gamarjoba")
print("tqveni davalebaa ishovot fuli valis gadasaxdelad")
print("Fulis sashovnelad gaqvt ori gza, WESIERIMUSHAOBA da BANKISGADZARCVA")
input('Airchiet Fulis Shov... | -2 | 2016-10-12T11:06:32Z | 39,997,082 | <p>Python needs indentation. Try this:</p>
<pre><code>print("Gamarjoba")
print("tqveni davalebaa ishovot fuli valis gadasaxdelad")
print("Fulis sashovnelad gaqvt ori gza, WESIERIMUSHAOBA da BANKISGADZARCVA")
x = input('Airchiet Fulis Shovnis Gza: ')
if "WESIERIMUSHAOBA" in x:
print("Sadaa Samushao Am Mtavrobis Xe... | -1 | 2016-10-12T11:08:00Z | [
"python"
] |
How can I add rows for all dates between two columns? | 39,997,063 | <pre><code>import pandas as pd
mydata = [{'ID' : '10', 'Entry Date': '10/10/2016', 'Exit Date': '15/10/2016'},
{'ID' : '20', 'Entry Date': '10/10/2016', 'Exit Date': '18/10/2016'}]
mydata2 = [{'ID': '10', 'Entry Date': '10/10/2016', 'Exit Date': '15/10/2016', 'Date': '10/10/2016'},
{'ID': '10', '... | 1 | 2016-10-12T11:06:57Z | 39,997,231 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> for reshaping, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> and remove column <code>variable</... | 1 | 2016-10-12T11:16:35Z | [
"python",
"datetime",
"pandas",
"resampling",
"melt"
] |
multiple console windows for one Python script | 39,997,081 | <p>I've seen similar questions such as this one: <a href="http://stackoverflow.com/questions/12122535">keep multiple console windows open from batch</a>.</p>
<p>However, I have a different situation. I do not want to run a different script in a different console window. My idea is to have socket running as a server an... | 0 | 2016-10-12T11:07:58Z | 40,033,234 | <p>A process can only be attached to one console (i.e. instance of conhost.exe) at a time, and a console with no attached processes automatically closes. You would need to spawn a child process with <code>creationflags=CREATE_NEW_CONSOLE</code>. </p>
<p>The following demo script requires Windows Python 3.3+. It spawns... | 1 | 2016-10-14T00:45:24Z | [
"python",
"windows",
"windows-console"
] |
Is there an anonymous call of a method in Python? | 39,997,132 | <p>This is my database manager class:</p>
<pre><code>class DatabaseManager(object):
def __init__(self):
super().__init__()
self.conn = sqlite3.connect('artist.db')
self.c = self.conn.cursor()
def create_table(self):
self.c.execute(
'CREATE TABLE IF NOT EXISTS artist... | 0 | 2016-10-12T11:11:11Z | 39,997,201 | <p>As @Remcogerlich said, you are assigning the instantiation to a variable. If you just don't do so, you can approach what you want.</p>
<pre><code>DatabaseManager().retrieve_artist('asdf')
AnyOtherClass().callAnyMethod()
# both disappeared
</code></pre>
<p>In this way, Python executes the instantiation, calls th... | 0 | 2016-10-12T11:15:26Z | [
"python",
"python-2.7",
"python-3.x"
] |
Using Google Appengine Python (Webapp2) I need to authenticate to Microsoft's new V2 endpoint using OpenID Connect | 39,997,134 | <p>There are built in decorators that easily allow me to access Google's own services but how can I overload these decorators to call other endpoints, specifically Microsofts V2 Azure endpoint (I need to authenticate Office 365 users).</p>
<p>Code snippet which I would like to override to call other end points such as... | 0 | 2016-10-12T11:11:12Z | 40,134,416 | <p>Having wasted a lot of time on this I can confirm that you CAN overload the decorator to direct to the Azure V2 endpoint using the code below:</p>
<pre><code>decorator = OAuth2Decorator(
client_id='d4ea6ab9-adf4-4aec-9b99-675cf46XXX',
auth_uri='https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
... | 0 | 2016-10-19T14:33:11Z | [
"python",
"google-app-engine",
"azure",
"office365",
"webapp2"
] |
Argparse: Default values not shown for subparsers | 39,997,152 | <p>I have the problem that I am not seeing any default values for arguments when specifying them via add_argument for subparsers using the argparse Python package.</p>
<p>Some research said that you need non-empty help-parameters set for each add_argument step and you need ArgumentDefaultsHelpFormatter as formatter_cl... | 1 | 2016-10-12T11:12:20Z | 39,997,364 | <p>Specify <code>formatter_class</code> when adding sub-parsers.</p>
<pre><code>subparsers = parser.add_subparsers(help="", dest="command")
fooparser = subparsers.add_parser('foo', help='Do foo',
formatter_class=ArgumentDefaultsHelpFormatter)
...
barparser = subparsers.add_parser('b... | 1 | 2016-10-12T11:24:17Z | [
"python",
"argparse"
] |
Robot Framework - check if element defined by xpath exists | 39,997,176 | <p>I'm wondering, I'd love to find or write condition to check if some element exists. If it does than I want to execute body of IF condition. If it doesn't exist than to execute body of ELSE.</p>
<p>Is there some condition like this or is it necessary to write by myself somehow?</p>
| -1 | 2016-10-12T11:14:01Z | 40,018,399 | <p>By locating the element using xpath, I assume that you're using <code>Sselenium2Library</code>. In that lib there is a keyword named: </p>
<p><code>Page Should Contain Element</code> which requires an argument, which is a <code>selector</code>, for example the xpath that defines your element. </p>
<p>The keyword f... | 0 | 2016-10-13T10:25:25Z | [
"python",
"testing",
"xpath",
"automated-tests",
"robotframework"
] |
Python numpy array assignment to integer indexed flat slice | 39,997,202 | <p>While learning numpy, I wrote code which doing LSB(steganography) encryption:</p>
<pre><code>def str2bits_nparray(s):
return np.array(map(int, (''.join(map('{:07b}'.format, bytearray(s))))), dtype=np.bool)
def LSB_encode(img, msg, channel):
msg_bits = str2bits_nparray(msg)
xor_mask = np.zeros_like(img,... | 0 | 2016-10-12T11:15:33Z | 39,997,869 | <p>IIUC, here's an approach to get the linear indices, then slice to the length of no. of elems required to be set and then perform the setting -</p>
<pre><code>m,n,r = xor_mask.shape # Store shape info
# Create range arrays corresponding to those shapes
x,y,z = np.ix_(np.arange(m),np.arange(n),channel)
# Get the i... | 1 | 2016-10-12T11:49:12Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"slice"
] |
Flask python manage.py db upgrade raise error | 39,997,252 | <p>I am working on an flask project which contain a large amount of models and some of them make user of <code>from sqlalchemy.dialects.postgresql import JSONB</code>. Form management i created manage.py as per this <a href="http://flask-migrate.readthedocs.io/en/latest/" rel="nofollow">link</a>. <code>pyhton manage.py... | 0 | 2016-10-12T11:18:11Z | 39,997,959 | <p>You need to import that <code>Text</code></p>
<p>As i searched it comes from <code>sqlalchemy.types</code>, so you need at the top of file import it</p>
<pre><code>from sqlalchemy.types import Text
</code></pre>
<p>But you don't even need to supply <code>astext_type</code> as a parameter, because it defaults to <... | 1 | 2016-10-12T11:54:00Z | [
"python",
"postgresql",
"flask",
"flask-sqlalchemy"
] |
editing and reordering tuples in a list | 39,997,293 | <p>I have a list of tuples:</p>
<pre><code>lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")]
</code></pre>
<p>The tuples have the structure <code>(int, string)</code> and start from 1 and the max value is 10. I would like to edit and reorder them to the following:</p>
<pre><code>lst2 = [(1, "text"), (2, "m... | 1 | 2016-10-12T11:20:37Z | 39,997,382 | <pre><code>lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")]
d = dict(lst)
lst2 = [(i, d.get(i, "")) for i in range(1, 11)]
</code></pre>
<p><strong>EDIT</strong></p>
<p>Or, using <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a>:</p>
<pre><... | 4 | 2016-10-12T11:25:08Z | [
"python"
] |
editing and reordering tuples in a list | 39,997,293 | <p>I have a list of tuples:</p>
<pre><code>lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")]
</code></pre>
<p>The tuples have the structure <code>(int, string)</code> and start from 1 and the max value is 10. I would like to edit and reorder them to the following:</p>
<pre><code>lst2 = [(1, "text"), (2, "m... | 1 | 2016-10-12T11:20:37Z | 39,997,427 | <p>Your inner for is excessive here.
Instead of for k in range(1,11): you should use if k>=1 and k<=10:</p>
| 1 | 2016-10-12T11:27:48Z | [
"python"
] |
editing and reordering tuples in a list | 39,997,293 | <p>I have a list of tuples:</p>
<pre><code>lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")]
</code></pre>
<p>The tuples have the structure <code>(int, string)</code> and start from 1 and the max value is 10. I would like to edit and reorder them to the following:</p>
<pre><code>lst2 = [(1, "text"), (2, "m... | 1 | 2016-10-12T11:20:37Z | 39,997,537 | <p>There are already better answers, but just to show you how your loop could be modified to yield the desired result:</p>
<pre><code>for k in range(1,11):
exists=False
for tupl in lst:
if tupl[0] == k:
lst2.append((k, tupl[1]))
exists = True
break
if not exists:
lst2.append((k, ""))
pr... | 1 | 2016-10-12T11:32:41Z | [
"python"
] |
root user execution fails | 39,997,297 | <p>When I run <code>python abc.py</code> it runs fine</p>
<p>But when I do sudo <code>python abc.py</code> then it shows some packages missing error. Of the several import errors, here's the one:</p>
<pre class="lang-none prettyprint-override"><code>ImportError: No module named numpy
</code></pre>
<p>Why?</p>
<p>Wh... | 3 | 2016-10-12T11:21:01Z | 39,997,375 | <p>The sudo environment may not contain your <code>PYTHONPATH</code></p>
<p><code>/etc/sudoers</code> contains Defaults <code>env_reset</code>.
Simply add Defaults <code>env_keep += "PYTHONPATH"</code> to <code>/etc/sudoers</code> and it will work just fine with <code>sudo</code>.</p>
| 1 | 2016-10-12T11:24:47Z | [
"python",
"linux",
"python-2.7"
] |
write times in NetCDF file | 39,997,314 | <p>While using the NETCDF4 package write times in netCDF file.</p>
<pre><code>dates = []
for iday in range(84):
dates.append(datetime.datetime(2016, 10, 1) + atetime.timedelta(hours = iday))
times[:] = date2num(dates, units=times.units, calendar = imes.calendar)
# print times[:]
for ii, i in enumerate(times[:]):
... | 1 | 2016-10-12T11:21:52Z | 39,998,698 | <p>Depending on the time units and datatype you choose, you may encounter floating point accuracy problems. For example, if you specify the time in <code>days since 1970-01-01 00:00</code>, 32 bit float is not sufficient and you should use a 64 bit float instead:</p>
<pre><code>import datetime
import netCDF4
times = ... | 1 | 2016-10-12T12:31:15Z | [
"python",
"netcdf"
] |
Error with .readlines()[n] | 39,997,324 | <p>I'm a beginner with Python.
I tried to solve the problem: "If we have a file containing <1000 lines, how to print only the odd-numbered lines? ". That's my code:</p>
<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
n=1
num_lines=sum(1 for line in f)
while n<num_lines:
... | 2 | 2016-10-12T11:22:13Z | 39,997,529 | <p>Well, I'd personally do it like this:</p>
<pre><code>def print_odd_lines(some_file):
with open(some_file) as my_file:
for index, each_line in enumerate(my_file): # keep track of the index of each line
if index % 2 == 1: # check if index is odd
print(each_line) # if it does... | 0 | 2016-10-12T11:32:08Z | [
"python",
"python-3.x",
"while-loop"
] |
Error with .readlines()[n] | 39,997,324 | <p>I'm a beginner with Python.
I tried to solve the problem: "If we have a file containing <1000 lines, how to print only the odd-numbered lines? ". That's my code:</p>
<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
n=1
num_lines=sum(1 for line in f)
while n<num_lines:
... | 2 | 2016-10-12T11:22:13Z | 39,997,559 | <p>This code will do exactly as you asked:</p>
<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
for i, line in enumerate(f.readlines()): # Iterate over each line and add an index (i) to it.
if i % 2 == 0: # i starts at 0 in python, so if i is even, the line is odd
... | 0 | 2016-10-12T11:33:32Z | [
"python",
"python-3.x",
"while-loop"
] |
Error with .readlines()[n] | 39,997,324 | <p>I'm a beginner with Python.
I tried to solve the problem: "If we have a file containing <1000 lines, how to print only the odd-numbered lines? ". That's my code:</p>
<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
n=1
num_lines=sum(1 for line in f)
while n<num_lines:
... | 2 | 2016-10-12T11:22:13Z | 39,997,580 | <p>As a fix, you need to type</p>
<pre><code>f.close()
f = open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')
</code></pre>
<p>everytime after you read through the file, in order to get back to the start.</p>
<p>As a side note, you should look up modolus % for finding odd numbers.</p>
| 0 | 2016-10-12T11:34:21Z | [
"python",
"python-3.x",
"while-loop"
] |
Error with .readlines()[n] | 39,997,324 | <p>I'm a beginner with Python.
I tried to solve the problem: "If we have a file containing <1000 lines, how to print only the odd-numbered lines? ". That's my code:</p>
<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
n=1
num_lines=sum(1 for line in f)
while n<num_lines:
... | 2 | 2016-10-12T11:22:13Z | 39,998,187 | <p>You have the call to <code>readlines</code> into a loop, but this is not its intended use,
because <code>readlines</code> ingests the whole of the file at once, returning you a LIST
of newline terminated strings.</p>
<p>You may want to save such a list and operate on it</p>
<pre><code>list_of_lines = open(filename... | 2 | 2016-10-12T12:05:30Z | [
"python",
"python-3.x",
"while-loop"
] |
is_max = s == s.max() | How should I read this? | 39,997,334 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' fo... | 4 | 2016-10-12T11:22:54Z | 39,997,371 | <p><code>s == s.max()</code> will evaluate to a boolean (due to the <code>==</code> in between the variables). The next step is storing that value in <code>is_max</code>.</p>
| 2 | 2016-10-12T11:24:36Z | [
"python",
"python-2.7",
"pandas"
] |
is_max = s == s.max() | How should I read this? | 39,997,334 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' fo... | 4 | 2016-10-12T11:22:54Z | 39,997,405 | <p>The code</p>
<p><code>is_max = s == s.max()</code></p>
<p>is evaluated as</p>
<p><code>is_max = (s == s.max())</code></p>
<p>The bit in parentheses is evaluated first, and that is either <code>True</code> or <code>False</code>. The result is assigned to <code>is_max</code>.</p>
| 2 | 2016-10-12T11:26:21Z | [
"python",
"python-2.7",
"pandas"
] |
is_max = s == s.max() | How should I read this? | 39,997,334 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' fo... | 4 | 2016-10-12T11:22:54Z | 39,997,436 | <p>In pandas <code>s</code> is very often <code>Series</code> (column in <code>DataFrame</code>).</p>
<p>So you compare all values in <code>Series</code> with <code>max</code> value of <code>Series</code> and get boolean mask. Output is in <code>is_max</code>. And then set style <code>'background-color: yellow'</code>... | 2 | 2016-10-12T11:28:03Z | [
"python",
"python-2.7",
"pandas"
] |
is_max = s == s.max() | How should I read this? | 39,997,334 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' fo... | 4 | 2016-10-12T11:22:54Z | 39,997,846 | <blockquote>
<p>is_max is EQUAL TO comparison of s and s_max</p>
</blockquote>
| 0 | 2016-10-12T11:48:33Z | [
"python",
"python-2.7",
"pandas"
] |
is_max = s == s.max() | How should I read this? | 39,997,334 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' fo... | 4 | 2016-10-12T11:22:54Z | 39,998,175 | <p>According to the document, <a href="https://docs.python.org/3/reference/expressions.html#evaluation-order" rel="nofollow">Evaluation order</a>:</p>
<blockquote>
<p>Notice that while evaluating an assignment, the right-hand side is
evaluated before the left-hand side.</p>
</blockquote>
<p>This is quite reasonab... | 0 | 2016-10-12T12:04:58Z | [
"python",
"python-2.7",
"pandas"
] |
TCP Client retrieving no data from the server | 39,997,379 | <p>I am trying to receive data from a TCP Server in python. I try to open a file at the server and after reading its content, try to send it to the TCP Client. The data is read correctly from the file as I try to print it first on the server side but nothing is received at the Client side.
PS. I am a beginner in networ... | 0 | 2016-10-12T11:24:58Z | 39,997,602 | <p>Add Accept() in while loop as below.</p>
<blockquote>
<p>while True: <BR>
client_socket, address = server_socket.accept()<BR>
print ("Conencted to - ",address,"\n")<BR>
......</p>
</blockquote>
| 1 | 2016-10-12T11:35:23Z | [
"python",
"sockets",
"tcp"
] |
TCP Client retrieving no data from the server | 39,997,379 | <p>I am trying to receive data from a TCP Server in python. I try to open a file at the server and after reading its content, try to send it to the TCP Client. The data is read correctly from the file as I try to print it first on the server side but nothing is received at the Client side.
PS. I am a beginner in networ... | 0 | 2016-10-12T11:24:58Z | 39,998,462 | <p>Try:</p>
<pre><code>#Get just the two bytes indicating the content length - client_socket.send(size.encode())
buffer = client_socket.recv(2)
size = len(buffer)
print size
print ("The file size is - ",buffer[0:2]," bytes")
#Now get the remaining. The actual content
print buffer.decode()
buffer = client_socket.re... | 1 | 2016-10-12T12:19:53Z | [
"python",
"sockets",
"tcp"
] |
convert Unicode to cyrillic | 39,997,386 | <p>I have lists with Unicode:</p>
<pre><code>words
[u'\xd1', u'\xd0\xb0', u'\xd0\xb8', u'\u043e', u'\xd1\x81', u'-', u'\xd0\xb2', u'\u0438', u'\u0441', u'\xd0\xb8\xd1', u'\xd1\x83', u'\u0432', u'\u043a', u'\xd0\xba', u'\xd0\xbf\xd0\xbe', u'|', u'search', u'\xd0\xbd\xd0\xbe', u'25', u'in', u'\xd0\xbd\xd0\xb0', u'\u043d... | 0 | 2016-10-12T11:25:23Z | 40,012,784 | <p>You have Russian already (at least some of it), you just need to print the strings, not the list, on an IDE/terminal that supports Russian characters. Here's an excerpt, printed with Python 2.7 on a UTF-8 terminal:</p>
<pre><code>L = [u'\u0442\u043e\u0432\u0430\u0440', u'\u0434\u0436\u0438\u043d\u0441\u044b']
pri... | 1 | 2016-10-13T05:14:37Z | [
"python",
"unicode",
"encoding",
"latin"
] |
need only link as an output | 39,997,410 | <p>I have multiple html tag I want to extract only content of 1st href="..." for example this single line of data.</p>
<pre><code><a class="product-link" data-styleid="1424359" href="/tops/biba/biba-beige--pink-women-floral-print-top/1424359/buy?src=search"><img _src="http://assets.myntassets.com/h_240,q_95,w... | 0 | 2016-10-12T11:26:33Z | 39,999,693 | <p>If you need a single "product link", just use <code>find()</code>:</p>
<pre><code>soup2.find('a', attrs={'class': 'product-link'})["href"]
</code></pre>
<p>Note that you can use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> location technique as we... | 0 | 2016-10-12T13:19:57Z | [
"python",
"python-2.7",
"beautifulsoup",
"data-cleansing"
] |
Python class to take care of MySQL connection keeps throwing an error | 39,997,429 | <p>I am trying to build a class using Python in order to handle all interactions with MySQL databases.
I have installed the MySQLdb module and tested the connection to the databases using a simple code.
When I run the following code:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect ( host="localhost", user="root" ... | 0 | 2016-10-12T11:27:50Z | 39,998,336 | <p>Isn't your MySQLdb.connect parameter syntax different in your examples? </p>
<p>In the working one you use named parameters for connect(host="localhost") etc. but in the class model you omit parameter names host=, user= etc and location based parameters do not seem to work.</p>
<p>Hannu</p>
| 0 | 2016-10-12T12:13:51Z | [
"python",
"mysql",
"python-2.7",
"class",
"mysql-python"
] |
Python class to take care of MySQL connection keeps throwing an error | 39,997,429 | <p>I am trying to build a class using Python in order to handle all interactions with MySQL databases.
I have installed the MySQLdb module and tested the connection to the databases using a simple code.
When I run the following code:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect ( host="localhost", user="root" ... | 0 | 2016-10-12T11:27:50Z | 40,005,022 | <p>Sorry guys! The code is fine, I was, systematically, inputing the name of a table instead of a database to the self.db variable .
The code works fine.</p>
| 0 | 2016-10-12T17:41:27Z | [
"python",
"mysql",
"python-2.7",
"class",
"mysql-python"
] |
How to retrieve PID from windows event log? | 39,997,471 | <p><a href="https://i.stack.imgur.com/dgTiR.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/dgTiR.jpg" alt="enter image description here"></a>I have a python code that uses WMI module of python to get windows event viewer logs. But I am unable to retrieve the PID of the process that generated the log.
My code :... | 0 | 2016-10-12T11:29:24Z | 39,998,098 | <p>The Win32 API call to get event log items is <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363674(v=vs.85).aspx" rel="nofollow">ReadEventLog</a> and this returns <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363646(v=vs.85).aspx" rel="nofollow">EVENTLOGRECORD</a> structure... | 0 | 2016-10-12T12:01:42Z | [
"python",
"wmi",
"pid",
"wmi-query",
"eventviewer"
] |
Finding the consecutive pairs of the values in a row and then operating on them in python | 39,997,575 | <p>I have a data frame in python like: <br></p>
<pre><code>item Value
abc 3
xyz 5
pqr 7
abc 3
pqr 7
abc 5
xyz 5
</code></pre>
<p>Now I want to add the first occurrence of any value and the second occurrence of that item's value in pairs,
so the output should be like:-<br></p>
<pre><code>item Value
... | -1 | 2016-10-12T11:34:17Z | 40,000,836 | <p>This is more of a question for logic than pandas but since you asked in pandas, there is a quick way to do this:</p>
<pre><code>df['value_to_add'] = df.sort_values('item').groupby('item').shift(-1)
df.dropna(inplace=True)
df['value'] = df.value + df.value_to_add
df.drop('value_to_add', inplace=True, axis=1)
</code... | 0 | 2016-10-12T14:10:04Z | [
"python",
"pandas"
] |
Can't use question mark (sqlite3, python) | 39,997,779 | <p>This code is stucks:</p>
<p><code>c.execute("select * from table_name where num=?", a)</code></p>
<p>And this is not:</p>
<p><code>c.execute("select * from table_name where num={}".format(a))</code></p>
<p>So what is wrong? Colmn in table is <code>int</code> and <code>a</code> is <code>int</code> too</p>
| -4 | 2016-10-12T11:45:27Z | 39,998,825 | <p>I'm not if it works the same on sqlite, but in mysql in order to use the "select from select" form, you must give each table an alias, like this:</p>
<pre><code>select count(*) from (select * from users as b where id=ID and lvl=LVL) as a
</code></pre>
<p>It might be the source of your problem.</p>
| -2 | 2016-10-12T12:38:32Z | [
"python",
"sqlite3"
] |
C++ uses twice the memory when moving elements from one dequeue to another | 39,997,840 | <p>In my project, I use <a href="https://github.com/pybind/pybind11" rel="nofollow">pybind11</a> to bind C++ code to Python. Recently I have had to deal with very large data sets (70GB+) and encountered need to split data from one <code>std::deque</code> between multiple <code>std::deque</code>'s. Since my dataset is s... | 3 | 2016-10-12T11:48:19Z | 40,068,900 | <p>The problem turned out to be caused by Data being created in one thread and then deallocated in another one. It is so because of malloc arenas in glibc <a href="https://siddhesh.in/posts/malloc-per-thread-arenas-in-glibc.html" rel="nofollow">(for reference see this)</a>. It can be nicely demonstrated by doing:</p>
... | 0 | 2016-10-16T09:41:51Z | [
"python",
"c++",
"out-of-memory",
"python-asyncio",
"pybind11"
] |
Wrong dimensions when building convolutional autoencoder | 39,997,894 | <p>I'm taking my first steps in Keras and struggling with the dimensions of my layers. I'm currently building a convolutional autoencoder that I would like to train using the MNIST dataset. Unfortunately, I cannot seem to get the dimensions right, and I'm having trouble to understand where is my mistake.</p>
<p>My mod... | 0 | 2016-10-12T11:50:24Z | 40,028,728 | <p>Looks like your input shape isn't correct. Try changing (1,28,28) to (28,28,1) and see if that works for you. For more details and other options to solve the problem, please refer to <a href="http://stackoverflow.com/questions/39848466/tensorflow-keras-convolution2d-valueerror-filter-must-not-be-larger-than-t/398828... | 1 | 2016-10-13T18:48:29Z | [
"python",
"python-2.7",
"deep-learning",
"keras",
"autoencoder"
] |
Wrong dimensions when building convolutional autoencoder | 39,997,894 | <p>I'm taking my first steps in Keras and struggling with the dimensions of my layers. I'm currently building a convolutional autoencoder that I would like to train using the MNIST dataset. Unfortunately, I cannot seem to get the dimensions right, and I'm having trouble to understand where is my mistake.</p>
<p>My mod... | 0 | 2016-10-12T11:50:24Z | 40,039,172 | <p>The reason was that while I changed my backend configuration in keras.json, I didn't change the image dimanesion, so it was still set to tensorflow.</p>
<p>Changing it to:</p>
<pre><code>{
"image_dim_ordering": "th",
"epsilon": 1e-07,
"floatx": "float32",
"backend": "theano"
}
</code></pre>
<p>... | 0 | 2016-10-14T09:04:20Z | [
"python",
"python-2.7",
"deep-learning",
"keras",
"autoencoder"
] |
Creating a recursive function for calculating R = x - N * y, with conditions | 39,997,920 | <p>I wish to create a function for calculating R = x - N * y, where x and y are floats and N is the largest positive integer, so that x > N * y.</p>
<p>The function should only take the inputs of x and y.</p>
<p>I have previously created the function through a loop, but having trouble trying to convert it to recursio... | 0 | 2016-10-12T11:51:44Z | 39,998,123 | <p>Here's a recursive way of computing R:</p>
<pre><code>def florec(x, y):
if x > y:
return florec(x-y, y)
return x
</code></pre>
<p>(Note it only works for positive floats.)</p>
<p>I don't know if this addresses your recursion issues. Maybe this use case is not best suited to illustrate recursion... | 2 | 2016-10-12T12:02:30Z | [
"python",
"python-3.x"
] |
Creating a recursive function for calculating R = x - N * y, with conditions | 39,997,920 | <p>I wish to create a function for calculating R = x - N * y, where x and y are floats and N is the largest positive integer, so that x > N * y.</p>
<p>The function should only take the inputs of x and y.</p>
<p>I have previously created the function through a loop, but having trouble trying to convert it to recursio... | 0 | 2016-10-12T11:51:44Z | 39,998,546 | <p>If you're trying to return a value at each incrementation, you can use a generator function:</p>
<pre><code>def florec(x, y):
N = 30 # not sure what you want N to start with
while True:
if x > N * y:
yield x - N * y
else:
break
N += 1
for i in florec(332.... | 0 | 2016-10-12T12:23:52Z | [
"python",
"python-3.x"
] |
Creating a recursive function for calculating R = x - N * y, with conditions | 39,997,920 | <p>I wish to create a function for calculating R = x - N * y, where x and y are floats and N is the largest positive integer, so that x > N * y.</p>
<p>The function should only take the inputs of x and y.</p>
<p>I have previously created the function through a loop, but having trouble trying to convert it to recursio... | 0 | 2016-10-12T11:51:44Z | 39,998,591 | <p>Per <a href="http://stackoverflow.com/users/4653485/j%C3%A9r%C3%B4me">Jerome</a>'s original comment, the function you're describing is the definition of the modulus. If you absolutely need to use recursion, the following will get it done.</p>
<pre><code>def florec(x, y, N=1):
R = x - N * y
if R < y:
... | 0 | 2016-10-12T12:25:19Z | [
"python",
"python-3.x"
] |
multiple connections to same spreadsheet (gspread) | 39,997,924 | <p>Good Morning, this is my first question so please bear with me! I created a system for doing a mock election at my high school that uses a raspberry pi and a touchscreen. The interface is handled through TKInter and the results are then appended to a google sheet using gspread. This allows me to then process the dat... | 1 | 2016-10-12T11:52:05Z | 40,091,230 | <p>The issue here is that if you have all four of these machines starting at the same time they will have a relatively similar state for the sheet. However, once a single machine has made a change the state for all the others becomes different from the actual sheet.</p>
<p>Lets say the sheet starts with N rows.</p>
<... | 0 | 2016-10-17T16:20:59Z | [
"python",
"gspread"
] |
How to run a zeppelin notebook using REST api and return results in python? | 39,998,000 | <p>I am running a zeppelin notebook using the following REST call from python:</p>
<p><code>import requests
requests.post('http://x.y.z.x:8080/api/notebook/job/2BZ3VJZ4G').json()</code></p>
<p>The output is {u'status': u'OK'}</p>
<p>But I want to return some results/exception(if any) from few blocks in the zeppelin ... | 1 | 2016-10-12T11:55:48Z | 40,102,838 | <p>Zeppelin has introduced a synchronous API to run a paragraph in its latest yet to be releases 0.7.0 version. You can clone the latest code form their repo and build a snapshot yourself. URL for API is <a href="http://[zeppelin-server]:[zeppelin-port]/api/notebook/run/[notebookId]/[paragraphId]" rel="nofollow">http:/... | 0 | 2016-10-18T08:06:55Z | [
"python",
"rest",
"apache-zeppelin"
] |
Passing captured video frame (numpy array object) from webcam feed to caffe model | 39,998,038 | <p>I am a beginner in Caffe and I am trying to use the Imagenet model for object classification. My requirement is that I want to use it from a webcam feed and detect the objects from the webcam feed.For this, I use the following code</p>
<pre><code> cap = cv2.VideoCapture(0)
while(True):
ret, frame... | 0 | 2016-10-12T11:58:37Z | 40,011,804 | <p>caffe.io.load_image does not do much. It only does the following :</p>
<ol>
<li>Read image from disk (given the path)</li>
<li>Make sure that the returned image has 3 dimensions (HxWx1 or HxWx3)</li>
</ol>
<p>(see source <a href="https://github.com/BVLC/caffe/blob/master/python/caffe/io.py#L279" rel="nofollow">caf... | 3 | 2016-10-13T03:26:22Z | [
"python",
"opencv",
"video",
"caffe",
"pycaffe"
] |
need to restart python while applying Celery config | 39,998,083 | <p>That's a small story...</p>
<p>I had this error:</p>
<blockquote>
<p>AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for'</p>
</blockquote>
<p>When changed tasks.py, like Diederik said at <a href="http://stackoverflow.com/questions/23215311/celery-with-rabbitmq-attributeerror-disabledb... | 0 | 2016-10-12T12:01:07Z | 39,999,436 | <p>If using the interpreter, you need to </p>
<pre><code>reload(tasks)
</code></pre>
<p>this will force reimport tasks module</p>
| 0 | 2016-10-12T13:08:45Z | [
"python",
"ipython",
"celery"
] |
Two Celery Processes Running | 39,998,138 | <p>I am debugging an issue where every scheduled task is run twice. I saw two processes named celery. Is it normal for two celery tasks to be running?</p>
<pre><code>$ ps -ef | grep celery
hgarg 303 32764 0 17:24 ? 00:00:00 /home/hgarg/.pythonbrew/venvs/Python-2.7.3/hgarg_env/bin/python /data/hgarg/current... | 0 | 2016-10-12T12:03:09Z | 40,053,897 | <p>There were two pairs of Celery processes, the older of which shouldn't have been. Killing them all and restarting celery seems to have fixed it. Without any other recent changes, unlikely that anything else could have caused it.</p>
| 0 | 2016-10-15T00:52:50Z | [
"python",
"django",
"celery"
] |
How to sum values grouped by a categorical column in pandas? | 39,998,184 | <p>I have data which has a categorical column that groups the data and other columns likes this in a dataframe <code>df</code>.</p>
<pre><code>id subid value
1 10 1.5
1 20 2.5
1 30 7.0
2 10 12.5
2 40 5
</code></pre>
<p>What I ... | 0 | 2016-10-12T12:05:27Z | 39,998,460 | <p>here we go</p>
<pre><code>df['id_sum'] = df.groupby('id')['value'].transform('sum')
df['proportion'] = df['value'] / df['id_sum']
</code></pre>
| 2 | 2016-10-12T12:19:42Z | [
"python",
"pandas",
"aggregate"
] |
I want to compile the __init__.py file and install into other folder in yocto build system? | 39,998,240 | <p>I want to compile the __init__.py file and install into other folder in yocto build system?</p>
<p>Scenario:</p>
<blockquote>
<p>This basically in yocto build system. Third party library as zipped file
is available in download folder in my yocto build system. But that
library does not have the __init__.py f... | 0 | 2016-10-12T12:08:31Z | 40,052,181 | <p>You can place empty file <strong>__init__.py</strong> along with recipe and add it to <strong>SRC_URI</strong> in this recipe:</p>
<pre><code>SRC_URI = "http://www.aaa/bbb.tar.gz \
file://__init__.py"
</code></pre>
<p>unpacker will just copy it to WORKDIR where the archive is unpacked.</p>
| 0 | 2016-10-14T21:20:54Z | [
"python",
"system",
"yocto"
] |
Append an empty row in dataframe using pandas | 39,998,262 | <p>I am trying to append an empty row at the end of dataframe but unable to do so, even trying to understand how pandas work with append function and still not getting it.</p>
<p>Here's the code:</p>
<pre><code>import pandas as pd
excel_names = ["ARMANI+EMPORIO+AR0143-book.xlsx"]
excels = [pd.ExcelFile(name) for nam... | 0 | 2016-10-12T12:09:34Z | 39,998,297 | <p>The correct function is:</p>
<pre><code>pd.append(..., axis = 0) # axis = 0 for rows
</code></pre>
| 0 | 2016-10-12T12:11:54Z | [
"python",
"python-2.7",
"pandas"
] |
Append an empty row in dataframe using pandas | 39,998,262 | <p>I am trying to append an empty row at the end of dataframe but unable to do so, even trying to understand how pandas work with append function and still not getting it.</p>
<p>Here's the code:</p>
<pre><code>import pandas as pd
excel_names = ["ARMANI+EMPORIO+AR0143-book.xlsx"]
excels = [pd.ExcelFile(name) for nam... | 0 | 2016-10-12T12:09:34Z | 39,998,624 | <p>You can add it by appending a Series to the dataframe as follows. I am assuming by blank you mean you want to add a row containing only "Nan".
You can first create a Series object with Nan. Make sure you specify the columns while defining 'Series' object in the -Index parameter.
The you can append it to the DF. Hope... | 0 | 2016-10-12T12:26:51Z | [
"python",
"python-2.7",
"pandas"
] |
How could I train a model in SPARK with MLlib with a Dataframe of String values? | 39,998,393 | <p>I am new on Apache SPARK and MLlib and I am trying to build a model to make a supervised classification over a dataset. The problema that I have is that all the examples I found in the internet are explanations of how to work with REGRESSION problems, and always with numerical values. But I have the next context:</p... | 0 | 2016-10-12T12:16:20Z | 39,998,713 | <p>You cannot. All variables have to be index and or encoded to be used with Spark ML/MLib. </p>
<p>Check:</p>
<ul>
<li><a href="https://spark.apache.org/docs/latest/ml-features.html" rel="nofollow">Extracting, transforming and selecting features</a></li>
<li><a href="https://spark.apache.org/docs/latest/mllib-featur... | 0 | 2016-10-12T12:31:53Z | [
"python",
"apache-spark",
"machine-learning",
"classification",
"prediction"
] |
How to delete a file without an extension? | 39,998,424 | <p>I have made a function for deleting files:</p>
<pre><code>def deleteFile(deleteFile):
if os.path.isfile(deleteFile):
os.remove(deleteFile)
</code></pre>
<p>However, when passing a FIFO-filename (without file-extension), this is not accepted by the os-module.
Specifically I have a subprocess create a FI... | 5 | 2016-10-12T12:17:51Z | 39,998,522 | <p><code>isfile</code> checks for <em>regular</em> file.</p>
<p>You could workaround it like this by checking if it exists but not a directory or a symlink:</p>
<pre><code>def deleteFile(filename):
if os.path.exists(filename) and not os.path.isdir(filename) and not os.path.islink(filename):
os.remove(file... | 6 | 2016-10-12T12:22:19Z | [
"python"
] |
Flask-Login - User returns to Anonymous after successful login then redirect | 39,998,516 | <p>I'm trying just to setup a base login model with developed code mostly from <a href="https://flask-login.readthedocs.io/en/latest/" rel="nofollow" title="Flask-Login">Flask-Login</a>. </p>
<p>After my user successfully logs in and I issue a <code>redirect(url_for('index'))</code>, the user loses his authentication... | 0 | 2016-10-12T12:21:56Z | 39,998,810 | <p>Add these functions to your <code>User</code> class.</p>
<pre><code>def is_authenticated(self):
return True
def is_active(self):
return self.active
def is_anonymous(self):
return False
</code></pre>
<p>If I remember correctly,<code>Flask-Login</code> requires them in your <code>User</code> class.</p>... | 0 | 2016-10-12T12:37:29Z | [
"python",
"flask-login"
] |
Flask-Login - User returns to Anonymous after successful login then redirect | 39,998,516 | <p>I'm trying just to setup a base login model with developed code mostly from <a href="https://flask-login.readthedocs.io/en/latest/" rel="nofollow" title="Flask-Login">Flask-Login</a>. </p>
<p>After my user successfully logs in and I issue a <code>redirect(url_for('index'))</code>, the user loses his authentication... | 0 | 2016-10-12T12:21:56Z | 40,010,704 | <p>Well, I need to answer my own question on a dumb oversight that I should have caught (bleary eyes?)</p>
<p>Simple fix in <code>def load_user(user_id):</code> where I needed to replace the line<br></p>
<p>Bad: <code>return User.query.get(user_id)</code></p>
<p>Good: <code>return User.query.filter_by(username=user_... | 0 | 2016-10-13T01:05:51Z | [
"python",
"flask-login"
] |
Regular expression not working in pywinauto unless I give full text | 39,998,520 | <p>Here is the code snippet that I am using:</p>
<pre><code>browserWin = application.Application()
browserWin.Start(<FirefoxPath>)
# This starts the Firefox browser.
browserWin.Window_(title_re="\.* Firefox \.*")
</code></pre>
<p>If I use the expression: ".* Mozilla Firefox Start Page .*", it works. However, i... | 0 | 2016-10-12T12:22:14Z | 39,998,728 | <p>See this excerpt from the pywinauto source code:</p>
<pre><code>title_regex = re.compile(title_re)
def _title_match(w):
t = handleprops.text(w)
if t is not None:
return title_regex.match(t)
return False
</code></pre>
<p>The <code>return title_regex.match(t)</code> line means that the regex is p... | 0 | 2016-10-12T12:32:47Z | [
"python",
"regex",
"pywinauto"
] |
Regular expression not working in pywinauto unless I give full text | 39,998,520 | <p>Here is the code snippet that I am using:</p>
<pre><code>browserWin = application.Application()
browserWin.Start(<FirefoxPath>)
# This starts the Firefox browser.
browserWin.Window_(title_re="\.* Firefox \.*")
</code></pre>
<p>If I use the expression: ".* Mozilla Firefox Start Page .*", it works. However, i... | 0 | 2016-10-12T12:22:14Z | 40,001,284 | <p>Escaped <code>.</code> with "\" means real dot symbol should be at the start of the text. Just remove "\".</p>
| 2 | 2016-10-12T14:30:46Z | [
"python",
"regex",
"pywinauto"
] |
How to save all items to memcached without losing them? | 39,998,614 | <pre><code>In [11]: from django.core.cache import cache
In [12]: keys = []
In [13]: for i in range(1, 10000):
...: key = "Key%s" % i
...: value = ("Value%s" % i)*5000
...: cache.set(key, value, None)
...: keys.append(key)
...: # check lost keys
...: lost = 0
...: ... | 0 | 2016-10-12T12:26:29Z | 39,998,762 | <p>You can achieve it by increasing Memcached cache size. </p>
| 0 | 2016-10-12T12:34:52Z | [
"python",
"django",
"memcached"
] |
Response mess up when curl Django url | 39,998,758 | <pre><code>@csrf_exempt
def add_node(request, uid=None):
resp = {
'status': 0
}
return JsonResponse(resp)
</code></pre>
<p>Then I use <code>curl</code> to test it, which messed my terminal. But it works fine in browser.</p>
<p><img src="https://i.stack.imgur.com/ifQEM.png" alt="screenshot">
<img s... | 0 | 2016-10-12T12:34:38Z | 40,011,999 | <p>Turns out it is because of my proxy configuration. Whenever <code>$http_proxy</code> variable is set, things go wrong.</p>
| 0 | 2016-10-13T03:50:06Z | [
"python",
"django",
"curl"
] |
regex - HTML tags with parameters | 39,998,776 | <pre><code>import re
text = "sometext <table var1=1 var2=2 var3=3> sometext"
tokenize = re.compile(r'(<\w+) ((\w+=\w+ )*) (\w+=\w+>)')
tokens = tokenize.search(text)
</code></pre>
<p>What I'm attempting to do here, in an exercise to better understand how to use regular expressions in Python, is write one t... | 2 | 2016-10-12T12:35:38Z | 39,999,157 | <p>I think some easier regex and a split is better for this case.</p>
<pre><code>import re
text = "sometext <table var1=1 var2=2 var3=3> sometext"
print(re.findall("<(.+)>", text)[0].split())
</code></pre>
<p>Returns <code>['table', 'var1=1', 'var2=2', 'var3=3']</code></p>
| 0 | 2016-10-12T12:55:17Z | [
"python",
"regex"
] |
Quickly build large dict in elegant manner | 39,998,790 | <p>I have a list with size about 30000: <code>['aa', 'bb', 'cc', 'dd', ...]</code>, from this list, I want to build a dict which maps element to index, so the result dict is <code>{'aa': 0, 'bb': 1, 'cc': 2, 'dd': 3, ...}</code>. Here comes my code:</p>
<pre><code>cnt = 0
mp = {}
for name in name_list:
mp[name] = ... | 0 | 2016-10-12T12:36:30Z | 39,998,824 | <p>You can use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> to create the mapping between list object and the indices, then call <code>dict</code> on the reversed outputs:</p>
<pre><code>mp = dict(tup[::-1] for tup in enumerate(name_list))
</code></pre>... | 3 | 2016-10-12T12:38:31Z | [
"python"
] |
Quickly build large dict in elegant manner | 39,998,790 | <p>I have a list with size about 30000: <code>['aa', 'bb', 'cc', 'dd', ...]</code>, from this list, I want to build a dict which maps element to index, so the result dict is <code>{'aa': 0, 'bb': 1, 'cc': 2, 'dd': 3, ...}</code>. Here comes my code:</p>
<pre><code>cnt = 0
mp = {}
for name in name_list:
mp[name] = ... | 0 | 2016-10-12T12:36:30Z | 39,998,835 | <p>The shortest is to use <a href="https://docs.python.org/2/library/functions.html#enumerate"><code>enumerate</code></a> and a dict comprehension, I guess:</p>
<pre><code>mp = {element: index for index, element in enumerate(name_list)}
</code></pre>
| 5 | 2016-10-12T12:38:54Z | [
"python"
] |
Quickly build large dict in elegant manner | 39,998,790 | <p>I have a list with size about 30000: <code>['aa', 'bb', 'cc', 'dd', ...]</code>, from this list, I want to build a dict which maps element to index, so the result dict is <code>{'aa': 0, 'bb': 1, 'cc': 2, 'dd': 3, ...}</code>. Here comes my code:</p>
<pre><code>cnt = 0
mp = {}
for name in name_list:
mp[name] = ... | 0 | 2016-10-12T12:36:30Z | 39,999,537 | <p>How about using the list index for each item? </p>
<pre><code>mp = {item: name_list.index(item) for item in name_list}
</code></pre>
| 1 | 2016-10-12T13:13:59Z | [
"python"
] |
pandas table subsets giving invalid type comparison error | 39,998,850 | <p>I am using pandas and want to select subsets of data and apply it to other columns.
e.g.</p>
<ul>
<li>if there is data in column A; & </li>
<li>if there is NO data in column B;</li>
<li>then, apply the data in column A to column D</li>
</ul>
<p>I have this working fine for now using <code>.isnull()</code> and ... | 1 | 2016-10-12T12:39:55Z | 39,998,901 | <p>I think you need add parentheses <code>()</code> to conditions, also better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting column with boolean mask which can be assigned to variable <code>mask</code>:</p>
<pre><code>ma... | 1 | 2016-10-12T12:42:31Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
Read regexes from file and avoid or undo escaping | 39,998,980 | <p>I want to read regular expressions from a file, where each line contains a regex:</p>
<pre><code>lorem.*
dolor\S*
</code></pre>
<p>The following code is supposed to read each and append it to a list of regex strings:</p>
<pre><code>vocabulary=[]
with open(path, "r") as vocabularyFile:
for term in vocabularyFi... | -2 | 2016-10-12T12:47:06Z | 39,999,099 | <p>You are getting confused by <em>echoing the value</em>. The Python interpreter echoes values by printing the <code>repr()</code> function result, and this makes sure to escape any meta characters:</p>
<pre><code>>>> regex = r"dolor\S*"
>>> regex
'dolor\\S*'
</code></pre>
<p><code>regex</code> is ... | 1 | 2016-10-12T12:53:09Z | [
"python",
"regex",
"python-3.x",
"escaping"
] |
Django abstract models - how to implement specific access in abstract view method? | 39,999,112 | <p>Let's say I have an abstract model in Django, with two models extending off that.</p>
<p>Inside a Django Rest Framework generic view, how can I control creation of one of the two implementing models?</p>
<p>My solution is below:</p>
<pre><code> from enum import Enum
from rest_framework.views import APIView... | 0 | 2016-10-12T12:53:33Z | 39,999,424 | <p>You can create a mapping/dictionary that maps a model class to the values of each <code>Enum</code> member, and use it in your <code>_internal_method</code> for fetching the model class given the <code>Enum</code> name:</p>
<pre><code>class AbstractView(APIView):
models_map = {1: ConcreteModelOne, 2: Concre... | 0 | 2016-10-12T13:08:15Z | [
"python",
"django"
] |
Referencing relation's relations in Django Serializer | 39,999,173 | <p>Let's say I have some models:</p>
<pre><code>class A(models.Model):
...
class B(models.Model):
my_reference_to_a = models.ForeignKey(A)
b_field_1 = ...
b_field_2 = ...
class C(models.Model):
my_reference_to_b = models.ForeignKey(B)
c_field_1 = ...
...
</code></pre>
<p>In my serializer... | 0 | 2016-10-12T12:55:43Z | 40,027,539 | <p>I figured it out. Just answering my own question in case anyone lands on this page and they need help.</p>
<p>You need to use the SerializerMethodResourceRelatedField from the Django Rest Framework JSON API. I had tried the regular ResourceRelatedField without it working, looking through the source code showed me t... | 0 | 2016-10-13T17:36:56Z | [
"python",
"django",
"ember.js",
"django-rest-framework",
"json-api"
] |
Surface plot with multiple polynomial fits | 39,999,239 | <p>what I'm asking may not be possible, but I'm hoping you guys can help me out.</p>
<p>So I have two 2D arrays, f1(x1) = y1, and f2(x2) = y2. I want to make a surface plot of the ratio of these, so the z dimension is (f2(x2)/f1(x1)). Unfortunately I'm coming up against a wall from whatever direction I approach the pr... | 0 | 2016-10-12T12:58:48Z | 40,008,961 | <p>So I managed to solve my problem. I did some preproccessing on my data as explained above, by setting x1 = x2, and thus extrapolated the edge values for f(x2).</p>
<pre><code>import numpy as np
import scipy.interpolate as interp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data1 = np.loa... | 0 | 2016-10-12T21:50:36Z | [
"python",
"matplotlib",
"curve-fitting",
"surface"
] |
Haystack with Whoosh not returning any results | 39,999,363 | <p>I've installed Django-Haystack and Whoosh and set it all up following the haystack documentation, but no matter what I search for I always get "No results found." on the search page, despite the index apparently being OK.</p>
<p>When running "manage.py rebuild_index" it correctly states:</p>
<pre><code>Indexing 12... | 0 | 2016-10-12T13:05:01Z | 40,018,850 | <p>For the benefit of any future people having this same problem, I found an unconventional solution...</p>
<p>So I double checked everything according to the haystack documentation and it all looked OK. I found out about a pip package called "django-haystackbrowser" that, once installed correctly, allows you to view... | 0 | 2016-10-13T10:46:45Z | [
"python",
"django",
"python-3.x",
"django-haystack",
"whoosh"
] |
TypeError: 'in <string>' requires string as left operand, not QueryDict | 39,999,567 | <p>While updating the edited blog i am getting this error: in edit_article function
Here is my function,</p>
<pre><code>def edit_article(request, id):
session_start(request)
if Article.exists(id):
article = Article.getByName(id)
else:
article = Article(id)
if request.method == 'POST' an... | 0 | 2016-10-12T13:14:58Z | 39,999,731 | <p>If you want to check if <code>request.POST</code> has the key <code>"content"</code>:</p>
<pre><code>if request.method == 'POST' and "content" in request.POST:
</code></pre>
| 1 | 2016-10-12T13:21:13Z | [
"python",
"python-3.x"
] |
Extracting multiple lists out of a nested dictionary | 39,999,581 | <p>I am new to Python. I want to extract multiple lists out of the nested dictionary. I did follow this link (<a href="http://stackoverflow.com/questions/28131446/get-nested-arrays-out-of-a-dictionary">Get nested arrays out of a dictionary</a>) didn't help me much.</p>
<p>If I have a dictionary, say:</p>
<pre><code>{... | -2 | 2016-10-12T13:15:30Z | 39,999,787 | <p>You can get each 'layer' by accessing <code>dict.keys()</code> or get the layer below by accessing <code>dict.values()</code>. If you want to dive one level deeper you just iterate over <code>parent.values()</code> and get <code>dict.keys()</code> on each element. The last layer finally is just <code>dict.values()</... | 0 | 2016-10-12T13:23:50Z | [
"python",
"list",
"dictionary"
] |
Create 4D upper diagonal array from 3D | 39,999,590 | <p>Let's say that I have a <code>(x, y, z)</code> sized matrix. Now, I wish to create a new matrix of dimension <code>(x, y, i, i)</code>, where the <code>(i, i)</code> matrix is upper diagonal and constructed from the values on the <code>z</code>-dimension. Is there some easy way of doing this in <code>numpy</code> wi... | 1 | 2016-10-12T13:15:37Z | 39,999,997 | <p>Here's an approach using <code>boolean-indexing</code> -</p>
<pre><code>n = 2 # This would depend on a.shape[-1]
out = np.zeros(a.shape[:2] + (n,n,),dtype=a.dtype)
out[:,:,np.arange(n)[:,None] <= np.arange(n)] = a
</code></pre>
<p>Sample run -</p>
<pre><code>In [247]: a
Out[247]:
array([[[0, 1, 3],
[4... | 1 | 2016-10-12T13:32:25Z | [
"python",
"numpy",
"vectorization"
] |
Approximate pattern matching? | 39,999,637 | <p>I am trying to write code for Approximate Pattern Matching which is as below:</p>
<pre><code>def HammingDistance(p, q):
d = 0
for p, q in zip(p, q): # your code here
if p!= q:
d += 1
return d
Pattern = "ATTCTGGA"
Text = "CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAA... | 1 | 2016-10-12T13:17:50Z | 40,000,120 | <p>I'm unsure why you're getting an empty list as one of your outputs - when I run your code above I only get [0] as the print out.</p>
<p>Specifically, your code at present only checks for an exact character substring match, without using the hamming distance definition you also included. </p>
<p>The following shoul... | 1 | 2016-10-12T13:37:28Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.