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 |
|---|---|---|---|---|---|---|---|---|---|
Quick way to Upper every value in xml? | 38,926,000 | <p>I have the following xml:</p>
<pre><code><Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info... | -1 | 2016-08-12T20:28:58Z | 38,926,021 | <p>Here is a way to upper everything, though note that this will include the tags as well:</p>
<pre><code>node = etree.fromstring(etree.tostring(item).upper())
print etree.tostring(node, pretty_print=True)
<ITEM>
<PLATFORM>ITUNES</PLATFORM>
<PLATFORMID>102224185</PLATFORMID>
<IN... | -1 | 2016-08-12T20:30:28Z | [
"python",
"xml",
"lxml"
] |
Quick way to Upper every value in xml? | 38,926,000 | <p>I have the following xml:</p>
<pre><code><Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info... | -1 | 2016-08-12T20:28:58Z | 38,926,040 | <p>You can find all elements and call <code>upper()</code> on each element's text:</p>
<pre><code>import lxml.etree as ET
data = """<Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<... | 4 | 2016-08-12T20:31:34Z | [
"python",
"xml",
"lxml"
] |
Quick way to Upper every value in xml? | 38,926,000 | <p>I have the following xml:</p>
<pre><code><Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info... | -1 | 2016-08-12T20:28:58Z | 38,926,050 | <p>Assuming you can parse the XML file you can just rewrite the contents using the <code>.upper()</code> function that is built into python for strings. You can call it like that:
<code>"mystring".upper()</code>. </p>
| -1 | 2016-08-12T20:32:16Z | [
"python",
"xml",
"lxml"
] |
Manipulate specific columns (sample features) conditional on another column's entries (feature value) using pandas/numpy dataframe | 38,926,031 | <p>my <strong>input</strong> dataframe (shortened) looks like this:</p>
<pre><code>>>> import numpy as np
>>> import pandas as pd
>>> df_in = pd.DataFrame([[1, 2, 'a', 3, 4], [6, 7, 'b', 8, 9]],
... columns=(['c1', 'c2', 'col', 'c3', 'c4']))
>>> df_in
c1 c2 ... | 4 | 2016-08-12T20:30:56Z | 38,926,091 | <p>You can condition on both the row and col positions to assign values using <code>loc</code> which supports both logic indexing and dimension name indexing:</p>
<pre><code>df_in.loc[df_in.col == 'b', ['c1', 'c2']] = np.nan
df_in
# c1 c2 col c3 c4
# 0 1.0 2.0 a 3 4
# 1 NaN NaN b 8 9
</code></... | 4 | 2016-08-12T20:35:36Z | [
"python",
"performance",
"python-3.x",
"pandas",
"numpy"
] |
Manipulate specific columns (sample features) conditional on another column's entries (feature value) using pandas/numpy dataframe | 38,926,031 | <p>my <strong>input</strong> dataframe (shortened) looks like this:</p>
<pre><code>>>> import numpy as np
>>> import pandas as pd
>>> df_in = pd.DataFrame([[1, 2, 'a', 3, 4], [6, 7, 'b', 8, 9]],
... columns=(['c1', 'c2', 'col', 'c3', 'c4']))
>>> df_in
c1 c2 ... | 4 | 2016-08-12T20:30:56Z | 39,026,466 | <p>When using <strong>pandas</strong> I would go for the solution provided by @Psidom.</p>
<p>However, for larger datasets it is faster when doing the whole <em>pandas -> numpy -> pandas</em> procedure, i.e. <em>dataframe -> numpy.array -> dataframe</em> (minus 10% process time for my setup). Without converting back t... | 0 | 2016-08-18T19:51:42Z | [
"python",
"performance",
"python-3.x",
"pandas",
"numpy"
] |
Join on date in SQLalchemy considering only date and not time of the day | 38,926,043 | <p>I need to join two tables in SQLalchemy on datetime columns but I do not want to consider full datetimes but only date parts of them (join two rows with similar dates even if the time of the days are not equal).</p>
<p>Here is something I have right now</p>
<pre><code>import sqlalchemy as sq
...
first = meta.table... | 0 | 2016-08-12T20:31:45Z | 38,936,276 | <p>To truncate the timestamps to day precision use the function <a href="https://www.postgresql.org/docs/current/static/functions-datetime.html" rel="nofollow"><code>date_trunc(text, timestamp)</code></a> in PostgreSQL:</p>
<pre><code>select = sq.select([first.c.id,
first.c.date,
... | 1 | 2016-08-13T19:30:54Z | [
"python",
"datetime",
"sqlalchemy"
] |
Join on date in SQLalchemy considering only date and not time of the day | 38,926,043 | <p>I need to join two tables in SQLalchemy on datetime columns but I do not want to consider full datetimes but only date parts of them (join two rows with similar dates even if the time of the days are not equal).</p>
<p>Here is something I have right now</p>
<pre><code>import sqlalchemy as sq
...
first = meta.table... | 0 | 2016-08-12T20:31:45Z | 38,936,373 | <pre><code>from sqlalchemy.sql.functions import func
first = meta.tables("schema.first")
second = meta.tables("schema.second")
select = sq.select([
first.c.id,
first.c.date,
first.c.value,
second.c.value])
.select_from(first.join(second, sq.and_(
first.c.id == second.c.id,
func.DATE(... | 0 | 2016-08-13T19:44:20Z | [
"python",
"datetime",
"sqlalchemy"
] |
Making flexible XPath for Selenium (Python) | 38,926,094 | <p>I am trying to use selenium and python to set the text contents of a web element to a string.</p>
<p>The code:
<code>monthname = browser.find_element_by_xpath("//*[@id='monthRow-7']/td[1]").text</code> works but I want to be able to change <code>monthRow-7</code> to include a different number.</p>
<p>My idea is to... | 0 | 2016-08-12T20:35:50Z | 38,926,262 | <p>I'd use <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">string formatting</a> for this.</p>
<pre><code>monthnum = 7
monthname = browser.find_element_by_xpath("//*[@id='monthRow-{}']/td[1]".format(monthnum)).text
</code></pre>
<p>Here <code>{}</code> will be replaced by t... | 0 | 2016-08-12T20:49:41Z | [
"python",
"xml",
"selenium",
"xpath",
"concatenation"
] |
How to convert date entries in OHLC data frame in Python to strings in order to use date time module to inspect dates | 38,926,193 | <pre><code>In[118]: Date.iloc[0].to_string()
Out[118]: 'Date 1997-09-09'
</code></pre>
<p>How do I eliminate "Date" from string in order to use date time module</p>
| 1 | 2016-08-12T20:43:54Z | 38,926,226 | <p>Try:</p>
<pre><code>Date.iloc[0, 0].strftime('%Y-%m-%d')
</code></pre>
<p>consider <code>tidx</code></p>
<pre><code>tidx = pd.date_range('2000-01-01', periods=2)
</code></pre>
<p>both print the same thing.</p>
<pre><code>print(tidx.strftime('%Y-%m-%d'))
print(tidx.to_series().dt.strftime('%Y-%m-%d').values)
['... | 2 | 2016-08-12T20:46:56Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
How to convert date entries in OHLC data frame in Python to strings in order to use date time module to inspect dates | 38,926,193 | <pre><code>In[118]: Date.iloc[0].to_string()
Out[118]: 'Date 1997-09-09'
</code></pre>
<p>How do I eliminate "Date" from string in order to use date time module</p>
| 1 | 2016-08-12T20:43:54Z | 38,926,231 | <p>Pass <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_string.html" rel="nofollow"><code>index=False</code></a>:</p>
<pre><code>Date.iloc[0].to_string(index=False)
</code></pre>
| 2 | 2016-08-12T20:47:09Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
How to convert date entries in OHLC data frame in Python to strings in order to use date time module to inspect dates | 38,926,193 | <pre><code>In[118]: Date.iloc[0].to_string()
Out[118]: 'Date 1997-09-09'
</code></pre>
<p>How do I eliminate "Date" from string in order to use date time module</p>
| 1 | 2016-08-12T20:43:54Z | 38,926,254 | <pre><code>Date.iloc[0].to_string()[-10:]
Out[129]: '1997-09-09'
</code></pre>
| 1 | 2016-08-12T20:49:06Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
how to concatenate two csv files and keep the original order of columns in python? | 38,926,206 | <p>Actually there are many parts in this question. I have solved some parts by viewing the answer of other stack overflow questions. However, there is still one tiny problem not solved. The output csv file tends to order alphabetically or in other order, which is not what I want.</p>
<p>As an example, I'm going to con... | 1 | 2016-08-12T20:45:15Z | 38,926,358 | <p>You almost have it with a.columns</p>
<pre><code>col_names = a.columns.tolist() # list of column names
sorted_cols = sorted(col_names)
df.to_csv("dfTest.txt","\t",header=True,cols=sorted_cols, engine='python')
</code></pre>
<p>In one line:</p>
<pre><code>df.to_csv("dfTest.txt","\t",
header=True,
... | 0 | 2016-08-12T20:57:45Z | [
"python",
"csv",
"pandas"
] |
how to concatenate two csv files and keep the original order of columns in python? | 38,926,206 | <p>Actually there are many parts in this question. I have solved some parts by viewing the answer of other stack overflow questions. However, there is still one tiny problem not solved. The output csv file tends to order alphabetically or in other order, which is not what I want.</p>
<p>As an example, I'm going to con... | 1 | 2016-08-12T20:45:15Z | 38,926,365 | <p>Build up an output order which you can then supply to <code>c.to_csv(...)</code>, eg:</p>
<pre><code>from collections import OrderedDict
out_order = OrderedDict.fromkeys(a.columns)
out_order.update(OrderedDict.fromkeys(b.columns))
out_order = list(out_order)
# ['B', 'A', 'C', 'E', 'D']
c.to_csv("c.csv", index=Fals... | 1 | 2016-08-12T20:58:11Z | [
"python",
"csv",
"pandas"
] |
Listen to ZeroMQ in aiohttp application process | 38,926,534 | <p>I run <code>aiohttp</code> application with <code>Gunicorn</code> behind <code>nginx</code>.
In my application's initialization module I don't run the application using <code>web.run_app(app)</code> but just create an instance that will be imported by <code>Gunicorn</code> to run it in each worker <code>Gunicorn</co... | 2 | 2016-08-12T21:12:26Z | 39,346,972 | <p>Ok, the question and the discussion on this <a href="https://github.com/KeepSafe/aiohttp/issues/1092" rel="nofollow">issue</a> has led to the new functionality I've contributed to <code>aiohttp</code>, namely in version <strong>1.0</strong> we'll have an ability to register <code>on_startup</code> application signal... | 0 | 2016-09-06T10:38:34Z | [
"python",
"zeromq",
"gunicorn",
"python-asyncio",
"aiohttp"
] |
Python -- list(some_float) fails but [some_float] works? | 38,926,579 | <p>I have a case where a user passes a function a single floating-point value. While trying to put that value into a list for easier data handling later, I've discovered that I cannot make a list using <code>list(some_float)</code>, but <code>[some_float]</code> does work. Python prints an error stating that "'float' o... | 0 | 2016-08-12T21:16:39Z | 38,926,607 | <p><code>list(thing)</code> doesn't mean "put <code>thing</code> in a list". It means "put <code>thing</code>'s <strong>elements</strong> in a list". If you want to put a <code>thing</code> in a list, that's <code>[thing]</code>.</p>
| 6 | 2016-08-12T21:19:14Z | [
"python",
"list"
] |
Python -- list(some_float) fails but [some_float] works? | 38,926,579 | <p>I have a case where a user passes a function a single floating-point value. While trying to put that value into a list for easier data handling later, I've discovered that I cannot make a list using <code>list(some_float)</code>, but <code>[some_float]</code> does work. Python prints an error stating that "'float' o... | 0 | 2016-08-12T21:16:39Z | 38,926,634 | <p>you have to pass iterable item </p>
<pre><code>print list.__doc__
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
</code></pre>
| 1 | 2016-08-12T21:21:34Z | [
"python",
"list"
] |
How to add a Heroku Django app's new model table to the remote Heroku Postgres with Python migrate? | 38,926,626 | <p>After successfully finishing a tutorial on <a href="https://devcenter.heroku.com/articles/getting-started-with-python#provision-a-database" rel="nofollow">a Heroku Python app with a Postgres db</a>, I made a new model on my Heroku app, based on the existing code, by copying and pasting the existing model and its tab... | 0 | 2016-08-12T21:20:56Z | 38,926,627 | <p>I wanted to actually create my new table on my remote Heroku Postgres database, by running <code>heroku run python manage.py migrate</code>, which was used in the tutorial. But it didn't work right off the bat. What I needed to do was to set up a few Python files and then run that command at the end.</p>
<p>This w... | 0 | 2016-08-12T21:20:56Z | [
"python",
"django",
"postgresql",
"heroku"
] |
Using web driver to get all text from a source page in python | 38,926,658 | <p>I am using selenium webdriver (firefox) to crawl some data from a website. I just found that opening the web page is slower than just opening the source of that web page. In other words, it took much longer to go to <code>'www.google.com'</code> than to go to <code>'view-source:www.google.com'</code></p>
<p>So I wa... | 0 | 2016-08-12T21:24:42Z | 38,926,703 | <p>If you only need the source use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>. Install it with pip: </p>
<pre><code>pip install requests
</code></pre>
<p>And use it like so:</p>
<pre><code>import requests
r = requests.get("http://google.com/")
# r.content, r.text, r.json(), r.s... | 1 | 2016-08-12T21:29:21Z | [
"python",
"selenium-webdriver",
"webdriver"
] |
Openpyxl not writing to cells properly | 38,926,683 | <p>Attemping to write a Python script that will open an existing invoice template I have created and prompt for the info to fill in the cells. The file is created with the intended name, the print statement at the end successfully prints the value intended for cell C5, and the script finishes without errors. Upon openi... | 0 | 2016-08-12T21:27:07Z | 39,134,903 | <ol>
<li>What happens if you open the file in Excel and save it (that corrects some openpyxl problems for me, where it has not fully updated an excel 2016 xlsx worksheet).</li>
<li>What does a file compare show between test.xlsx and invoiceN.xlsx?</li>
</ol>
| 0 | 2016-08-25T00:22:51Z | [
"python",
"excel",
"openpyxl"
] |
Open .hdr files with OpenCV | 38,926,689 | <p>I try to read <code>.hdr</code> files like this:</p>
<pre><code>img = cv2.imread(sys.argv[1])
cv2.imshow('Image', img)
</code></pre>
<p>This gives me a 3-channel 8-bit <code>Mat</code> which is either (nearly) completely white or a very dark picture. So I suppose it only gives me one image of the exposure sequence... | 1 | 2016-08-12T21:27:29Z | 39,472,526 | <p>The data you have is the merged stack not individual exposures. To display it correctly, you need to tone-map the data. This is the correct procedure, for example:</p>
<pre><code>Mat hdr = imread("xxx.hdr",-1); // correct element size should be CV_32FC3
Mat ldr;
Ptr<TonemapReinhard> tonemap = createTonemapRei... | 1 | 2016-09-13T14:28:32Z | [
"python",
"opencv",
"hdr"
] |
ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb -- Django 1.4 & Google App Engine | 38,926,708 | <p>This will be the second time in my life posting about almost exactly the same thing. The difference between this time and last time is about 9 months, lots of difficult learning, and the fact that for those past 9 months I have never had this issue and have frequently used MySQLdb flawlessly during the entire time p... | 0 | 2016-08-12T21:29:47Z | 39,003,811 | <p>After digging around for hours I have finally discovered the root issue. The only significant change that has occurred from the time that MySQLdb was working properly and the time that MySQLdb stopped working properly was upon my upgrading OS X to El Capitan.</p>
<p>Running:</p>
<p><code>otool -L /Library/Python/2... | 1 | 2016-08-17T18:23:57Z | [
"python",
"mysql",
"django",
"google-app-engine",
"mysql-python"
] |
Effective Way to Validate Field Values Spark | 38,926,715 | <p>I need to validate certain columns in a data frame before saving data to hdfs. I want to know if there is an elegant and effective way to do this in pyspark 1.5.2 / python 2.7</p>
<p>For example, say I have the following data</p>
<pre><code>+-----+---+
| a| b|
+-----+---+
|"foo"|123|
+-----+---+
</code></pre>
... | 2 | 2016-08-12T21:30:19Z | 38,926,864 | <p>You can use several predefined <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=functions#module-pyspark.sql.functions" rel="nofollow">functions</a> to accomplish your objective.</p>
<pre><code>from pyspark.sql.functions import *
df = sc.parallelize([("fo", 100),("alb", 501),("ro... | 3 | 2016-08-12T21:42:50Z | [
"python",
"hadoop",
"apache-spark",
"bigdata",
"pyspark"
] |
Python(2.7) keeps crashing when launching scapy via console or importing it | 38,926,728 | <p>Regardless of if I do </p>
<pre><code>scapy
</code></pre>
<p>or </p>
<pre><code>Python
from scapy.all import *
</code></pre>
<p>it simply crashes python. It says "Python is not responding" with the classic little bar that does nothing. I'm currently on Win10. </p>
<p>There's only one other person that I found... | 0 | 2016-08-12T21:31:32Z | 38,935,298 | <p>Well, nobody put an answer, but I finally figured it out, so in the oddball chance someone ends up in the same predicament, here's how I got it to work: </p>
<p>Make sure the anniversary update for windows is installed, and enable the beta(or not anymore by the time your read this?) linux bash (a quick googling wil... | 1 | 2016-08-13T17:30:06Z | [
"python",
"wireshark",
"scapy",
"packets"
] |
Parse XML tag's attribute value via ElementTree AND replace the value string | 38,926,854 | <p>I am new to Python and trying to automate a task. I have spent two days reading the docs, looked into various other similar questions, but now, I've hit a wall and can't move forward. </p>
<p>I feel Python docs are not well documented on Elementtree module. Maybe it is just me. Also, I know I can use other modules.... | 0 | 2016-08-12T21:42:11Z | 38,927,097 | <p>Consider using <code>iter()</code> across the elements with a conditional <code>if</code> replace:</p>
<pre><code>import xml.etree.ElementTree as ET
#----------------------------------------------------------------------
def parseXML(xml_file):
"""
Parse XML with ElementTree
"""
tree = ET.ElementT... | 1 | 2016-08-12T22:07:52Z | [
"python",
"xml",
"parsing",
"elementtree"
] |
Implications of flushing stdout after each print | 38,926,917 | <p>I have a script whose output is piped to <code>less</code>, and I would like the script to print it's statements into <code>less</code> as they come, rather than all at once.</p>
<p>I found that if I flush stdout (via <code>sys.stdout.flush()</code>) after each print, the line is displayed in <code>less</code> when... | 1 | 2016-08-12T21:48:18Z | 38,926,942 | <p>Basically, the only drawback is that it's potentially slower. The buffering on stdin allows your program to run ahead of the physical I/O which is slow.</p>
<p>However, if you're sending it to less, you're operating at human speeds anyway -- it's not going to make a difference.</p>
| 0 | 2016-08-12T21:50:45Z | [
"python",
"python-2.7"
] |
How to get parent directory and sub directory for file | 38,926,949 | <p>I'm trying list out the names of directories a particular file belongs to. Below is an example of my file tree: </p>
<pre><code>root_folder
âââ topic_one
â  âââ one-a.txt
â  âââ one-b.txt
âââ topic_two
âââ subfolder_one
â  âââ sub-two-a.txt
âââ tw... | 2 | 2016-08-12T21:51:10Z | 38,929,509 | <p>Thanks to <a href="http://stackoverflow.com/users/6451573/jean-fran%C3%A7ois-fabre">Jean-François Fabre</a> and <a href="http://stackoverflow.com/users/1040495/jjpx">Jjpx</a> for this solution:</p>
<pre><code>for root, dirs, files in os.walk(root_folder):
# removes hidden files and dirs
files = [f for f i... | 0 | 2016-08-13T05:23:57Z | [
"python"
] |
Multiply elementwise array and rectangular matrix | 38,927,004 | <p>I want to multiply elementwise an array of shape (10,) and a matrix of shape (10,20), basically multiply each column by the array.</p>
<p>But I got </p>
<blockquote>
<p><code>ValueError: operands could not be broadcast together with shapes (20,) (20,10)</code> </p>
</blockquote>
<p>It does work when I use a (10... | 0 | 2016-08-12T21:56:03Z | 38,927,317 | <p>If you want to multiply 2 matrix they have to have an order in math and in programs</p>
<pre><code>A => a x n
B => n x b
</code></pre>
<p>and you get <code>C = A x B</code> will be shaped <code>C => a x b</code></p>
<p>so your first array has to be (1,10) to multiply a matrix (10,20) and you will get a... | 0 | 2016-08-12T22:34:54Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Multiply elementwise array and rectangular matrix | 38,927,004 | <p>I want to multiply elementwise an array of shape (10,) and a matrix of shape (10,20), basically multiply each column by the array.</p>
<p>But I got </p>
<blockquote>
<p><code>ValueError: operands could not be broadcast together with shapes (20,) (20,10)</code> </p>
</blockquote>
<p>It does work when I use a (10... | 0 | 2016-08-12T21:56:03Z | 38,927,616 | <p>The first rule of broadcasting is that the arrays with fewest dimensions get expanded - and the expansion occurs at the front of the array.</p>
<p>In the (10,) * (10,20) case, there are 2 dim, so the first expands to (1,10). But that can't be changed to match (10,20).</p>
<p>So you need to explicitly change the (... | 2 | 2016-08-12T23:13:48Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Python Selenium Calling Hidden File Input | 38,927,073 | <p>I am using selenium-python with chromedriver.</p>
<p>In a webpage,which is <a href="https://web.whatsapp.com/" rel="nofollow">https://web.whatsapp.com/</a> ,I am trying to send a file with send_keys() to a file type input.</p>
<p>But the problem is,that input element is only visible in inspector when you drop a fi... | 1 | 2016-08-12T22:05:21Z | 38,928,116 | <p>If you wat to work with file input element then try to make it visible instead of it's parent element as below :</p>
<pre><code>xpath = '//*[@id="app"]/div/div[3]/div[1]/span[2]/span/div/div[2]/input'
file = driver.find_element_by_xpath(xpath)
file = driver.execute_script("arguments[0].style.display='block'; retu... | 0 | 2016-08-13T00:41:04Z | [
"javascript",
"python",
"selenium",
"input",
"hidden"
] |
KeyError: nan in dict | 38,927,099 | <p>I do as below</p>
<pre><code>import numpy as np
from numpy import nan
df = pd.DataFrame({'a':[1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0, nan : nan}
df['a'] = [ mapper[x] for x in df['a'] ]
</code></pre>
<p>and </p>
<pre><code>KeyError: nan
</code></pre>
<p>I tried to change dtypes</p>... | 2 | 2016-08-12T22:08:21Z | 38,927,116 | <p>The problem is that nan is "not a number", and as such it equals no other number, not even another nan. You can read more about it <a href="https://en.wikipedia.org/wiki/NaN">here</a>.</p>
<p>To demonstrate:</p>
<pre><code>from numpy import nan
nan == nan
=> False
</code></pre>
<p>From this it must follow that... | 5 | 2016-08-12T22:10:36Z | [
"python",
"numpy",
"dictionary"
] |
KeyError: nan in dict | 38,927,099 | <p>I do as below</p>
<pre><code>import numpy as np
from numpy import nan
df = pd.DataFrame({'a':[1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0, nan : nan}
df['a'] = [ mapper[x] for x in df['a'] ]
</code></pre>
<p>and </p>
<pre><code>KeyError: nan
</code></pre>
<p>I tried to change dtypes</p>... | 2 | 2016-08-12T22:08:21Z | 38,927,217 | <p>@shx2 explains why this happens. But you can still do what you want — just forget the <code>NaN</code> and use <code>Series.map</code>:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0}
df['a'] = df['a'].map(mapp... | 2 | 2016-08-12T22:21:40Z | [
"python",
"numpy",
"dictionary"
] |
keyboard stops working when typing my PYPI password in the cmd | 38,927,157 | <p>I have logged into the python package index but when I tried to upload my first python file and pressed 1 to type my username and password , the keyboard at the password section stopped working and when I pressed enter the server response is: "you must login to access this feature" ,but i just cant type the passwor... | -1 | 2016-08-12T22:15:11Z | 38,927,222 | <p>type your password and press enter</p>
<p>you won't see any <code>*</code>, that doesn't mean your keyboard stopped working (it's invisible)</p>
| 0 | 2016-08-12T22:22:18Z | [
"python",
"pypi"
] |
How can I specify a class method as a callback target in Python? | 38,927,207 | <p>I'm using the sftp module of paramiko to transfer payloads to remote hosts. Part of the <code>sftp.put</code> call allows for specifying a callback method with signature <code>func(int,int)</code>. I'm trying to put a transfer stats method into my <code>Connection</code> class to keep track of payload progress.</p>
... | 0 | 2016-08-12T22:20:24Z | 38,927,252 | <p>Your problem is in :</p>
<pre><code> log.info(self.sftp.put(payloadPath, '%s/%s' % (targetDir,payloadPath), callback=self.TransferStats()))
</code></pre>
<p>Your error :</p>
<pre><code>ERROR - (, TypeError('TransferStats() takes exactly 3 arguments (1 given)',), )
</code></pre>
<p>Is caused by calling <code>T... | 2 | 2016-08-12T22:25:49Z | [
"python",
"python-2.7",
"callback"
] |
Panda AssertionError columns passed, passed data had 2 columns | 38,927,230 | <p>I am working on Azure ML implementation on text analytics with NLTK, the following execution is throwing </p>
<pre><code>AssertionError: 1 columns passed, passed data had 2 columns\r\nProcess returned with non-zero exit code 1
</code></pre>
<p>Below is the code </p>
<pre><code># The script MUST include the follow... | 1 | 2016-08-12T22:23:17Z | 38,927,256 | <p>Try this:</p>
<pre><code>dataframe_output = pd.DataFrame(tagged, columns=['Output', 'temp'])
</code></pre>
| 1 | 2016-08-12T22:26:09Z | [
"python",
"pandas",
"dataframe",
"nltk",
"azure-ml"
] |
shortcuts in append function in python | 38,927,266 | <p>I am programming newbie here, so sorry for these elementary questions.
I am dealing with python code which has vectors and a lot of append function. For example lines like these</p>
<pre><code>a = [[],[],[]]
a[0].append(1)
a[1].append(2)
a[2].append(5)
</code></pre>
<p>So I was wondering if the above lines could b... | 0 | 2016-08-12T22:28:14Z | 38,927,309 | <p>the most pythonic way I can think of to create and then append to the list of lists. Best for Python 3 where <code>zip</code> is a generator function.</p>
<pre><code>a = [[] for i in range(0,3)]
for i,j in zip(a,[1,2,5]):
i.append(j)
</code></pre>
<p>For python 2, <code>zip</code> will allocate a lot of memory... | 1 | 2016-08-12T22:33:46Z | [
"python",
"numpy",
"append"
] |
Python: Fill space between two lines drawn on a Basemap | 38,927,272 | <p>I have drawn two lines on a Basemap created in python. Each line is created with two points (start and end points). Both lines originate from the same point.</p>
<pre><code>m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
m.plot([x, x1],... | 0 | 2016-08-12T22:29:09Z | 38,938,531 | <p>Here is my solution. Wish it help!</p>
<pre><code>from matplotlib.patches import Polygon
m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
x,y = (119.46 + 121.406)/2.0,(21.62+23.43)/2.0
x1,y1 = 120.0,24.0
x2,y2 = 124.0,22.0
lons = np.ar... | 0 | 2016-08-14T01:58:43Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
Python: Fill space between two lines drawn on a Basemap | 38,927,272 | <p>I have drawn two lines on a Basemap created in python. Each line is created with two points (start and end points). Both lines originate from the same point.</p>
<pre><code>m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
m.plot([x, x1],... | 0 | 2016-08-12T22:29:09Z | 38,964,397 | <p>I solved this by using a wedge patch object and using the azimuths of the radar sweeps.</p>
<pre><code>fig, ax = plt.subplots()
m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
wedge = Wedge((x,y), 200000, az2, az1, edgecolor="none", col... | 0 | 2016-08-15T23:19:07Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
numpy.column_stack with numeric and string arrays | 38,927,294 | <p>I have several arrays, some of them have float numbers and others have string characters, all the arrays have the same length. When I try to use numpy.column_stack in these arrays, this function convert to string the float numbers, for example:</p>
<pre><code>a = np.array([3.4,3.4,6.4])
b = np.array(['holi','xlo','... | 1 | 2016-08-12T22:31:49Z | 38,927,331 | <p>To store such mixed type data, most probably you would be required to store them as Object dtype arrays or use <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow"><code>structured arrays</code></a>. Going with the Object dtype arrays, we could convert either of the input arrays to an Object... | 2 | 2016-08-12T22:37:22Z | [
"python",
"numpy"
] |
numpy.column_stack with numeric and string arrays | 38,927,294 | <p>I have several arrays, some of them have float numbers and others have string characters, all the arrays have the same length. When I try to use numpy.column_stack in these arrays, this function convert to string the float numbers, for example:</p>
<pre><code>a = np.array([3.4,3.4,6.4])
b = np.array(['holi','xlo','... | 1 | 2016-08-12T22:31:49Z | 38,927,737 | <p>The easiest structured array approach is with the <code>rec.fromarrays</code> function:</p>
<pre><code>In [1411]: a=np.array([3.4,3.4,6.4]); b=np.array(['holi','xlo','xlo'])
In [1412]: B = np.rec.fromarrays([a,b],names=['a','b'])
In [1413]: B
Out[1413]:
rec.array([(3.4, 'holi'), (3.4, 'xlo'), (6.4, 'xlo')],
... | 2 | 2016-08-12T23:30:10Z | [
"python",
"numpy"
] |
Python - Capture Individaul value result of request | 38,927,321 | <p>I am new to Python. I am trying to capture individual values that returned from the request result.</p>
<p>Here is part of my code to send the request:</p>
<pre><code>opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pw... | -1 | 2016-08-12T22:35:27Z | 38,927,551 | <p>Have you tried using json loads. load in the background uses the method .read() so if you wanted to use it you must use a file like object like StringIO or file/open</p>
<p>Like this:</p>
<pre><code>import urllib2
import json
import base64
test_load = "foo=bar"
user = "test"
pwd = "test"
opener = urllib2.build_op... | 0 | 2016-08-12T23:05:23Z | [
"python"
] |
Splitting multiple pipe delimited values in multiple columns of a comma delimited CSV and mapping them to each other | 38,927,384 | <p>I have a csv with comma delimiters that has multiple values in a column that are delimited by a pipe and I need to map them to another column with multiple pipe delimited values and then give them their own row along with data in the original row that doesn't have multiple values. My CSV looks like this (with commas... | 1 | 2016-08-12T22:42:45Z | 38,927,650 | <p>Maybe not the nicest but working solution:
(works with no piped lines and for different pipe-length)</p>
<pre><code>df = pd.read_csv('<your_data>.csv')
str_split = ' | '
# Calculate maximum length of piped (' | ') values
df['max_len'] = df[['name', 'city']].apply(lambda x: max(len(x[0].split(str_split)),
... | 1 | 2016-08-12T23:18:03Z | [
"python",
"csv"
] |
Splitting multiple pipe delimited values in multiple columns of a comma delimited CSV and mapping them to each other | 38,927,384 | <p>I have a csv with comma delimiters that has multiple values in a column that are delimited by a pipe and I need to map them to another column with multiple pipe delimited values and then give them their own row along with data in the original row that doesn't have multiple values. My CSV looks like this (with commas... | 1 | 2016-08-12T22:42:45Z | 38,927,717 | <p>Given a row:</p>
<pre><code>['1','frank|joe|dave', 'toronto|new york|anaheim', '20']
</code></pre>
<p>you can use</p>
<pre><code>itertools.izip_longest(*[value.split('|') for value in row])
</code></pre>
<p>on it to obtain following structure:</p>
<pre><code>[('1', 'frank', 'toronto', '20'),
(None, 'joe', 'new... | 1 | 2016-08-12T23:27:24Z | [
"python",
"csv"
] |
How can I perform word tokenization of a text, using the tokenize annotator, with pycorenlp (Python wrapper for Stanford CoreNLP), without ssplit? | 38,927,415 | <p>I am trying to run <a href="https://github.com/smilli/py-corenlp" rel="nofollow">pycorenlp</a>, which is a Python wrapper for <a href="http://stanfordnlp.github.io/CoreNLP/" rel="nofollow">Stanford CoreNLP</a>, to perform word tokenization of a text, using the <a href="http://stanfordnlp.github.io/CoreNLP/tokenize.h... | 0 | 2016-08-12T22:45:49Z | 38,931,392 | <p>You are right, the API doesn't seem to be responding if the only annotator provided is 'tokenize'. It should be have defaulted to <code>PTBTokenizer</code> as mentioned in the docs. Another relevant question is present here: <a href="http://stackoverflow.com/q/21742186/1005215">Stanford CoreNLP gives NullPointerExc... | 1 | 2016-08-13T09:43:17Z | [
"python",
"nlp",
"stanford-nlp",
"tokenize"
] |
Impala/SQL: select a sub-table and join | 38,927,422 | <p>I am trying to use the following code to find the last month data in table_1, then left join it with table_2:</p>
<pre><code>import pandas as pd
query = 'select * from table_1 where table_1.ts > "2016-07-12 00:00:00" as recent_table left join table_2 on table_1.t2__fk=table_2.id'
cursor = impala_con.cursor()
... | 0 | 2016-08-12T22:46:19Z | 38,927,484 | <p>That's cause your query syntax is wrong. You can't use alias for conditional statement as pointed below. Aliases are used only for table name and column name.</p>
<pre><code>where table_1.ts > "2016-07-12 00:00:00" as recent_table
</code></pre>
<p>The correct query would be</p>
<pre><code>select t1.*
from tab... | 1 | 2016-08-12T22:56:02Z | [
"python",
"sql",
"impala"
] |
How to find Spark RDD created in different cores of a computer | 38,927,439 | <p>I just wanted to educate myself more on Spark. So wanted to ask this question. </p>
<p>I have Spark currently installed on my local machine. Its a Mach with 16GB. </p>
<p>I have connected a Jupyter notebook running with Pyspark. </p>
<p>So now when I do any coding in that notebook, like reading the data and conve... | 0 | 2016-08-12T22:48:21Z | 38,929,653 | <p>Jupyter has mainly three parts Jupyter Notebook, Jupyter Clients and Kernels. <a href="http://jupyter.readthedocs.io/en/latest/architecture/how_jupyter_ipython_work.html" rel="nofollow">http://jupyter.readthedocs.io/en/latest/architecture/how_jupyter_ipython_work.html</a></p>
<p><em>Here is short note on Kernel fr... | 0 | 2016-08-13T05:46:39Z | [
"python",
"apache-spark",
"ipython"
] |
Pandas boxplot with ranges in x-axis | 38,927,459 | <p>I have the foll. dataframe in pandas:</p>
<pre><code>value combined_delta
100 7
100 45
100 49
100 12
100 71
94.09 21
91.42 45
88.7 36
87.26 34
77.61 55
76.3 28
73.81 89
71 80
69.5 27
67.45 12
66.96 127
66.18 43
54.48 68
54.15 23
53.29 48
53.29 49
53.25 302
51.99 24
51.99 11... | 2 | 2016-08-12T22:52:28Z | 38,927,562 | <pre><code>cut = pd.cut(df.value, [0, 20, 40, 60, 80, 100])
boxdf = df.groupby(cut) \
.apply(lambda df: df.combined_delta.reset_index(drop=True)) \
.unstack(0)
sns.boxplot(data=boxdf);
</code></pre>
<p><a href="http://i.stack.imgur.com/Ulbxo.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ulbxo.png" a... | 3 | 2016-08-12T23:06:38Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Pandas boxplot with ranges in x-axis | 38,927,459 | <p>I have the foll. dataframe in pandas:</p>
<pre><code>value combined_delta
100 7
100 45
100 49
100 12
100 71
94.09 21
91.42 45
88.7 36
87.26 34
77.61 55
76.3 28
73.81 89
71 80
69.5 27
67.45 12
66.96 127
66.18 43
54.48 68
54.15 23
53.29 48
53.29 49
53.25 302
51.99 24
51.99 11... | 2 | 2016-08-12T22:52:28Z | 38,927,580 | <p>Use <code>pd.cut</code> to create the groups you want and plot <code>combined_delta</code> against those.</p>
<pre><code>df['value_group'] = pd.cut(df['value'], bins=range(0, 101, 20))
ax = sns.boxplot(x="value_group", y="combined_delta", data=df)
</code></pre>
<p><a href="http://i.stack.imgur.com/0UIfM.png" rel="... | 3 | 2016-08-12T23:09:19Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
AttributeError: 'Ui_Login' object has no attribute 'GetTable' | 38,927,480 | <p>Im creating a login and signup page that links to other GUI using PyQt. Most of the code works but when i try to sign up a new user, it gives me a <strong>AttributeError: 'Ui_Login' object has no attribute 'GetTable'</strong>. GetTable is defined in the code for the databse created with MySQl whic is called into the... | 1 | 2016-08-12T22:55:06Z | 38,927,673 | <p>Your code expects this line:</p>
<pre><code>db.DatabaseUtility('UsernamePassword_DB', 'masterTable')
</code></pre>
<p>to return an object with a <code>GetTable</code> method (and assign that object to <code>self.dbu</code>). Therefore when you call <code>self.dbu.GetTable()</code> you get an error if whatever was ... | 0 | 2016-08-12T23:21:09Z | [
"python",
"pyqt"
] |
AttributeError: 'Ui_Login' object has no attribute 'GetTable' | 38,927,480 | <p>Im creating a login and signup page that links to other GUI using PyQt. Most of the code works but when i try to sign up a new user, it gives me a <strong>AttributeError: 'Ui_Login' object has no attribute 'GetTable'</strong>. GetTable is defined in the code for the databse created with MySQl whic is called into the... | 1 | 2016-08-12T22:55:06Z | 38,927,704 | <p>The issue seems to be in your initialization of the <code>Ui_Form</code>. In this snippet</p>
<pre><code>@QtCore.pyqtSignature("on_signUpButton_clicked()")
def signUp_Button(self):
self.newuser = Ui_Form(self)
self.newuser.show()
</code></pre>
<p>it looks like you are passing <code>self</code>, in this cas... | 0 | 2016-08-12T23:25:58Z | [
"python",
"pyqt"
] |
Polaroid Effect with Images in Python | 38,927,526 | <p>I'm trying to take an image and add the following effect from imagemagick <a href="http://www.imagemagick.org/Usage/transform/#polaroid" rel="nofollow">http://www.imagemagick.org/Usage/transform/#polaroid</a>. I've searched for Python code examples and have been unsuccessful. I don't need to use imagemagick(wand, py... | 1 | 2016-08-12T23:01:06Z | 38,955,798 | <p>With <a href="/questions/tagged/wand" class="post-tag" title="show questions tagged 'wand'" rel="tag">wand</a>, you will need to implement the C-API methods <code>MagickPolaroidImage</code> & <code>MagickSetImageBorderColor</code></p>
<pre class="lang-py prettyprint-override"><code>import ctypes
from... | 0 | 2016-08-15T13:15:06Z | [
"python",
"imagemagick",
"python-imaging-library",
"imagemagick-convert",
"pythonmagick"
] |
Convert pandas cut operation to a regular string | 38,927,585 | <p>I get the foll. output from a pandas cut operation:</p>
<pre><code>0 (0, 20]
1 (0, 20]
2 (0, 20]
3 (0, 20]
4 (0, 20]
5 (0, 20]
6 (0, 20]
7 (0, 20]
8 (0, 20]
9 (0, 20]
</code></pre>
<p>How can I convert the (0, 20] to 0 - 20?</p>
<p>I am doing t... | 2 | 2016-08-12T23:10:22Z | 38,927,619 | <p>assuming the output was assigned to a variable <code>cut</code></p>
<pre><code>cut.astype(str)
</code></pre>
<p>To remove bracketing</p>
<pre><code>cut.astype(str).str.strip('()[]')
</code></pre>
| 2 | 2016-08-12T23:14:02Z | [
"python",
"pandas"
] |
Convert pandas cut operation to a regular string | 38,927,585 | <p>I get the foll. output from a pandas cut operation:</p>
<pre><code>0 (0, 20]
1 (0, 20]
2 (0, 20]
3 (0, 20]
4 (0, 20]
5 (0, 20]
6 (0, 20]
7 (0, 20]
8 (0, 20]
9 (0, 20]
</code></pre>
<p>How can I convert the (0, 20] to 0 - 20?</p>
<p>I am doing t... | 2 | 2016-08-12T23:10:22Z | 38,927,645 | <p>Use the <code>labels</code> parameter of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>pd.cut</code></a>:</p>
<pre><code>pd.cut(df['some_col'], bins=[0,20,40,60], labels=['0-20', '20-40', '40-60'])
</code></pre>
<p>I don't know what your exact <code>pd.cut</c... | 4 | 2016-08-12T23:16:59Z | [
"python",
"pandas"
] |
How do I make a force-directed graph in python? | 38,927,682 | <p>I want a graph that shows a few nodes, directional arrows between nodes representing a relationship, with thickness relative to the strength of their connection.</p>
<p>In R this is very simple</p>
<pre><code>library("qgraph")
test_edges <- data.frame(
from = c('a', 'a', 'a', 'b', 'b'),
to = c('a', 'b', '... | 1 | 2016-08-12T23:23:38Z | 38,930,780 | <p>I first tried doing this with NetworkX's standard drawing functions, which use matplotlib, but I was not very successful.</p>
<p>However, NetworkX also <a href="https://networkx.github.io/documentation/development/reference/drawing.html#module-networkx.drawing.nx_agraph" rel="nofollow">supports drawing to the <code... | 2 | 2016-08-13T08:25:01Z | [
"python",
"data-visualization",
"igraph",
"networkx",
"r-qgraph"
] |
How can I identify the correct td tag using bs4 in python when HTML code is inconsistent | 38,927,775 | <p>I'm using BeautifulSoup4 in Python to parse some HTML code. I've managed to drill down to the correct table and identify the td tags, but the problem I'm facing is that the style attribute in the tags is inconsistently applied and it is making the task of getting the correct td tag a real challenge.</p>
<p>The data... | 1 | 2016-08-12T23:37:05Z | 38,933,177 | <p>Filter the tds using a list comp, keeping only if the td does not have a style attribute in the set <code>{"display:none", "display: none;","display: none;","display: none"}</code>:</p>
<pre><code>In [8]: h1 = """"<td style="display: none;">01/03/2016</td>
...: <td style="display: table-cell;">... | 1 | 2016-08-13T13:23:43Z | [
"python",
"html",
"beautifulsoup",
"bs4"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp... | 4 | 2016-08-12T23:39:36Z | 38,927,878 | <p>In a list, the code <code>if tmp not in num:</code> is O(n)<strike>, while it is O(lgn) in dict</strike>.</p>
<p><strong>Edit</strong>: The dict is based on hashing, so it is much quicker than liner list search.
Thanks @user2357112 for point this.</p>
| 0 | 2016-08-12T23:54:52Z | [
"python",
"performance",
"list",
"dictionary"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp... | 4 | 2016-08-12T23:39:36Z | 38,927,933 | <p>I am almost positive that the "magic sauce" using a dictionary lies in the fact that the dictionary is comprised of key->value pairs.</p>
<p>in a list, youre dealing with arrays, which means the for loop has to start at index 0 inside of your list in order to loop through every record.</p>
<p>the dictionary just h... | 0 | 2016-08-13T00:04:37Z | [
"python",
"performance",
"list",
"dictionary"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp... | 4 | 2016-08-12T23:39:36Z | 38,927,968 | <p>In Python, the average time complexity of a dictionary key lookup is O(1), since they are implemented as hash tables. The time complexity of lookup in a list is O(n) on average. In your code, this makes a difference in the line <code>if tmp not in num:</code>, since in the list case, Python needs to search through t... | 4 | 2016-08-13T00:10:35Z | [
"python",
"performance",
"list",
"dictionary"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp... | 4 | 2016-08-12T23:39:36Z | 38,929,814 | <p>If it's about speed, you should not create any lists:</p>
<pre><code>n = 100000
factors = ((frozenset(factors(i)), i) for i in range(2, n+1))
num = {k:v for k,v in factors if len(k)==2}
suma = sum(num.values())
</code></pre>
| 1 | 2016-08-13T06:14:26Z | [
"python",
"performance",
"list",
"dictionary"
] |
Parsing a Pandas dataframe with an unknown number of columns for use in statsmodels.api | 38,927,844 | <p>I would like to create a generic script to perform linear regressions on multiple data sets. Each data set will have the same y-variable called "SM" and an unknown number of x-variables. I have been able to do this successfully if I know exactly which data will be used for the regression. For example:</p>
<pre><cod... | 1 | 2016-08-12T23:47:36Z | 38,927,871 | <p>See if this works:</p>
<pre><code>df = pd.DataFrame(np.arange(20).reshape(2, 10), columns=list('abcdefghij'))
formula = '{} ~ {}'.format(df.columns[0], ' + '.join(df.columns[1:]))
formula
'a ~ b + c + d + e + f + g + h + i + j'
</code></pre>
| 0 | 2016-08-12T23:53:31Z | [
"python",
"pandas",
"linear-regression",
"statsmodels",
"patsy"
] |
How to call the function from user input? | 38,927,857 | <p>I'm trying to call <code>Floyd_Warshall(G)</code> from <code>user_command</code> however I get this <code>error</code>:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 24, in <module>
Floyd_Warshall()
NameError: name 'Floyd_Warshall' is not defined
</code></pre>
<p>How to call it to ge... | 0 | 2016-08-12T23:50:51Z | 38,929,416 | <p>function should be defined before calling it. So place the function before while loop</p>
<pre><code>import sys
import re
# also this function needs one input mandatorily
def Floyd_Warshall(G):
............
............
print("File containing graph: ")
while True:
user_input = input()
if user_input == "... | 0 | 2016-08-13T05:08:40Z | [
"python",
"function",
"python-3.x",
"input"
] |
How to call the function from user input? | 38,927,857 | <p>I'm trying to call <code>Floyd_Warshall(G)</code> from <code>user_command</code> however I get this <code>error</code>:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 24, in <module>
Floyd_Warshall()
NameError: name 'Floyd_Warshall' is not defined
</code></pre>
<p>How to call it to ge... | 0 | 2016-08-12T23:50:51Z | 38,929,535 | <p>Its would not run anyway: </p>
<pre><code>Floyd_Warshall()
</code></pre>
<p>and </p>
<pre><code>def Floyd_Warshall(G):
</code></pre>
<p>are not compatible. The function needs a variable input, which is missing when you call it with <code>Floyd_Warshall()</code></p>
| 0 | 2016-08-13T05:29:33Z | [
"python",
"function",
"python-3.x",
"input"
] |
python pandas reindexing removes data at 0.0 | 38,927,875 | <p>I have three columns of data: two position values and one data value. I would like to pivot this data so that the elements of one column become the new columns and the elements of another one of the original columns become the indices. These data will be plotted using <code>pcolormesh</code>. <code>pcolormesh</code>... | 2 | 2016-08-12T23:54:06Z | 38,930,393 | <p>I am not sure about the real reason. However, I changed your <code>min_max</code> function to:</p>
<pre><code>def min_max(column):
column_min = np.floor(column.min())
column_max = np.ceil(column.max()) + 1
return column_min, column_max
</code></pre>
<p>And then it worked:</p>
<p><a href="http://i.stac... | 2 | 2016-08-13T07:34:49Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Have 2 flask pages that share a database, need to merge their models | 38,927,891 | <p>Need some guidance with this please. I have two pages or apps made with flask(+sqlalchemy) - one that acts as the front page and the other one that works as some kind of admin or extranet for the first one.</p>
<p>The apps use their own views and models but they share the same database and this is starting to mess ... | 0 | 2016-08-12T23:56:25Z | 38,929,064 | <p>It is unclear what problem you are trying to solve. SQLAlchemy has a <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/api.html" rel="nofollow">declarative API</a> that allows you to sub-class some base (in Flask-SQLAlchemy, conventionally, <code>db.Model</code>); it then automatically builds ... | 0 | 2016-08-13T04:04:55Z | [
"python",
"flask",
"flask-sqlalchemy"
] |
Pygame move a object to mouse | 38,927,892 | <p>I wanted to move a sprite (bullet) slowly to the coordinates of the mouse by calculating the x and y of the image with: </p>
<pre><code>angle = math.atan2(dX,dY) * 180/math.pi
x = speed * sin(angle)
y = speed * cos(angle)
</code></pre>
<p>The problem is that even though a sprite points to the mouse (in this game, ... | 0 | 2016-08-12T23:56:31Z | 38,954,726 | <h2>There are three things wrong with your calculations.</h2>
<ol>
<li><code>math.atan2</code> takes the arguments in the order y and x, not x and y. This isn't a huge deal since you can compensate for it.</li>
<li><code>math.cos</code> and <code>math.sin</code> takes <strong>radians</strong> as arguments. You have co... | 0 | 2016-08-15T12:02:34Z | [
"python",
"pygame",
"mouse"
] |
request.headers.get('Authorization') is empty in Flask production | 38,927,945 | <p>I have the following flask method that simple returns back the value of the Authorization header:</p>
<pre><code>@app.route('/test', methods=['POST'])
def test():
return jsonify({"data" : request.headers.get('Authorization') })
</code></pre>
<p>When I submit the following curl request to my API which has been d... | 0 | 2016-08-13T00:06:29Z | 38,928,853 | <p>Have you tried using a proper <code>Authorization</code> header? Possibly the header is being filtered out by a web application firewall or proxy because it doesn't specify a scheme. For example:</p>
<pre>
curl --data '' -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" api.mysite.com/test
</pre>
<p>This sends a ... | 1 | 2016-08-13T03:17:11Z | [
"python",
"http",
"flask",
"authorization"
] |
Python subprocess call throws errors when using find | 38,927,956 | <p>I am making a script in <code>python3</code> using <code>call</code> from the <code>subprocess</code> library. The problem that I am having is that this command <code>find . -mtime +3 | xargs rm -rf</code> will work perfectly fine when put into the terminal but when I do this:</p>
<pre class="lang-py prettyprint-ov... | -1 | 2016-08-13T00:07:33Z | 38,928,082 | <p><code>|</code> isn't a command argument; it is shell syntax for joining two commands together.</p>
<p>The simplest way to use a pipe is to pass a single string to <code>subprocess</code> and let a shell parse it:</p>
<pre><code>from subprocess import call
call("find . -mtime +3 | xargs rm -rf", shell=True)
</code>... | 3 | 2016-08-13T00:33:30Z | [
"python",
"bash",
"python-3.x",
"find",
"subprocess"
] |
Default export in Python 3 | 38,927,979 | <p>In a project I'm working on, I'm separating a lot of bigger files into smaller pieces so they're easier to work with. One specific example is creating class based views from function based views in Django:</p>
<pre><code># app/views/LoginView.py
class LoginView(View):
...
# urls.py
from app.views import LoginVie... | 3 | 2016-08-13T00:12:16Z | 38,928,273 | <p>You can import <code>LoginView</code> as a name under <code>app.views</code> using the <code>__init__.py</code> of <code>app.views</code>.</p>
<p>In <code>app/views/__init__.py</code>:</p>
<pre><code>from LoginView import LoginView
</code></pre>
<p>In <code>urls.py</code></p>
<pre><code>import app.views
urlpat... | 4 | 2016-08-13T01:12:21Z | [
"python",
"django",
"python-3.5"
] |
Django with Crispy-forms VariableDoesNotExist | 38,927,992 | <p>I have been trying to load a form into a modal for about a week now and I just can't figure out what it is I'm doing wrong. It is a simple form for someone to send an email to me, and I started out trying to modularize the form and am now just trying to load it direcly into base.html.</p>
<p>My model:</p>
<pre><co... | 0 | 2016-08-13T00:13:38Z | 38,929,385 | <p>The problem is that you are trying to use your <code>form</code> in your <code>base.html</code> (for all views). But the form is only added to the context in your <code>emailme</code> view. The home page view (<code>home</code>) does not provide any <code>form</code>, hence the error when you try to load the home pa... | 0 | 2016-08-13T05:01:19Z | [
"python",
"django",
"twitter-bootstrap",
"django-models",
"django-crispy-forms"
] |
Avoid creating app with flask-cli | 38,927,996 | <p>I'm using a custom manage.py script for my flask app, which is created with a factory pattern.</p>
<p>This script needs to both be able to run the server and run my tests. I use an external tool to run my tests, so I do not need to create an app to run the tests. How can I only create the app when running certain c... | 0 | 2016-08-13T00:14:27Z | 39,786,386 | <p>you need to add:</p>
<pre><code>cli.add_command(test)
</code></pre>
<p>before:</p>
<pre><code>if __name__ == '__main__':
cli()
</code></pre>
<p>And I am not sure if it is the only left thing you need to do. I am also study this and feel confused. But if you want to add a command in the FlaskGroup, you must d... | 0 | 2016-09-30T07:52:50Z | [
"python",
"flask",
"python-click"
] |
Asking user to input a file from their computer | 38,928,015 | <p>New python 2.7 user. I just started learning about dictionaries and asking the user for input so I can make a little code to practice manipulating dictionaries such as simple math computations. </p>
<p>I am able to ask a user to input something manually such as :</p>
<pre><code> fav_numbs = (raw_input("What is you... | 0 | 2016-08-13T00:19:24Z | 38,928,480 | <p>Assuming this is run on the command line, you'll want to use <code>argparse</code> to get the file path from the user, instead of <code>raw_input</code>. But either way, you shouldn't worry about where the user is importing the file from. Files specified by relative and absolute path are practically handled the same... | 0 | 2016-08-13T01:59:43Z | [
"python",
"python-2.7",
"dictionary"
] |
Asking user to input a file from their computer | 38,928,015 | <p>New python 2.7 user. I just started learning about dictionaries and asking the user for input so I can make a little code to practice manipulating dictionaries such as simple math computations. </p>
<p>I am able to ask a user to input something manually such as :</p>
<pre><code> fav_numbs = (raw_input("What is you... | 0 | 2016-08-13T00:19:24Z | 38,929,253 | <p>To have an input argument, use sys python library. Add to a file </p>
<pre><code>import sys
import os
if __name__ == "__main__":
test_dir_name = os.getcwd() # Current directory
test_file_name = sys.argv[1] # Get the first input argument
path = open(os.path.join(test_dir_name, test_file_name))
</code></... | 0 | 2016-08-13T04:40:40Z | [
"python",
"python-2.7",
"dictionary"
] |
Identify whether or not a number is prime | 38,928,040 | <p>The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong? </p>
<pre><code>quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME... | -3 | 2016-08-13T00:25:25Z | 38,928,073 | <p>The logic is incorrect </p>
<p>A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.</p>
<p>Simple python code below</p>
<pre><code>def is_prime(n):
for i in... | 0 | 2016-08-13T00:32:06Z | [
"python"
] |
Identify whether or not a number is prime | 38,928,040 | <p>The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong? </p>
<pre><code>quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME... | -3 | 2016-08-13T00:25:25Z | 38,928,075 | <p>The above code is checking if a number is even or odd. If you enter a prime number, for example 17, the code checks if 17 is less than or equal to 0. Then it checks <em>17%2</em> which evalutes to 1, and is not 0. Hence the else block is executed which prints <strong>IS NOT PRIME</strong>.</p>
<p>If you enter an ev... | 0 | 2016-08-13T00:32:25Z | [
"python"
] |
Identify whether or not a number is prime | 38,928,040 | <p>The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong? </p>
<pre><code>quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME... | -3 | 2016-08-13T00:25:25Z | 38,932,460 | <p>I assume you're a beginner with python so let me point out the logic to check primality of numbers in your code is not correct, you should read first carefully the definition of <a href="https://en.wikipedia.org/wiki/Prime_number" rel="nofollow">primes numbers</a>, when you do so, try to understand this little examp... | 0 | 2016-08-13T11:55:58Z | [
"python"
] |
Adding a column to existing csv file as an array (Python) | 38,928,112 | <p>Have a csv file called 'data.csv' in the following format:</p>
<pre><code>test1,test2,test3
1,2,3
4,5,6
7,8,9
</code></pre>
<p>Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:</p>
<pre><code>test1,test2,tes... | 1 | 2016-08-13T00:40:46Z | 38,928,203 | <p>read lines in</p>
<pre><code>with open('data.csv', 'r') as fi:
lines = [[i.strip() for i in line.strip().split(',')] \
for line in fi.readlines()]
col = ['test4', 4, 7, 10]
</code></pre>
<p>Concatenate each row with corresponding element of <code>col</code>. Using enumerate to help keep track of... | 0 | 2016-08-13T01:00:34Z | [
"python",
"list",
"csv"
] |
Adding a column to existing csv file as an array (Python) | 38,928,112 | <p>Have a csv file called 'data.csv' in the following format:</p>
<pre><code>test1,test2,test3
1,2,3
4,5,6
7,8,9
</code></pre>
<p>Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:</p>
<pre><code>test1,test2,tes... | 1 | 2016-08-13T00:40:46Z | 38,928,315 | <p>I would just treat the csv like the raw text it is. Load in each line, strip off the line break, append the new entry, then put the line break back. <strong>This only works if the entries in test4 are guaranteed to be in the same order as the rows in data.csv.</strong> </p>
<p>If instead test4 needs to be added ... | 1 | 2016-08-13T01:22:09Z | [
"python",
"list",
"csv"
] |
Adding a column to existing csv file as an array (Python) | 38,928,112 | <p>Have a csv file called 'data.csv' in the following format:</p>
<pre><code>test1,test2,test3
1,2,3
4,5,6
7,8,9
</code></pre>
<p>Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:</p>
<pre><code>test1,test2,tes... | 1 | 2016-08-13T00:40:46Z | 38,928,332 | <p>Since you're working with csv files use the <code>csv</code> <code>readers</code> and <code>writers</code> to improve readability:</p>
<pre><code>import csv
new_data = ['test4', 4, 7, 10]
with open(r'data.csv', 'r') as in_csv, open(r'adj_data.csv', 'w') as out_csv:
reader = csv.reader(in_csv)
writer = csv... | 0 | 2016-08-13T01:24:23Z | [
"python",
"list",
"csv"
] |
mongodb: how to check if a value is associated to a specific key | 38,928,131 | <p>I'm trying to write a python program that checks if a value is mapped to a specific key in a mongodb document. Is there anyway to do this?</p>
<pre><code>if { key_1 : value_1 } in db_i/collection_j/document_k:
do this
elif { key_1 : value_2 } in db_i/collection_j/document_k:
do something else
</code></pre>
| 0 | 2016-08-13T00:45:01Z | 38,981,834 | <p>Figured out the answer, thanks to the comments above:</p>
<pre><code>if db.collection.find_one({"Pod":"24"},{"Available":False}) is None:
perform update that "$sets" {"Available":False}
else:
do nothing because {Available:False} already exists
print "Pod 24 is already unavailable"
</code></pre>
<p>This... | 0 | 2016-08-16T18:16:05Z | [
"python",
"mongodb"
] |
Patching a parent class | 38,928,243 | <p>I'm having trouble getting a parent class mocked with <code>mock.patch</code>.</p>
<p>Here's a test case:</p>
<p>In <code>parent.py</code>:</p>
<pre><code>import mock
class Parent():
def __init__(self):
print("Original recipe")
</code></pre>
<p>In <code>child.py</code>:</p>
<pre><code>from parent i... | 1 | 2016-08-13T01:06:35Z | 38,928,265 | <p>You are not patching the <code>Parent</code> class, you are patching the <code>child</code> module, changing its <code>Parent</code> attribute to a mock. This does not change <code>Child</code> at all, because it still uses the old <code>Parent</code> class as base class.</p>
<p>In Python 3, you can instead patch <... | 2 | 2016-08-13T01:11:15Z | [
"python",
"python-3.x",
"mocking"
] |
Convert multiple types of dates | 38,928,292 | <p>I'm working with data that comes from different places and need to convert dates into the same format. Below are few examples of what I have:</p>
<pre><code>Thu Dec 03 07:27:23 GMT 2015
3-Dec-15
2015-12-04T06:58:54Z
23-Sep-2015 07:03:37 UTC
</code></pre>
<p>The desired output format should be the same for all date... | 3 | 2016-08-13T01:17:21Z | 38,928,309 | <p>Yes, the <a href="https://pypi.python.org/pypi/python-dateutil/1.5" rel="nofollow">dateutil</a> library provides date format detection with the <a href="http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2" rel="nofollow"><code>parse</code></a> function :</p>
<pre><code>from dateutil.parse... | 3 | 2016-08-13T01:20:39Z | [
"python",
"date",
"datetime",
"format"
] |
Error of running an executable file from Python subprosess | 38,928,330 | <p>I am trying to run an executable file (a linear programming solver CLP.exe) from Python 3.5. </p>
<pre><code> Import subprocess
exeFile = " C:\\MyPath\\CLP.exe"
arg1 = "C:\\Temp\\LpModel.mps"
arg2 = "-max"
arg3 = " -dualSimplex"
arg4 = " -printi all"
arg5 = "-solution t solutionFile.txt"
subprocess.check_ou... | 1 | 2016-08-13T01:24:12Z | 38,928,366 | <p>Every space separated token needs to be another argument in the array for <code>subprocess.check_output</code></p>
<pre><code>exeFile = " C:\\MyPath\\CLP.exe"
subprocess.check_output([
exeFile,
"C:\\Temp\\LpModel.mps",
"-max",
"-dualSimplex",
"-printi",
"all",
"-solution",
"t",
"... | 1 | 2016-08-13T01:31:53Z | [
"python",
"eclipse",
"python-3.x",
"pydev",
"clp"
] |
Python os.walk skip directories with specific name instead of path | 38,928,423 | <p>So I have a file system that I want to be able to check and update using python. my solution was os.walk but it becomes problematic with my needs and my file system. This is how the directories are laid out:</p>
<pre><code>Root
dir1
subdir
1
2
3...
file1
file2
dir2
subdir
... | 0 | 2016-08-13T01:45:10Z | 38,928,455 | <p><code>os.walk</code> allows you to modify the list of directories it gives you. If you take some out, it won't descend into those directories.</p>
<pre><code>for dirpath, dirnames, filenames in os.walk("/root/path"):
if "subdir" in dirnames:
dirnames.remove("subdir")
# process the files here
</code>... | 5 | 2016-08-13T01:51:42Z | [
"python",
"os.walk"
] |
regular expression match issue in Python 2.7 | 38,928,601 | <p>Using Python 2.7, want to use regular expression to find the <code>Hello</code> part of a given string. The rule is, <code>Hello</code> maybe in the pattern starts with <code>{(1N)</code>, <code>{(2N)</code> (until <code>10N</code>), or combination of them <code>{(1N,2N,3N,4N)</code>, and ends with <code>}</code>.</... | 1 | 2016-08-13T02:23:04Z | 38,928,651 | <p>Regular expressions cannot really count (which is why you say you tried to write 10 times the same pattern), but instead you can match the sequence and then split to count :</p>
<pre><code>In [100]: match = re.compile(r"\{\s?\(\s?((\d+N,?)+)\)\s?(.*)\s?\}").search("Some content { (1N,2N,3N,4N) Hello } Some content... | 2 | 2016-08-13T02:36:25Z | [
"python",
"regex",
"python-2.7"
] |
regular expression match issue in Python 2.7 | 38,928,601 | <p>Using Python 2.7, want to use regular expression to find the <code>Hello</code> part of a given string. The rule is, <code>Hello</code> maybe in the pattern starts with <code>{(1N)</code>, <code>{(2N)</code> (until <code>10N</code>), or combination of them <code>{(1N,2N,3N,4N)</code>, and ends with <code>}</code>.</... | 1 | 2016-08-13T02:23:04Z | 38,928,744 | <pre><code>In [82]: string = "Some content {(1N,2N,3N,4N) Hello } Some content"
In [83]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string)
In [84]: nums = re.findall(r"10N|[1-9]N", result[0][0])
In [85]: nums
Out[85]: ['1N', '2N', '3N', '4N']
In [86]: matchString = result[0][1]
In [87]: matchStrin... | 1 | 2016-08-13T02:53:32Z | [
"python",
"regex",
"python-2.7"
] |
Vectorizing a function that finds the nearest value in an array | 38,928,617 | <p>I've written the following function:</p>
<pre><code>import numpy as np
def _find_nearest(array, value):
"""Find the index in array whose element is nearest to value.
Parameters
----------
array : np.array
The array.
value : number
The value.
Returns
-------
integer
... | 1 | 2016-08-13T02:27:36Z | 38,928,648 | <p>Inside the parent function, where both the <code>value</code> and the <code>array</code> are visible, you can use a <code>lambda</code> to enable the vectorization. I shall call the parent function <code>main</code></p>
<pre><code>def main():
value = np.random.rand(10, 1)
array = np.random.rand(100, 100)
... | 1 | 2016-08-13T02:35:14Z | [
"python",
"numpy",
"vectorization"
] |
iterating a stock tick data with append on python | 38,928,632 | <p>I am trying to combine a series of stock tick data based on the dates.
But it wont work. Please help.</p>
<pre><code>import pandas as pd
import tushare as ts
def get_all_tick(stockID):
dates=pd.date_range('2016-01-01',periods=5,freq='D')
append_data=[]
for i in dates:
stock_tick=pd.DataFram... | -1 | 2016-08-13T02:31:16Z | 38,929,454 | <p>Eyeballing your code, the most obvious missing thing is a <code>return</code> statement:</p>
<pre><code>def get_all_tick(stockID):
dates=pd.date_range('2016-01-01',periods=5,freq='D')
append_data=[]
for i in dates:
# ...
return append_data
</code></pre>
<p>Whatever is in the return stat... | 0 | 2016-08-13T05:14:06Z | [
"python",
"loops",
"append",
"concat",
"stock"
] |
iterating a stock tick data with append on python | 38,928,632 | <p>I am trying to combine a series of stock tick data based on the dates.
But it wont work. Please help.</p>
<pre><code>import pandas as pd
import tushare as ts
def get_all_tick(stockID):
dates=pd.date_range('2016-01-01',periods=5,freq='D')
append_data=[]
for i in dates:
stock_tick=pd.DataFram... | -1 | 2016-08-13T02:31:16Z | 38,967,196 | <p>I figure it out myself. </p>
<pre><code>def get_all_tick(stockID):
.........
df = pd.DataFrame()
for i in get_date:
stock_tick = ts.get_tick_data(stockID, date=i)
stock_tick['Date']=i
stock_tick.sort('volume', inplace=True, ascending=False)
stock_tick = stock_tick[:10]
stock_tick.sort('time', i... | 1 | 2016-08-16T05:27:31Z | [
"python",
"loops",
"append",
"concat",
"stock"
] |
Python 3.5: Print Canvas Text | 38,928,665 | <p>Could anyone share with me how to print the text of the text widget added to a Canvas object? In the code below, I want the system return the value of "hello" when mouse on the text, however, it turns out giving me "1". Don't know why. Could anyone help me?</p>
<p>Many many thanks!!!</p>
<pre><code>import tkinter
... | -1 | 2016-08-13T02:38:38Z | 38,929,698 | <p>According to the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_text.html" rel="nofollow">canvas docs</a>:</p>
<blockquote>
<p>You can display one or more lines of text on a canvas C by creating a
text object:</p>
<pre><code>id = C.create_text(x, y, option, ...)
</code></pre>
<p>This re... | 1 | 2016-08-13T05:52:23Z | [
"python",
"tkinter",
"tkinter-canvas"
] |
How to understand ndarray.reshape function? | 38,928,669 | <p>The prototype of <code>reshape()</code> is that <code>reshape(shape, order="C")</code>, and the type of shape is tuple.
So we should call this function with <code>myarray.reshape((1000, 1, 32, 32))</code>, But I find that many use <code>myarray.reshape(1000, 1, 32, 32)</code>, why?</p>
| 2 | 2016-08-13T02:39:07Z | 38,928,861 | <p>It's a bit of hidden flexibility built into the <code>reshape</code> method.</p>
<p>The keyword here needs to be explicit: you <em>can't</em> do for example:</p>
<pre><code>myarray.reshape(1000, 1, 32, 32, "C")
</code></pre>
<p>You'll get a <code>TypeError</code>, saying that an integer is required.</p>
<p>(In f... | 3 | 2016-08-13T03:19:12Z | [
"python",
"numpy"
] |
Python test class stuck on 'Instantiating tests' | 38,928,748 | <p>My test class produces the required plot, but I have to manually stop execution every time - the console continues to show 'Instantiating tests'; can anyone spot why the execution never halts? Any tips on increasing my code's 'Pythonic-ness' would also be appreciated!</p>
<p>(Python 3.5 running in PyCharm CE 2016.2... | 0 | 2016-08-13T02:53:49Z | 38,929,105 | <p>You need to close the window where the plot is shown in order for the script (your test in this case) to continue/complete/finish. <a href="http://matplotlib.org/faq/howto_faq.html#use-show" rel="nofollow">From the docs</a>, emphasis mine:</p>
<blockquote>
<p>When you want to view your plots on your display, the ... | 1 | 2016-08-13T04:10:56Z | [
"python",
"matplotlib"
] |
What does this mean in regular expressions? re.match(r"(^[cf-qs-z]+)", any file name)? | 38,928,755 | <p>I stumbled upon this code and I do not know what does it match:</p>
<pre><code>re.match(r"(^[cf-qs-z]+)", words)
</code></pre>
| -1 | 2016-08-13T02:55:23Z | 38,928,776 | <ul>
<li>The <code>f-q</code> and <code>s-z</code> are <em>character ranges</em>, meaning any letter from <code>f</code> to <code>q</code> and from <code>s</code> to <code>z</code> in the alphabet, case sensitive</li>
<li><code>c</code> is a <em>literal character</em> <code>c</code> - no special meaning</li>
<li><code>... | 3 | 2016-08-13T02:59:34Z | [
"python",
"regex",
"python-2.7",
"pattern-matching",
"match"
] |
Different results in numpy vs matlab | 38,928,832 | <p>I'm trying to implement a gradient descent algorithm that was previously written in matlab in python with numpy, but I'm getting a set of similar but different results.</p>
<p>Here's the matlab code</p>
<pre><code>function [theta] = gradientDescentMulti(X, y, theta, alpha, num_iters)
m = length(y);
num_features =... | 0 | 2016-08-13T03:13:13Z | 38,928,929 | <p>This line in your Python:</p>
<pre><code> temp_theta = theta
</code></pre>
<p>doesn't do what you think it does. It doesn't make a copy of <code>theta</code> and "assign" it to the "variable" <code>temp_theta</code> -- it just says "<code>temp_theta</code> is now a new name for the object currently named by <c... | 7 | 2016-08-13T03:34:02Z | [
"python",
"matlab",
"numpy"
] |
getting input in a function and calling it in another function | 38,928,900 | <p>how would this work? Lets say I have a function called getInput that gets three numbers based on user input </p>
<pre><code>def getInput():
num1 = int(input("please enter a int"))
num2 = int(input("please enter a int"))
num3 = int(input("please enter a int"))
</code></pre>
<p>how would I use this funct... | 1 | 2016-08-13T03:28:26Z | 38,928,922 | <p>You need to <code>return</code> the variables (<code>num1</code>, <code>num2</code>, <code>num3</code>) from the <code>getInput</code> function.</p>
<p>Like this:</p>
<pre><code>def getInput():
num1 = int(input("please enter a int"))
num2 = int(input("please enter a int"))
num3 = int(input("please enter a... | 2 | 2016-08-13T03:32:07Z | [
"python",
"function",
"input"
] |
getting input in a function and calling it in another function | 38,928,900 | <p>how would this work? Lets say I have a function called getInput that gets three numbers based on user input </p>
<pre><code>def getInput():
num1 = int(input("please enter a int"))
num2 = int(input("please enter a int"))
num3 = int(input("please enter a int"))
</code></pre>
<p>how would I use this funct... | 1 | 2016-08-13T03:28:26Z | 38,929,010 | <p>Use an array for scalability. You may one day need to return 1000 values. Get the three numbers, place them in an array and return them as follows:</p>
<pre><code>num_list = [];
i = 3;
temp = 0;
while i > 0:
temp = int(input("please enter a int"));
num_list.append(temp);
temp=0;
i--;
return n... | 1 | 2016-08-13T03:52:37Z | [
"python",
"function",
"input"
] |
Heroku Scheduler vs Heroku Temporize Scheduler, what's the difference? | 38,928,911 | <p>I'm wondering what is the difference between the <a href="https://elements.heroku.com/addons/scheduler" rel="nofollow">Heroku Scheduler</a> add-on and the <a href="https://elements.heroku.com/addons/temporize" rel="nofollow">Heroku Temporize Scheduler</a> add-on. They both seem to be free and do scheduled jobs.</p>... | 2 | 2016-08-13T03:30:31Z | 38,942,364 | <p>Temporize is a 3rd party service. You'd have to read what the limitations of their free plan is. It looks like the free plan only lets you run a task 20 times per day which is a far cry from your needs of a 1-minute interval.</p>
<p>Heroku's Scheduler is offered by Heroku. It spins up a server for each task and bil... | 1 | 2016-08-14T12:42:23Z | [
"python",
"postgresql",
"heroku",
"cron",
"scheduled-tasks"
] |
Build Python as UCS-4 via pyenv | 38,928,942 | <p>I run into this issue <a href="http://stackoverflow.com/q/17443166/1391441">ImportError numpy/core/multiarray.so: undefined symbol: PyUnicodeUCS2_AsASCIIString</a> installing Python in a <a href="https://github.com/yyuu/pyenv-virtualenv" rel="nofollow">pyenv-virtualenv</a> environment.</p>
<p>In my case, it happens... | 0 | 2016-08-13T03:37:24Z | 38,930,764 | <p>Installing <code>python</code> with <code>pyenv</code> with <code>ucs2</code>:</p>
<pre><code>$ export PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2
$ pyenv install -v 2.7.11
...
$ pyenv local 2.7.11
$ pyenv versions
system
* 2.7.11 (set by /home/nwani/.python-version)
$ /home/nwani/.pyenv/shims/python
Python 2.7... | 1 | 2016-08-13T08:23:01Z | [
"python",
"ucs2",
"pyenv",
"ucs",
"ucs-4"
] |
Installing scikits.samplerate fails | 38,928,949 | <p>I'd like to use "scikits.samplerate", but installation fails.
I'm using Windows10 (64 Bits) for Python 3.51 with Anaconda.</p>
<p>Firstly, I followed this instruction:
<a href="https://scikits.appspot.com/samplerate" rel="nofollow">https://scikits.appspot.com/samplerate</a></p>
<pre><code>>pip install scikits.s... | 0 | 2016-08-13T03:38:43Z | 38,929,336 | <p>I am not sure if this would work, but glad if it does. Have you tried to edit the site.cfg file and try the installation again.This is what line 20 error in your question says as well.</p>
<p>The user here has done it on Ubuntu, maybe a similar approach works for Windows as well.</p>
<p><a href="http://msnoise.org... | 0 | 2016-08-13T04:53:49Z | [
"python",
"install",
"anaconda",
"scikits"
] |
Python and sqlite3 data structure to store table name and columns for multiple reuse | 38,929,005 | <p>I'm using python sqlite3 api to create a database.
In all examples I saw on the documentation table names and colum names are hardcoded inside queries..but this could be a potential problem if I re-use the same table multiple times (ie, creating table, inserting records into table, reading data from table, alter tab... | 0 | 2016-08-13T03:51:31Z | 38,929,114 | <p>If you are going to start using classes to provide an abstraction layer for your database tables, you might as well start using an ORM. Some examples are <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> and <a href="https://www.google.com.au/url?sa=t&rct=j&q=&esrc=s&source=web&c... | 0 | 2016-08-13T04:13:14Z | [
"python",
"sqlite3"
] |
Python and sqlite3 data structure to store table name and columns for multiple reuse | 38,929,005 | <p>I'm using python sqlite3 api to create a database.
In all examples I saw on the documentation table names and colum names are hardcoded inside queries..but this could be a potential problem if I re-use the same table multiple times (ie, creating table, inserting records into table, reading data from table, alter tab... | 0 | 2016-08-13T03:51:31Z | 38,929,115 | <p>I don't know what's proper but I can tell you that it's not conventional.</p>
<p>If you really want to structure tables as classes, you could consider an object relational mapper like <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>. Otherwise, the way you're going about it, how do you know how ma... | 0 | 2016-08-13T04:13:30Z | [
"python",
"sqlite3"
] |
Python and sqlite3 data structure to store table name and columns for multiple reuse | 38,929,005 | <p>I'm using python sqlite3 api to create a database.
In all examples I saw on the documentation table names and colum names are hardcoded inside queries..but this could be a potential problem if I re-use the same table multiple times (ie, creating table, inserting records into table, reading data from table, alter tab... | 0 | 2016-08-13T03:51:31Z | 38,929,352 | <p>I personally don't like to use libraries and frameworks without proper reason. So, if I'd such reason, so will write a thinking wrapper around <code>sqlite</code>.</p>
<pre><code>class Column(object):
def __init__(self, col_name="FOO", col_type="INTEGER"):
# standard initialization
</code></pre>
<p>And... | 0 | 2016-08-13T04:57:04Z | [
"python",
"sqlite3"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.