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 |
|---|---|---|---|---|---|---|---|---|---|
Convert string of list to list | 38,022,075 | <p>I have the list of strings: </p>
<pre><code>['[12 9 15]','[98 12 18]','[56 45 45]']
</code></pre>
<p>and I want to convert it to </p>
<pre><code>[[12,9,15],[98,12,18],[56,45,45]]
</code></pre>
| 3 | 2016-06-24T21:01:46Z | 38,022,200 | <p>As long as the strings are fairly regular, this should work:</p>
<pre><code>>>> x = ['[12 9 15]','[98 12 18]','[56 45 45]']
>>> x = [[int(i) for i in string.strip('[]').split()] for string in x]
>>> x
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
</code></pre>
| 2 | 2016-06-24T21:13:06Z | [
"python",
"string",
"list",
"python-2.7"
] |
Convert string of list to list | 38,022,075 | <p>I have the list of strings: </p>
<pre><code>['[12 9 15]','[98 12 18]','[56 45 45]']
</code></pre>
<p>and I want to convert it to </p>
<pre><code>[[12,9,15],[98,12,18],[56,45,45]]
</code></pre>
| 3 | 2016-06-24T21:01:46Z | 38,022,300 | <p>Use a regular expression</p>
<pre><code>[map(int, re.findall('\d+', item)) for item in x]
</code></pre>
<p>In case it is not always well-formated. </p>
<hr>
<pre><code>>>> import re
>>> [map(int, re.findall('\d+', item)) for item in x]
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
</code></pre>
| 1 | 2016-06-24T21:21:33Z | [
"python",
"string",
"list",
"python-2.7"
] |
Convert string of list to list | 38,022,075 | <p>I have the list of strings: </p>
<pre><code>['[12 9 15]','[98 12 18]','[56 45 45]']
</code></pre>
<p>and I want to convert it to </p>
<pre><code>[[12,9,15],[98,12,18],[56,45,45]]
</code></pre>
| 3 | 2016-06-24T21:01:46Z | 38,025,891 | <p>The simpler the solution, the better it is for others to understand.</p>
<p>Well here is my solution:</p>
<pre><code>list_of_strings = ['[12 9 15]','[98 12 18]','[56 45 45]']
list_of_lists = [map(int, x[1:-1].split()) for x in list_of_strings]
</code></pre>
<p>So I using list-comprehension here. The 'map' func... | 0 | 2016-06-25T06:57:27Z | [
"python",
"string",
"list",
"python-2.7"
] |
Convert string of list to list | 38,022,075 | <p>I have the list of strings: </p>
<pre><code>['[12 9 15]','[98 12 18]','[56 45 45]']
</code></pre>
<p>and I want to convert it to </p>
<pre><code>[[12,9,15],[98,12,18],[56,45,45]]
</code></pre>
| 3 | 2016-06-24T21:01:46Z | 38,030,583 | <p>Please check if this is helpful.</p>
<pre><code>>>> x = ['[12 9 15]','[98 12 18]','[56 45 45]']
>>> print eval(str([ item.replace(" ",",") for item in x ]).replace("'", ''))
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
</code></pre>
| 0 | 2016-06-25T16:33:04Z | [
"python",
"string",
"list",
"python-2.7"
] |
group rows if atleast one word overlaps with other in a dataframe column | 38,022,220 | <p>I have a data frame as below </p>
<pre><code> words group_id
0 set([a, c, b, d]) 1
1 set([a, b]) 2
2 set([h, e, g, f]) 3
</code></pre>
<p>I need to group the rows into one even if one word in the set(words) overlaps with a word in set of other row and update the group_id.</p>
<pre><code> ... | 0 | 2016-06-24T21:14:20Z | 38,029,469 | <p>This works but it's pretty inefficient since its producing a set of unique groupings then searching through this set of unique groupings once for each entry in the dataframe. Would be neat to see more efficient ways of doing this.</p>
<pre><code>def unique_grouper(series_of_entry_sets):
set_of_groups = [series_... | 1 | 2016-06-25T14:22:23Z | [
"python",
"pandas",
"dataframe"
] |
group rows if atleast one word overlaps with other in a dataframe column | 38,022,220 | <p>I have a data frame as below </p>
<pre><code> words group_id
0 set([a, c, b, d]) 1
1 set([a, b]) 2
2 set([h, e, g, f]) 3
</code></pre>
<p>I need to group the rows into one even if one word in the set(words) overlaps with a word in set of other row and update the group_id.</p>
<pre><code> ... | 0 | 2016-06-24T21:14:20Z | 38,032,044 | <p>This is a pretty inefficient and hacked-together solution, but works nonetheless:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"Names":[set(["a", "c", "b", "d"]),set(["a", "b"]),set(["h", "e", "g", "f"]),set(["z"])]})
groups={}
idx=0
data=[]
for row in df.itertuples():
values = row.Names
groups[i... | 0 | 2016-06-25T19:09:29Z | [
"python",
"pandas",
"dataframe"
] |
Finding Merge (Outer - Inner) Pandas DF differences | 38,022,230 | <p>Want to find the difference between two outer-merge and inner-merge DataFrames, without finding any row with <code>NaN</code> -- I want to keep some rows with them. Is there a way to do this using the <code>difference</code> method or preferably without having to create both <code>FrameA</code> and <code>FrameB</cod... | 3 | 2016-06-24T21:15:33Z | 38,022,527 | <p>You are looking for the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.symmetric_difference.html" rel="nofollow"><code>symmetric_difference</code></a>:</p>
<pre><code>a = DataA.set_index('a')
b = DataB.set_index('a')
# select rows from the outer join using the symmetric difference (^)
... | 4 | 2016-06-24T21:44:15Z | [
"python",
"pandas",
"dataframe",
"merge",
"difference"
] |
Python: Simulating CSV.DictReader with OpenPyXL | 38,022,247 | <p>I have an Excel (.xlsx) file that I'm trying to parse, row by row. I have a header (first row) that has a bunch of column titles like School, First Name, Last Name, Email, etc.</p>
<p>When I loop through each row, I want to be able to say something like:</p>
<pre><code>row['School']
</code></pre>
<p>and get back... | 0 | 2016-06-24T21:17:09Z | 38,028,439 | <p>Excel sheets are far more flexible than CSV files so it makes little sense to have something like DictReader.</p>
<p>Just create an auxiliary dictionary from the relevant column titles.</p>
<p>If you have columns like <code>"School", "First Name", "Last Name", "EMail"</code> you can create the dictionary like this... | 1 | 2016-06-25T12:16:34Z | [
"python",
"excel",
"openpyxl"
] |
How to set dependencies between DAGs in Airflow? | 38,022,323 | <p>I am using <a href="https://github.com/apache/incubator-airflow" rel="nofollow">Airflow</a> to schedule batch jobs. I have one DAG (A) that runs every night and another DAG (B) that runs once per month. B depends on A having completed successfully. However B takes a long time to run and so I would like to keep it in... | 1 | 2016-06-24T21:23:28Z | 38,028,511 | <p>You can achieve this behavior using an operator called ExternalTaskSensor.
Your task (B1) in DAG(B) will be scheduled and wait for a success on task (A2) in DAG(A)</p>
<p><a href="https://pythonhosted.org/airflow/code.html#airflow.operators.ExternalTaskSensor" rel="nofollow">External Task Sensor documentation</a>... | 1 | 2016-06-25T12:25:16Z | [
"python",
"etl",
"airflow"
] |
How to resize the plotted frame in Matplotlib | 38,022,409 | <pre><code>import matplotlib.pyplot as plt
plt.figure()
plt.xlabel('x')
plt.ylabel('y')
plt.plot([0,1],[1,0])
plt.show()
</code></pre>
<p>I would like to be able to resize just the plot itself, NOT the entire window, without having to physically resize it. For example, I would like to have the x axis be only 0.75 time... | 1 | 2016-06-24T21:32:10Z | 38,022,642 | <p>If I understand your question correctly, what you are looking for is the GridSpec function in the matplotlib module.</p>
<p>you can use :</p>
<pre><code>import matplotlib.pyplot as plt
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha=... | 0 | 2016-06-24T21:55:16Z | [
"python",
"matplotlib",
"plot"
] |
Django- limit_choices_to using 2 different tables | 38,022,480 | <p>I fear that what I am trying to do might be impossible but here we go:</p>
<p>Among my models, I have the following</p>
<pre><code>Class ParentCategory(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
Class Category(models.Model):
parentCategory ... | 1 | 2016-06-24T21:39:15Z | 38,022,728 | <p>Maybe this will work:</p>
<pre><code>limit_choices_to={'parentCategory__name': 'comp method'}
</code></pre>
| 1 | 2016-06-24T22:03:06Z | [
"python",
"django",
"django-models"
] |
Why is my CSV larger than my JSON file with identical data? | 38,022,511 | <p>I used pandas to export a large dataset (510,000 rows) to CSV and JSON for comparison. Both files contain the same dataset.</p>
<pre><code>-rw-r--r-- 1 ****** staff 187584246 Jun 24 16:23 case_06-24-16_16-14.csv
-rw-r--r-- 1 ****** staff 14026640 Jun 24 16:24 case_06-24-16_16-14.csv.zip
-rw-r--r-- 1 ****... | 1 | 2016-06-24T21:42:41Z | 38,022,997 | <p>Would be more easy if you showed some csv and json rows. My guess is that the characters used to separate the values are different in the two files and that's why you see a difference in file size.</p>
<p>The only thing is about this answer is that I would then expect the json to be bigger. </p>
<pre><code>A;B;C
1... | 1 | 2016-06-24T22:31:47Z | [
"python",
"json",
"csv",
"pandas",
"bigdata"
] |
Why is my CSV larger than my JSON file with identical data? | 38,022,511 | <p>I used pandas to export a large dataset (510,000 rows) to CSV and JSON for comparison. Both files contain the same dataset.</p>
<pre><code>-rw-r--r-- 1 ****** staff 187584246 Jun 24 16:23 case_06-24-16_16-14.csv
-rw-r--r-- 1 ****** staff 14026640 Jun 24 16:24 case_06-24-16_16-14.csv.zip
-rw-r--r-- 1 ****... | 1 | 2016-06-24T21:42:41Z | 38,023,035 | <p><strong>Json</strong> it's a human readable file. It's not optimized.</p>
<p>In few words <strong>Json</strong> file will use <strong>more characters</strong> and elements to represent the same data as in <strong>csv</strong>. </p>
<p><strong>Csv</strong> idea is optimized to move data. </p>
| 0 | 2016-06-24T22:37:08Z | [
"python",
"json",
"csv",
"pandas",
"bigdata"
] |
Custom logger error? | 38,022,534 | <p>I'm trying to learn how to create a custom logger. I'm not exactly sure what the below <strong>error</strong> is telling me, so if anyone could lead me in the right direction that would be great.</p>
<p>When I import and run the logger from my launcher.py file...</p>
<pre><code>import custom_logging as logging
lo... | 0 | 2016-06-24T21:45:00Z | 38,022,613 | <p>According to <a href="http://stackoverflow.com/questions/345991/python-no-handlers-could-be-found-for-logger-opengl-error">Python - No handlers could be found for logger "OpenGL.error"</a>, to debug your code you need to have:</p>
<pre><code>import custom_logging as logging
logging.basicConfig()
</code></... | 1 | 2016-06-24T21:52:17Z | [
"python",
"logging"
] |
Custom logger error? | 38,022,534 | <p>I'm trying to learn how to create a custom logger. I'm not exactly sure what the below <strong>error</strong> is telling me, so if anyone could lead me in the right direction that would be great.</p>
<p>When I import and run the logger from my launcher.py file...</p>
<pre><code>import custom_logging as logging
lo... | 0 | 2016-06-24T21:45:00Z | 38,031,037 | <p>Finally found the problem. @martineau suggested showing the code, so I started editing it to be more presentable. During that process I found the error!</p>
<p>To answer my initial question, the <code>mb</code> in the error message refers to the root_logger. </p>
<p>When I was overriding the getLogger method in... | 1 | 2016-06-25T17:21:17Z | [
"python",
"logging"
] |
Django - No apps.py when running startapp | 38,022,555 | <p>Django version: Django-1.9.7
I am following this tutorial: </p>
<p><a href="https://docs.djangoproject.com/en/1.9/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/1.9/intro/tutorial01/</a></p>
<p>I get to this step:</p>
<pre><code>python manage.py startapp polls
</code></pre>
<p>once I run it ... | 0 | 2016-06-24T21:47:08Z | 38,022,943 | <p>You are probably running the wrong version of Django.</p>
<p>Use <code>python manage.py --version</code> to check which version of Django is installed.</p>
<p>(If you use more then one version of Python (Python 2 + Python 3) or if you are using virtualenvs, you might have more than one version of Django installed ... | 1 | 2016-06-24T22:25:54Z | [
"python",
"django"
] |
Unclosed character class using punctuation in Spark | 38,022,570 | <p>I'm trying to build a regex pattern that'll remove punctuations from a string. I've decided to use <code>punctuation</code> from the <code>string</code> library. However, when I execute it, Spark returns an error that theres an unenclosed character.</p>
<p>I suspect the characters within <code>punctuation</code> cl... | 0 | 2016-06-24T21:48:21Z | 38,022,757 | <p>Plain and simple:</p>
<pre><code>regexp_replace(column, "\p{Punct}", "")
</code></pre>
<p>To use <code>string.punctuation</code> you'd have to escape individual characters and put them in a character set but it is error prone and ugly:</p>
<pre><code>import re
regexp_replace(column, "[{0}]".format(re.escape(stri... | 3 | 2016-06-24T22:05:06Z | [
"python",
"apache-spark",
"pyspark"
] |
Unclosed character class using punctuation in Spark | 38,022,570 | <p>I'm trying to build a regex pattern that'll remove punctuations from a string. I've decided to use <code>punctuation</code> from the <code>string</code> library. However, when I execute it, Spark returns an error that theres an unenclosed character.</p>
<p>I suspect the characters within <code>punctuation</code> cl... | 0 | 2016-06-24T21:48:21Z | 38,337,665 | <pre><code>column = regexp_replace(column, '[^\w\s]', '')
column = regexp_replace(column, '_', '')
</code></pre>
<p>Note that underscores are treated as legitimate alphanumeric characters, so need special removal.</p>
| 2 | 2016-07-12T19:45:47Z | [
"python",
"apache-spark",
"pyspark"
] |
Unclosed character class using punctuation in Spark | 38,022,570 | <p>I'm trying to build a regex pattern that'll remove punctuations from a string. I've decided to use <code>punctuation</code> from the <code>string</code> library. However, when I execute it, Spark returns an error that theres an unenclosed character.</p>
<p>I suspect the characters within <code>punctuation</code> cl... | 0 | 2016-06-24T21:48:21Z | 38,571,726 | <p>you might just include things you want: digits, letters and spaces</p>
<pre><code>return lower(trim(regexp_replace(regexp_replace(column, '[^\w\s]', ''),'_','')))
</code></pre>
| 0 | 2016-07-25T15:24:40Z | [
"python",
"apache-spark",
"pyspark"
] |
What's the proper syntax to follow a link using beautifulsoup & requests in a django app? | 38,022,573 | <p>I asked a question that I don't think I was clear on. I have already succesfuly scraped posts from a sites home page. The next step is to follow the link from the post to it's detail page so I can scrape the details content. This is the code I have tried to modify but it's not working. Mind you I am a novice and I a... | 2 | 2016-06-24T21:48:33Z | 38,029,872 | <p>this will work</p>
<pre><code>def sprinkle():
url_two = 'http://www.vladtv.com'
html = requests.get(url_two, headers=headers)
soup = BeautifulSoup(html.text, 'html5lib')
titles = soup.find_all('div', {'class': 'entry-pos-1'})
def make_soup(url):
the_comments_page... | 2 | 2016-06-25T15:12:30Z | [
"python",
"django",
"web-scraping",
"beautifulsoup"
] |
AttributeError: 'module' object has no attribute 'getmro' | 38,022,587 | <p>I try to start a python app and after many problems with dependencies I got into another problem. After googling for a few hours I turned to my fav site for answers</p>
<pre><code>python manage.py runserver
</code></pre>
<p>gives:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <... | 2 | 2016-06-24T21:50:24Z | 38,029,462 | <p>I managed to solve this error by removing all the project files, reinstalling python and cloning the project once again. Thanks!</p>
| 0 | 2016-06-25T14:21:04Z | [
"python",
"django",
"python-2.7"
] |
AttributeError: 'module' object has no attribute 'getmro' | 38,022,587 | <p>I try to start a python app and after many problems with dependencies I got into another problem. After googling for a few hours I turned to my fav site for answers</p>
<pre><code>python manage.py runserver
</code></pre>
<p>gives:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <... | 2 | 2016-06-24T21:50:24Z | 38,443,318 | <p>You require <strong>django-inspect</strong>.<br>
Install it using <code>pip install django-inspect</code></p>
| 2 | 2016-07-18T18:08:50Z | [
"python",
"django",
"python-2.7"
] |
Connecting to SSH using Python | 38,022,611 | <p>I am trying to use Spur to connect to remote server via SSH. It works well when I give 'ps' and 'aux' argument, it works fine.
When I give 'ps', 'aux', '|', 'grep' and 'java' it gives me an error</p>
<pre><code>spur.results.RunProcessError: return code: 1
output: b''
stderr output: b'ERROR: Garbage option.\n*******... | 0 | 2016-06-24T21:52:05Z | 38,034,624 | <p>It should work by doing the following:</p>
<pre><code>import spur
shell = spur.SshShell(hostname='host',
username='user',
password='password')
with shell:
result = shell.run(['sh','-c','ps aux | grep java'])
print result.output
</code></pre>
<p>In my case the resul... | 1 | 2016-06-26T02:08:33Z | [
"python",
"shell",
"ssh",
"automation"
] |
Connecting to SSH using Python | 38,022,611 | <p>I am trying to use Spur to connect to remote server via SSH. It works well when I give 'ps' and 'aux' argument, it works fine.
When I give 'ps', 'aux', '|', 'grep' and 'java' it gives me an error</p>
<pre><code>spur.results.RunProcessError: return code: 1
output: b''
stderr output: b'ERROR: Garbage option.\n*******... | 0 | 2016-06-24T21:52:05Z | 38,044,241 | <p>Thanks Mostafa for the answer. I achieved the same result after using <a href="https://pexpect.readthedocs.io/en/stable/" rel="nofollow">Pexpect</a>. Here my code. I hope it helps other users.</p>
<pre><code>def connect():
s = pxssh.pxssh()
hostname = 'host'
username = 'name'
password = 'password'
... | 0 | 2016-06-26T23:52:15Z | [
"python",
"shell",
"ssh",
"automation"
] |
transform string in class instance? | 38,022,622 | <p>I would like to turn string into a class to instantiate an object. Example:</p>
<h1>A normal class:</h1>
<pre><code>class Rank:
    def __init__ (self):
        print ('obj created ...')
</code></pre>
<h1>Instantiating an object:</h1>
<pre><code>obj = Rank ()
</code></pre>
<h1>Turning str in class... | 0 | 2016-06-24T21:53:26Z | 38,022,650 | <p>This is not the best practice, but you can execute strings by using <code>exec()</code>.
For example:</p>
<pre><code>rank = 'Rank()'
exec('obj = ' + rank)
</code></pre>
<p><code>exec</code> treats its parameter as if it was the line itself. So it'll basically execute <code>obj = Rank()</code>.</p>
| 0 | 2016-06-24T21:56:13Z | [
"python",
"python-3.x"
] |
transform string in class instance? | 38,022,622 | <p>I would like to turn string into a class to instantiate an object. Example:</p>
<h1>A normal class:</h1>
<pre><code>class Rank:
    def __init__ (self):
        print ('obj created ...')
</code></pre>
<h1>Instantiating an object:</h1>
<pre><code>obj = Rank ()
</code></pre>
<h1>Turning str in class... | 0 | 2016-06-24T21:53:26Z | 38,022,681 | <p>You can use eval().</p>
<p>Example:</p>
<pre><code>class Rank:
def __init__ (self):
print ( 'obj created ...')
print ( eval("Rank") )
</code></pre>
| 0 | 2016-06-24T21:58:16Z | [
"python",
"python-3.x"
] |
transform string in class instance? | 38,022,622 | <p>I would like to turn string into a class to instantiate an object. Example:</p>
<h1>A normal class:</h1>
<pre><code>class Rank:
    def __init__ (self):
        print ('obj created ...')
</code></pre>
<h1>Instantiating an object:</h1>
<pre><code>obj = Rank ()
</code></pre>
<h1>Turning str in class... | 0 | 2016-06-24T21:53:26Z | 38,022,704 | <p>try to use dict</p>
<pre><code>class Rank:
def __init__ (self):
print ( 'obj created ...')
option = { 'rank': Rank }
obj = option['rank']
print 'init object'
obj()
init object
obj created ...
</code></pre>
| 3 | 2016-06-24T22:00:38Z | [
"python",
"python-3.x"
] |
Selenium Python - Handling No such element exception | 38,022,658 | <p>I am writing automation test in Selenium using Python. One element may or may not be present. I am trying to handle it with below code, it works when element is present. But script fails when element is not present, I want to continue to next statement if element is not present.</p>
<pre><code>try:
elem = dr... | 2 | 2016-06-24T21:56:48Z | 38,022,755 | <p>Are you not importing the exception?</p>
<pre><code>from selenium.common.exceptions import NoSuchElementException
try:
elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
elem.click()
except NosSuchElementException:
pass
</code></pre>
| -1 | 2016-06-24T22:04:49Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver"
] |
Selenium Python - Handling No such element exception | 38,022,658 | <p>I am writing automation test in Selenium using Python. One element may or may not be present. I am trying to handle it with below code, it works when element is present. But script fails when element is not present, I want to continue to next statement if element is not present.</p>
<pre><code>try:
elem = dr... | 2 | 2016-06-24T21:56:48Z | 38,022,946 | <p>Why not simplify and use logic like this? No exceptions needed.</p>
<pre><code>if elem.is_displayed():
elem.click()
</code></pre>
| -1 | 2016-06-24T22:26:05Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver"
] |
Selenium Python - Handling No such element exception | 38,022,658 | <p>I am writing automation test in Selenium using Python. One element may or may not be present. I am trying to handle it with below code, it works when element is present. But script fails when element is not present, I want to continue to next statement if element is not present.</p>
<pre><code>try:
elem = dr... | 2 | 2016-06-24T21:56:48Z | 38,023,345 | <p>You can see if the element exists and then click it if it does. No need for exceptions. Note the plural "s" in <code>.find_elements_*</code>.</p>
<pre><code>elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
elem[0].click()
</code></pre>
| 0 | 2016-06-24T23:11:59Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver"
] |
How to do special regex find and replace in emacs | 38,022,680 | <p>If anyone can tell me how to do this in emacs, it would save me a TON of time: I want to do a find and replace, but save what I "find" to put in the "replace". </p>
<p>Basically, I have a bunch of print statements throughout my file. I redefined print to verboseprint(), which prints when the verbose flag is presen... | 1 | 2016-06-24T21:58:16Z | 38,023,520 | <p><em>Figured I'd go ahead and work on the assumption that you can edit the file, will edit when you answer my comment</em></p>
<p>Not familiar with emacs (or too familiar with Python 2.5, to be honest), but assuming that you can access the file directly, this should work:</p>
<p><strong>MY TEST FILE</strong></p>
<... | 0 | 2016-06-24T23:36:51Z | [
"python",
"regex",
"replace",
"emacs"
] |
How to do special regex find and replace in emacs | 38,022,680 | <p>If anyone can tell me how to do this in emacs, it would save me a TON of time: I want to do a find and replace, but save what I "find" to put in the "replace". </p>
<p>Basically, I have a bunch of print statements throughout my file. I redefined print to verboseprint(), which prints when the verbose flag is presen... | 1 | 2016-06-24T21:58:16Z | 38,024,487 | <p>Here's a quick Emacs command that should do it. Use <code>M-x foo</code> or bind <code>foo</code> to a key.</p>
<p>The regexp here assumes that the text after <code>verboseprint</code> and up to the line end is within double-quote characters. If not, or if you want to allow whitespace here or there, adjust the reg... | 1 | 2016-06-25T02:53:28Z | [
"python",
"regex",
"replace",
"emacs"
] |
how to remove the delay in obtaining data from the Arduino via COM? | 38,022,770 | <p>I have an Arduino connected to the joystick. Arduino sends the data via COM port to my PC. On PC, the data processed by the program in Python, in which the circle moving with joystick. The fact is that after a few minutes there is a delay between the joystick and circle.</p>
<p>Code for Arduino</p>
<pre><code>#def... | 1 | 2016-06-24T22:06:14Z | 38,022,971 | <p>In the Arduino code, only send the coordinates if the coordinates change: </p>
<pre><code>int value_X = 0, value_Y = 0;
int old_X = 0, old_Y = 0;
void loop() {
value_X = analogRead(axis_X);
value_Y = analogRead(axis_Y);
if ( value_X != old_X || value_Y != old_Y )
{
Serial.print(value_X, DEC);
S... | 0 | 2016-06-24T22:28:37Z | [
"python",
"arduino",
"serial-port"
] |
Python: Passing complex (ffmpeg) arguments to Popen | 38,022,828 | <p>This ffmpeg <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen" rel="nofollow">Popen</a> invocation works :</p>
<pre><code>command = ['ffmpeg', '-y',
'-i', filename,
'-filter_complex', 'showwavespic',
'-colorkey', 'red',
'-frames:v', '1',
... | 0 | 2016-06-24T22:12:01Z | 38,023,087 | <p>These are just regular Python strings. The string value is passed directly to FFmpeg, without any interpretation by the shell.</p>
<p>So when you see a command-line example like this,</p>
<pre><code>ffmpeg -i input -filter_complex "showwavespic=s=640x120" -frames:v 1 output.png
</code></pre>
<p>First, since the ... | 2 | 2016-06-24T22:43:00Z | [
"python",
"ffmpeg",
"subprocess"
] |
Retaining empty elements when parsing with ElementTree | 38,022,862 | <p>Using Python 3.4 and ElementTree, I'm trying to add a sub-element to an xml file, keeping the xml file (written in UTF-16) otherwise exactly the same.</p>
<p>My code:</p>
<pre><code> new = new_XML_file.xml
tree = ET.parse(new)
root = tree.getroot()
new_element = ET.SubElement(root, 'RENAMED_SOUND_FILE')
new_el... | -1 | 2016-06-24T22:15:58Z | 38,023,073 | <p>Per the <a href="https://docs.python.org/3.5/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring" rel="nofollow">documentation</a>, output methods (whether you're using tostring methods or write) have a "short_empty_elements" keyword that defaults to True. Making this False should give you your desired... | 0 | 2016-06-24T22:41:50Z | [
"python",
"xml",
"elementtree"
] |
Find indices in an array that contain one of values from another array | 38,022,873 | <p>How to get the index of values in an array (a) by a another array (label) with more than one "markers"? For example, given</p>
<pre><code>label = array([1, 2])
a = array([1, 1, 2, 2, 3, 3])
</code></pre>
<p>the goal is to find the indices of <code>a</code> with the value of 1 or 2; that is, 0, 1, 2, 3. </p>
<p>I ... | 0 | 2016-06-24T22:17:18Z | 38,023,068 | <p><code>np.where(a==label)</code> is the same as <code>np.nonzeros(a==label)</code>. It tells us the coordinates (indexes) of all non-zero (or <code>True</code>) elements in the array, <code>a==label</code>.</p>
<p>So instead of trying all these different <code>where</code> expressions, focus on the conditional arra... | 1 | 2016-06-24T22:40:32Z | [
"python",
"arrays",
"numpy"
] |
Find indices in an array that contain one of values from another array | 38,022,873 | <p>How to get the index of values in an array (a) by a another array (label) with more than one "markers"? For example, given</p>
<pre><code>label = array([1, 2])
a = array([1, 1, 2, 2, 3, 3])
</code></pre>
<p>the goal is to find the indices of <code>a</code> with the value of 1 or 2; that is, 0, 1, 2, 3. </p>
<p>I ... | 0 | 2016-06-24T22:17:18Z | 38,023,077 | <p>As I understand it, you want the indices of 1 and 2 in array "a".</p>
<p>In that case, try</p>
<pre><code>label= [1,2]
a= [1,1,2,2,3,3]
idx_list = list()
for x in label:
for i in range(0,len(a)-1):
if a[i] == x:
idx_list.append(i)
</code></pre>
| 0 | 2016-06-24T22:42:17Z | [
"python",
"arrays",
"numpy"
] |
Find indices in an array that contain one of values from another array | 38,022,873 | <p>How to get the index of values in an array (a) by a another array (label) with more than one "markers"? For example, given</p>
<pre><code>label = array([1, 2])
a = array([1, 1, 2, 2, 3, 3])
</code></pre>
<p>the goal is to find the indices of <code>a</code> with the value of 1 or 2; that is, 0, 1, 2, 3. </p>
<p>I ... | 0 | 2016-06-24T22:17:18Z | 38,023,136 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html#numpy.in1d" rel="nofollow"><code>numpy.in1d</code></a>:</p>
<pre><code>>>> a = numpy.array([1, 1, 2, 2, 3, 3])
>>> label = numpy.array([1, 2])
>>> numpy.in1d(a, label)
array([ True, True, True, Tru... | 4 | 2016-06-24T22:49:23Z | [
"python",
"arrays",
"numpy"
] |
Find indices in an array that contain one of values from another array | 38,022,873 | <p>How to get the index of values in an array (a) by a another array (label) with more than one "markers"? For example, given</p>
<pre><code>label = array([1, 2])
a = array([1, 1, 2, 2, 3, 3])
</code></pre>
<p>the goal is to find the indices of <code>a</code> with the value of 1 or 2; that is, 0, 1, 2, 3. </p>
<p>I ... | 0 | 2016-06-24T22:17:18Z | 38,023,422 | <p>I think what I'm reading as your intent is to get the indices in the second list, 'a', of the values in the first list, 'labels'. I think that a dictionary is a good way to store this information where the labels will be keys and indices will be the values.</p>
<p>Try this:</p>
<pre><code> labels = [a,2]
a... | 0 | 2016-06-24T23:22:40Z | [
"python",
"arrays",
"numpy"
] |
How to unit test a python version switch | 38,022,926 | <p>How can I write a unit test for the following function:</p>
<pre><code>def version_switch():
if sys.version_info.major < 3:
print('not python 3')
else:
print('python 3')
</code></pre>
<p>My first thought was mocking <code>sys.version_info.major</code> but as it is a read only attribute i... | 0 | 2016-06-24T22:23:51Z | 38,022,986 | <p>You may not be able to swap out the value of <code>major</code> on <code>sys.version_info</code>, but you can swap out the value of <code>version_info</code> on <code>sys</code>:</p>
<pre><code>Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type ... | 2 | 2016-06-24T22:30:28Z | [
"python",
"python-2.7",
"unit-testing",
"python-3.x",
"py.test"
] |
How to unit test a python version switch | 38,022,926 | <p>How can I write a unit test for the following function:</p>
<pre><code>def version_switch():
if sys.version_info.major < 3:
print('not python 3')
else:
print('python 3')
</code></pre>
<p>My first thought was mocking <code>sys.version_info.major</code> but as it is a read only attribute i... | 0 | 2016-06-24T22:23:51Z | 38,023,063 | <blockquote>
<p>however, each run will only check one code path</p>
</blockquote>
<p>So?</p>
<p>You don't <em>care</em> what the Python 3 code path would do if you ran it on Python 2, or vice versa. There's no need to test that. Just check that the output correctly corresponds to the Python version you're running o... | 1 | 2016-06-24T22:39:59Z | [
"python",
"python-2.7",
"unit-testing",
"python-3.x",
"py.test"
] |
Python Sync Variables in multiprocessing | 38,022,960 | <p>I'm sure this has been asked before, I looked all over and could not find anything! Don't yell at me if you find this to be a duplicate, just give a link or copy the details.</p>
<p>Anyways, I have this data structure, like this:</p>
<pre><code>data = {
'sysstats': {
'sysgen_time': datetime.now ( ),
... | 0 | 2016-06-24T22:27:23Z | 38,023,213 | <p>Well, might I suggest the possibility of a <em>redesign?</em></p>
<p>It seems, from your description, that you've launched a process/thread that's doing a <em>busy wait</em> to find out "if three minutes have gone by." </p>
<p>... and <em>then,</em> "unfortunately, to make matters much worse," it is going to try ... | 0 | 2016-06-24T22:57:58Z | [
"python",
"variables",
"synchronization",
"multiprocessing",
"shared"
] |
CSV and PyEnchant Python Program | 38,022,981 | <p>I'm attemping to comb through a list of a couple hundred thousand words in a csv file, in order to determine which ones are not english. I know I can utilize PyEnchant to do this, but I'm new to coding in general and could use some help on the details.</p>
<p>Here's what I have thus far, I've created a list "L" to ... | 0 | 2016-06-24T22:29:58Z | 38,023,223 | <p>after you create instance of enchant, using check to check each word in your file<br>
your code is reading each line of file, however it could contain more than one word each line, so please also iterate each row. </p>
<pre><code>import enchant
import csv
with open('list.csv') as csvfile:
shortcut = csv.reade... | 0 | 2016-06-24T22:59:04Z | [
"python",
"csv"
] |
How can I get the value of the EC2 instance tag "Name" with boto? | 38,023,082 | <p>I'm working from the instance id. I can get the tags, but I can't figure out how filter on both the instance id and the tag "Name" or index in and return the value of the tag called "Name"</p>
<p>I ended up grabbing all tags and iterating over them till I find the one I want, which can't possibly be right.</p>
<pr... | 2 | 2016-06-24T22:42:33Z | 38,023,634 | <p>You do have a better way:</p>
<pre><code>conn.get_all_images(filters={'tag-key': 'Name'. 'resource-id': instance_id})
</code></pre>
| 2 | 2016-06-24T23:56:03Z | [
"python",
"amazon-ec2",
"boto"
] |
How can I get the value of the EC2 instance tag "Name" with boto? | 38,023,082 | <p>I'm working from the instance id. I can get the tags, but I can't figure out how filter on both the instance id and the tag "Name" or index in and return the value of the tag called "Name"</p>
<p>I ended up grabbing all tags and iterating over them till I find the one I want, which can't possibly be right.</p>
<pr... | 2 | 2016-06-24T22:42:33Z | 38,023,646 | <p>I think the way you're doing it is fine. You could always wrap it in a function call as an abstraction:</p>
<pre><code>def get_instance_tag(all_tags, tag_name):
for tag in all_tags:
if tag_name == tag.name:
return tag.value
return None
name = get_instance_tag(conn.get_all_tags({'resource-id': instan... | 0 | 2016-06-24T23:57:40Z | [
"python",
"amazon-ec2",
"boto"
] |
Debugging program in Spyder IDE | 38,023,191 | <p>Given the following piece of code (see 3rd code block) (not mine and available at <a href="http://neuralnetworksanddeeplearning.com/chap1.html#implementing_our_network_to_classify_digits" rel="nofollow">http://neuralnetworksanddeeplearning.com/chap1.html#implementing_our_network_to_classify_digits</a>)</p>
<p>Initi... | 0 | 2016-06-24T22:55:54Z | 38,060,110 | <p>You need to run it using the debugger, rather than running it normally. Under the <code>Debug</code> toolbar entry, just press the <code>Debug</code> entry. This will run it with the debugger, allowing you to step through, run to breakpoints, etc. In my version there is a also a toolbar button for it (a blue "pla... | 0 | 2016-06-27T17:45:49Z | [
"python",
"debugging",
"spyder"
] |
python packages with dependencies in windows system | 38,023,256 | <p>I am trying to work with python on a new project in my windows system. The project uses ffmpeg and pyrabin among others. I find it extremely difficult to move forward with pip installing these packages as they constantly keep on asking for missing dependencies. Following are some errors:</p>
<blockquote>
<p>ffvid... | 0 | 2016-06-24T23:02:48Z | 38,023,476 | <p>You're basically asking how to quickly set up a development environment to compile a given project. You're generally at the mercy of the project developers and how well they documented the build process. </p>
<p>On linux, you often have a package manager to make the installing and resolving of dependencies easy.</... | 0 | 2016-06-24T23:31:20Z | [
"python",
"windows",
"pyffmpeg"
] |
How to Make a Portable Jupyter Slideshow | 38,023,285 | <p>How do I make a Jupyter slide show portable? I can serve the slideshow locally, but I can't send that to anyone and have it work with all the images, slide animation functionality, etc. </p>
<p>I am using <code>jupyter nbconver my_notebook.ipynb --to slides</code> and get a simple linear html file that depends on t... | 3 | 2016-06-24T23:05:33Z | 38,023,879 | <p>You should specify <code>--reveal-prefix</code> to convert it, <a href="http://nbconvert.readthedocs.io/en/latest/usage.html#reveal-js-html-slideshow" rel="nofollow">nbconvert doc</a>.</p>
<pre><code>jupyter nbconvert my_notebook.ipynb --to slides --post serve --reveal-prefix "http://cdnjs.cloudflare.com/ajax/libs/... | 2 | 2016-06-25T00:40:46Z | [
"python",
"ipython",
"jupyter",
"reveal.js"
] |
Python 2 Get the highest prim factor of a number || invalid synthax | 38,023,299 | <p>i try to write a program in Python 2 that searches me the biggest prim factor of a number.
But i have problems with my code:</p>
<pre><code>def all_prims():
primnumbers = []
numbers = [True] * (1000 + 1)
#0 and 1 aren't prims, so False
numbers[0] = False
numbers[1] = False
i = 2
while i * i <= 1000:
if n... | -5 | 2016-06-24T23:06:42Z | 38,024,116 | <p>You need to add another parenthesis to close this line:</p>
<pre><code>number = int( raw_input( 'Please insert a Number: ' )
</code></pre>
<p>So it becomes:</p>
<pre><code>number = int(raw_input('Please insert a Number: '))
</code></pre>
| 0 | 2016-06-25T01:30:11Z | [
"python",
"syntax",
"primes"
] |
Why isn't it filter(not None, iterable)? | 38,023,300 | <p>Since the definition of <code>filter()</code> is to return a list of elements in which the function returns <code>True</code>, wouldn't <code>filter(not None, iterable)</code> make more sense for filtering to a list that only includes items that aren't <code>NoneType</code>? </p>
| 1 | 2016-06-24T23:06:43Z | 38,023,325 | <p>It is, kind of, you just need to turn it into a function</p>
<pre><code>filter(lambda x: x is not None, iterable)
</code></pre>
| 1 | 2016-06-24T23:09:33Z | [
"python",
"python-3.x"
] |
Why isn't it filter(not None, iterable)? | 38,023,300 | <p>Since the definition of <code>filter()</code> is to return a list of elements in which the function returns <code>True</code>, wouldn't <code>filter(not None, iterable)</code> make more sense for filtering to a list that only includes items that aren't <code>NoneType</code>? </p>
| 1 | 2016-06-24T23:06:43Z | 38,023,328 | <p><a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow">Quoting from the docs</a></p>
<blockquote>
<p>If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.</p>
</blockquote>
<p>In other words, passing <code>None</code> in the... | 4 | 2016-06-24T23:10:15Z | [
"python",
"python-3.x"
] |
Why isn't it filter(not None, iterable)? | 38,023,300 | <p>Since the definition of <code>filter()</code> is to return a list of elements in which the function returns <code>True</code>, wouldn't <code>filter(not None, iterable)</code> make more sense for filtering to a list that only includes items that aren't <code>NoneType</code>? </p>
| 1 | 2016-06-24T23:06:43Z | 38,023,334 | <p><code>not None</code> is just <code>True</code>. The correct syntax for what you're thinking of would be</p>
<pre><code>filter(lambda x: x is not None, iterable)
</code></pre>
<p>That would work for what you're trying to do, but it's not actually what <code>filter(None, iterable)</code> does.</p>
<p><code>filter(... | 3 | 2016-06-24T23:10:53Z | [
"python",
"python-3.x"
] |
Why isn't it filter(not None, iterable)? | 38,023,300 | <p>Since the definition of <code>filter()</code> is to return a list of elements in which the function returns <code>True</code>, wouldn't <code>filter(not None, iterable)</code> make more sense for filtering to a list that only includes items that aren't <code>NoneType</code>? </p>
| 1 | 2016-06-24T23:06:43Z | 38,023,431 | <blockquote>
<p>Since the definition of <code>filter()</code> is to return a list of elements in
which the <strong>function</strong> returns True</p>
</blockquote>
<p>But <code>not None</code> is a not function, and so not callable. <code>None</code> is used as shorthand for the identity predicate (not just functi... | 3 | 2016-06-24T23:23:48Z | [
"python",
"python-3.x"
] |
Why isn't it filter(not None, iterable)? | 38,023,300 | <p>Since the definition of <code>filter()</code> is to return a list of elements in which the function returns <code>True</code>, wouldn't <code>filter(not None, iterable)</code> make more sense for filtering to a list that only includes items that aren't <code>NoneType</code>? </p>
| 1 | 2016-06-24T23:06:43Z | 38,023,555 | <p>For <em>python3</em> you don't need to use a lambda, <code>None.__ne__</code> will only filter <em>None</em>:</p>
<pre><code>In [1]: list(filter(None.__ne__, [None, 0, 1, 2]))
Out[1]: [0, 1, 2]
</code></pre>
| 3 | 2016-06-24T23:42:01Z | [
"python",
"python-3.x"
] |
Raw Custom Logs in Google App Engine Flexible Environment | 38,023,451 | <p>I've used the following code in a Flexible (VM) Environment on Google App Engine to separate custom logs with a specific formatting requirement from other application logs:</p>
<pre><code>import logging as std_logging
std_logging.basicConfig()
custom_formatter = std_logging.Formatter('%(created)f\t%(message)s')
c... | 1 | 2016-06-24T23:27:08Z | 38,380,746 | <p>The extra information is actually quite handy, especially in an appengine environment where filtering on module/service, version, or instance_id can really help you investigate issues.</p>
<p>If reprocessing the logs is your problem, I would suggest turing on the <a href="https://cloud.google.com/logging/docs/expor... | 0 | 2016-07-14T17:38:35Z | [
"python",
"google-app-engine"
] |
SWIG: How to pass list of complex from c++ to python | 38,023,521 | <p>I have a function in c++ who returns a list of complex:</p>
<pre><code>#include <complex>
std::list< std::complex<double> > func(...);
</code></pre>
<p>what should i do in the '*.i' file ?</p>
<p>Thank you every body.</p>
<p>=================</p>
<p>Following are details:</p>
<p>the function ... | 1 | 2016-06-24T23:36:53Z | 38,028,645 | <p>This works:</p>
<pre><code>%include <std_list.i>
%include <std_complex.i>
%template(ComplexList) std::list<std::complex<double> >;
... (your includes / function declarations)
</code></pre>
<p>I think your version (3) should actually also work. Strange that it doesn't. Maybe a SWIG bug.</p>
| 0 | 2016-06-25T12:41:40Z | [
"python",
"c++",
"list",
"swig",
"complex-numbers"
] |
Is it safe to do a data migration as just one operation in a larger Django migration? | 38,023,545 | <p>I am handling what I assume is a common issue: I've realized that an existing model field of the model <code>Foo</code> would be better as a completely seperate model <code>Bar</code> with a foreign key to <code>Foo</code>. So, we need to make a schema migration. But what's more, since there is already existing data... | 3 | 2016-06-24T23:39:56Z | 38,023,725 | <p>With regards to Django itself, this is perfectly safe. Each operation will receive the correct state based on all previous migrations and operations within the same migration. Your <code>RunPython</code> operation will receive an app registry that includes the new <code>Bar</code> model and still has the old field o... | 2 | 2016-06-25T00:11:11Z | [
"python",
"django"
] |
flask-security make user always signed in | 38,023,610 | <p>Im trying to make it so a specific user is always logged in using the flask security extension.</p>
<p>I cant find any docs on this.
Can someone point me in the right direction to start.</p>
| 0 | 2016-06-24T23:52:37Z | 38,023,876 | <p><a href="https://flask-login.readthedocs.io/en/latest/#cookie-settings" rel="nofollow">https://flask-login.readthedocs.io/en/latest/#cookie-settings</a></p>
<blockquote>
<p>âRemember Meâ functionality can be tricky to implement. However, Flask-Login makes it nearly transparent - just pass remember=True to
t... | 0 | 2016-06-25T00:39:43Z | [
"python",
"flask",
"flask-login",
"flask-security"
] |
Writing plot increments in Latex font? | 38,023,626 | <p>Is there a way to type the increments on the x and y axes in Latex font, instead of just Arial? </p>
<p>Likewise, the legend?</p>
| 0 | 2016-06-24T23:54:50Z | 38,040,164 | <p>To change the font of the axis labels, in the preamble of your program, you can
do so by editing the <code>rc</code> parameters:</p>
<pre><code>import matplotlib
font = {'fontname' : 'serif',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
</code></pre>
<p>Now your font labels ar... | 1 | 2016-06-26T15:37:46Z | [
"python",
"matplotlib",
"latex"
] |
How to nest LabelKFold? | 38,023,726 | <p>I have a dataset with ~300 points and 32 distinct labels and I want to evaluate a LinearSVR model by plotting its learning curve using grid search and LabelKFold validation.</p>
<p>The code I have looks like this:</p>
<pre><code>import numpy as np
from sklearn import preprocessing
from sklearn.svm import LinearSVR... | 13 | 2016-06-25T00:11:17Z | 39,374,458 | <p>From your question, you are looking for the LabelKFold score on your data, while grid-searching the parameters of your pipeline in each of the iterations of this outer LabelKFold, using again a LabelKFold. Although I was not able to achieve that out-of-the-box it takes only one loop: </p>
<pre><code>outer_cv = Labe... | 3 | 2016-09-07T15:54:28Z | [
"python",
"scikit-learn",
"cross-validation"
] |
I have to create a basic Bank Menu and I've been having a hard time wrapping my head around it | 38,023,865 | <p>I'm trying to figure out where to go from here, I know I have to have an accumulator somewhere in there to show the current balance of the the user. I'm not quite sure how to implement it, as well as keeping it persistent when the user wants to do other things like 'withdrawal' and other stuff. </p>
<p>I've also ... | -3 | 2016-06-25T00:37:36Z | 38,024,107 | <p>I don't understand what you are trying to do, but i am going to guess. </p>
<p>You want a program that while the user doesn't hit five doesn't exit, right?</p>
<p>The way I'd do it</p>
<pre><code>from sys import exit
balance = 0.0000
print("Welcome to Sys Financial Bank! New clients must open a new account to co... | 0 | 2016-06-25T01:28:53Z | [
"python",
"menu",
"bank"
] |
Pandas - change the order of levels of factor-type object | 38,023,881 | <p>I have a Pandas dataframe <code>df</code> with column <code>school</code> as factor</p>
<pre><code>Name school
A An
B Bn
C Bn
</code></pre>
<p>How can I change the levels of the <code>school</code> column from ('An', 'Bn') to ('Bn', 'An') in python?</p>
<p>R equivalent is </p>
<pre><code>lev... | 2 | 2016-06-25T00:41:02Z | 38,023,941 | <p>As a general solution, you can remap using a dictionary:</p>
<pre><code>df = pd.DataFrame({'Name': ['A', 'B', 'C'],
'school': ['An', 'Bn', 'Bn']})
d = {'An': 'Bn', 'Bn': 'An'}
df['school'] = df.school.map(d)
>>> df
Name school
0 A Bn
1 B An
2 C An
</code></pre>
| 1 | 2016-06-25T00:51:44Z | [
"python",
"pandas"
] |
Pandas - change the order of levels of factor-type object | 38,023,881 | <p>I have a Pandas dataframe <code>df</code> with column <code>school</code> as factor</p>
<pre><code>Name school
A An
B Bn
C Bn
</code></pre>
<p>How can I change the levels of the <code>school</code> column from ('An', 'Bn') to ('Bn', 'An') in python?</p>
<p>R equivalent is </p>
<pre><code>lev... | 2 | 2016-06-25T00:41:02Z | 38,024,183 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.CategoricalIndex.reorder_categories.html" rel="nofollow"><code>reorder_categories</code></a> (you pass in the sorted factors):</p>
<pre><code>In [11]: df
Out[11]:
Name school
0 A An
1 B Bn
2 C Bn
In [12]: df['s... | 3 | 2016-06-25T01:42:41Z | [
"python",
"pandas"
] |
Pandas - change the order of levels of factor-type object | 38,023,881 | <p>I have a Pandas dataframe <code>df</code> with column <code>school</code> as factor</p>
<pre><code>Name school
A An
B Bn
C Bn
</code></pre>
<p>How can I change the levels of the <code>school</code> column from ('An', 'Bn') to ('Bn', 'An') in python?</p>
<p>R equivalent is </p>
<pre><code>lev... | 2 | 2016-06-25T00:41:02Z | 38,024,803 | <p>You can set <code>cat.categories</code>:</p>
<pre><code>import pandas as pd
school = pd.Series(["An", "Bn", "Bn"])
school = school.astype("category")
school.cat.categories = ["Bn", "An"]
</code></pre>
| 0 | 2016-06-25T03:58:57Z | [
"python",
"pandas"
] |
Shortest distance from point to function scipy | 38,023,938 | <p>Given the output of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" rel="nofollow">scipy.interpolate.interp1d</a> (function f) and a 2D point (let's say <code>test_pnt.X</code> and <code>test_pnt.Y</code>) is there a scipy function to calculate... | 1 | 2016-06-25T00:51:14Z | 38,024,008 | <p>You can use</p>
<pre><code> scipy.lining.norm(x-test_pnt.X, f(x) - test_pnt.Y)
</code></pre>
<p>to get the actual distance between the point and the function</p>
| 2 | 2016-06-25T01:07:30Z | [
"python",
"scipy",
"interpolation",
"points",
"spline"
] |
UnicodeDecodeError 'charmap' codec with Tesseract OCR in Python | 38,023,947 | <p>I am trying to do OCR on an image file in python using teseract-OCR.
My environment is-
Python 3.5 Anaconda on Windows Machine. </p>
<p>Here is the code:</p>
<pre><code>from PIL import Image
from pytesseract import image_to_string
out = image_to_string(Image.open('sample.png'))
</code></pre>
<p>The error I am g... | 1 | 2016-06-25T00:52:39Z | 38,024,096 | <p>Hmm..something very weird going on there -
The character "\x81" is unprintable when we talk about the "latin1" text encoding. However, on the "cp1252" encoding the library is using, it is mapped instead to an "undefined character" - this is explicit.</p>
<p>What happens is that "latin1" is somewhat a "no-op" code... | 0 | 2016-06-25T01:26:27Z | [
"python",
"character-encoding",
"tesseract",
"python-tesseract"
] |
Where is Python's coroutine type defined? | 38,024,104 | <p>I'm working on Python 3.5.1 and I want to be able to tell if a function has returned as coroutine object but I cannot find where the coroutine type is defined, instead as of late I've been using the below snippet to get the type through instantiating a coroutine with a function.</p>
<pre><code>async def _f():
p... | 0 | 2016-06-25T01:28:39Z | 38,024,204 | <p>The best way to tell if a function is a coroutine is with <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.iscoroutinefunction" rel="nofollow"><code>asyncio.iscoroutinefunction</code></a>. </p>
<pre><code>asyncio.iscoroutinefunction(some_func)
</code></pre>
| 1 | 2016-06-25T01:46:32Z | [
"python",
"async-await",
"python-3.4",
"python-3.5",
"python-asyncio"
] |
Where is Python's coroutine type defined? | 38,024,104 | <p>I'm working on Python 3.5.1 and I want to be able to tell if a function has returned as coroutine object but I cannot find where the coroutine type is defined, instead as of late I've been using the below snippet to get the type through instantiating a coroutine with a function.</p>
<pre><code>async def _f():
p... | 0 | 2016-06-25T01:28:39Z | 38,024,291 | <p>Python's coroutine type is defined in <a href="https://github.com/python/cpython/blob/master/Lib/_collections_abc.py" rel="nofollow"><code>_collections_abc</code></a>, which is imported in <a href="https://github.com/python/cpython/blob/master/Lib/collections/abc.py" rel="nofollow"><code>collections.abc</code></a>, ... | 0 | 2016-06-25T02:07:31Z | [
"python",
"async-await",
"python-3.4",
"python-3.5",
"python-asyncio"
] |
Where is Python's coroutine type defined? | 38,024,104 | <p>I'm working on Python 3.5.1 and I want to be able to tell if a function has returned as coroutine object but I cannot find where the coroutine type is defined, instead as of late I've been using the below snippet to get the type through instantiating a coroutine with a function.</p>
<pre><code>async def _f():
p... | 0 | 2016-06-25T01:28:39Z | 38,024,333 | <p>Probably the best way to access the coroutine type is through the <a href="https://docs.python.org/3/library/types.html#types.CoroutineType" rel="nofollow"><code>types</code></a> module:</p>
<pre><code>import types
types.CoroutineType # here it is
</code></pre>
<p>That's not actually where the coroutine type is ... | 1 | 2016-06-25T02:15:42Z | [
"python",
"async-await",
"python-3.4",
"python-3.5",
"python-asyncio"
] |
Python: Accessing a specific object efficiently as if it were a dict | 38,024,196 | <p>Currently I'm coding up some graph theory stuff in Python, at this point DFS. I've made a Node class which holds the name of the Node (vertex if you like) and a list of strings with the names of all the other nodes with which it is connected. </p>
<pre><code># Simplified for the sake of the question.
class Node:
... | 0 | 2016-06-25T01:45:04Z | 38,024,410 | <p>Why you don't create a dict that link letters to nodes instead of traversing all nodes whenever you want to know which node has the letter.</p>
<p>So the idea is simple</p>
<ul>
<li>create dic with letters as keys and nodes as values</li>
<li>and whenever you create a node add it to the dict</li>
<li>and when ever... | 0 | 2016-06-25T02:34:03Z | [
"python",
"class",
"dictionary",
"graph",
"graph-theory"
] |
Python: Accessing a specific object efficiently as if it were a dict | 38,024,196 | <p>Currently I'm coding up some graph theory stuff in Python, at this point DFS. I've made a Node class which holds the name of the Node (vertex if you like) and a list of strings with the names of all the other nodes with which it is connected. </p>
<pre><code># Simplified for the sake of the question.
class Node:
... | 0 | 2016-06-25T01:45:04Z | 38,024,445 | <p>You can subclass most Python types (besides the NoneType, to my knowledge, and the GeneratorType).</p>
<p>Just do something like this:</p>
<pre><code>class MyDict(dict):
'''This walks and talks like a dict'''
def do_something(self):
print(repr(self))
</code></pre>
<p>You can extend it however you... | 1 | 2016-06-25T02:42:55Z | [
"python",
"class",
"dictionary",
"graph",
"graph-theory"
] |
Martingale method | 38,024,202 | <p>I'm trying to simulate the <a href="https://en.wikipedia.org/wiki/Martingale_%28probability_theory%29" rel="nofollow">martingale method</a>, but it doesn't seem to do anything.</p>
<p>Here's my code:</p>
<pre><code>import random
w = 1 # wager
# w1 = w # an amount for reference when the wager has to go back to i... | 0 | 2016-06-25T01:45:45Z | 38,024,282 | <p>Try doing it with iterator:</p>
<pre><code>for x in range(0,10):
for i in range(0,100):
y = random.randint(0, 1) # Picking between 1 or 0 for a %50 chance.
if y == 1: #
br += w
wins += 1
w = 1
else:
br -= w #
w *= 2
l... | 0 | 2016-06-25T02:04:56Z | [
"python"
] |
Martingale method | 38,024,202 | <p>I'm trying to simulate the <a href="https://en.wikipedia.org/wiki/Martingale_%28probability_theory%29" rel="nofollow">martingale method</a>, but it doesn't seem to do anything.</p>
<p>Here's my code:</p>
<pre><code>import random
w = 1 # wager
# w1 = w # an amount for reference when the wager has to go back to i... | 0 | 2016-06-25T01:45:45Z | 38,024,531 | <p>The reason it never ends is because your indentation is wrong for incrementing the counters. You also have a lot of unnecessary code. Here's a cleaned-up version, that will finish â so you can continue working on it.</p>
<pre><code>import random
w = 1 # Wager
br = 10000000 # Bankroll
losses = 0 # K... | 0 | 2016-06-25T03:01:33Z | [
"python"
] |
Martingale method | 38,024,202 | <p>I'm trying to simulate the <a href="https://en.wikipedia.org/wiki/Martingale_%28probability_theory%29" rel="nofollow">martingale method</a>, but it doesn't seem to do anything.</p>
<p>Here's my code:</p>
<pre><code>import random
w = 1 # wager
# w1 = w # an amount for reference when the wager has to go back to i... | 0 | 2016-06-25T01:45:45Z | 38,024,624 | <p>Try tabbing over your incrementers i += 1 and x += 1. They should line up with the other code in the loop and not with the while statements.</p>
| 0 | 2016-06-25T03:23:27Z | [
"python"
] |
My Kivy android app keeps crashing on start up even though it runs perfectly fine my PC | 38,024,299 | <p>I made an app using kivy on my PC running Ubuntu 16,[64bit], I am new to kivy, but I managed to successfully run the app on my PC, the app includes a kv file, a png, and a video [avi]. I used buildozer to create the apk but every time I run the app on my android device it crashes on start up. I have successfully run... | 0 | 2016-06-25T02:08:45Z | 38,030,566 | <p>When I started with Kivy I had same kind of problems. Solution for my problem was to add needed libries to buildozer file.</p>
<pre><code>requirements = kivy,jsonrpclib,jsonpickle
</code></pre>
<p>And in source I have also "pyc", but I'm not sure is it needed.</p>
<pre><code>source.include_exts = py,pyc,png,jpg,k... | 0 | 2016-06-25T16:31:22Z | [
"android",
"python",
"kivy",
"buildozer",
"kivy-language"
] |
Read particular numbers from a particular line | 38,024,399 | <p>I have a certain text file from which stores certain properties about 'n' number of points. The lines of the file are as follows:</p>
<pre><code>line 1 yy
line 2 zz
line 3 aa
line 4 bb
line 5 cc
line 6 Absolute values
line 7 lut flp err
lin... | 0 | 2016-06-25T02:32:10Z | 38,024,512 | <pre><code>#!/usr/bin/env python3
f = open('data')
err_dict = {k: [] for k in ['p','v','s','T']}
i = 0
for line in f:
i += 1
if i < 8:
continue
if line.startswith("POINT "):
continue
line_split = line.split()
err_dict[line_split[0]].append(line_split[3])
err_p = err_dict['p'... | 0 | 2016-06-25T02:58:12Z | [
"python",
"file-io"
] |
Read particular numbers from a particular line | 38,024,399 | <p>I have a certain text file from which stores certain properties about 'n' number of points. The lines of the file are as follows:</p>
<pre><code>line 1 yy
line 2 zz
line 3 aa
line 4 bb
line 5 cc
line 6 Absolute values
line 7 lut flp err
lin... | 0 | 2016-06-25T02:32:10Z | 38,024,761 | <p>Iterate over the lines in the file; split each line; pick out the part you are interested in; <em>save</em> it if it matches your criteria.</p>
<p>Use a couple of helpers for readability</p>
<pre><code>import operator
col_zero = operator.itemgetter(0)
err = operator.itemgetter(3)
</code></pre>
<p>Use a set to tes... | 0 | 2016-06-25T03:49:38Z | [
"python",
"file-io"
] |
Argparse shortcut option for combining other options | 38,024,501 | <p>Let's say I have an input file option and an output file option. How can I create an option that combines the two? For example:</p>
<pre><code>$ ./my_script.py -i input.txt -o output.txt
</code></pre>
<p>could be combined as:</p>
<pre><code>$ ./my_script.py --io input_output.txt
</code></pre>
<p>You might say ... | 0 | 2016-06-25T02:56:03Z | 38,024,693 | <p>Keep it simple--the exclusive groups code you showed didn't exclude using both forms anyway. Try this:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", help="Input file")
parser.add_argument("-o", "--output", help="Output file")
parser.add_argument("--io", he... | 0 | 2016-06-25T03:37:25Z | [
"python",
"argparse"
] |
Argparse shortcut option for combining other options | 38,024,501 | <p>Let's say I have an input file option and an output file option. How can I create an option that combines the two? For example:</p>
<pre><code>$ ./my_script.py -i input.txt -o output.txt
</code></pre>
<p>could be combined as:</p>
<pre><code>$ ./my_script.py --io input_output.txt
</code></pre>
<p>You might say ... | 0 | 2016-06-25T02:56:03Z | 38,024,708 | <p>It is easier to explain why things don't work than to suggest a solution.</p>
<p>Yes, <code>dest</code> must be a string; there's no provision for a list or tuple of <code>dest</code> values. But your <code>in_file = out_file = args.io</code> addresses that issue just fine. You could have also used:</p>
<pre><co... | 1 | 2016-06-25T03:40:41Z | [
"python",
"argparse"
] |
Color underplot of tsplot | 38,024,511 | <p>I'd like to color the lower part of a <code>tsplot</code> in Seaborn. I have the following code:</p>
<p><code>sns.tsplot(time=time,data=data)</code></p>
<p>Is it possible to color the lower area of the plot? I tried using <code>barplot</code>, but my data is too large so it just doesn't look right. Any advice?</p>... | 1 | 2016-06-25T02:57:45Z | 38,025,431 | <p>Try to use <code>fill_between</code> from matplotlib, like here:</p>
<pre><code>import numpy as np; np.random.seed(22)
import seaborn as sns; sns.set(color_codes=True)
import matplotlib.pylab as plt
x = np.arange(31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
sns.tsplot(data=data)
ax = plt.g... | 1 | 2016-06-25T05:48:58Z | [
"python",
"matplotlib",
"seaborn"
] |
Get the intensity and position of a group of peaks in a image | 38,024,525 | <p>I have a photo shown as follow:</p>
<p><img src="http://i.stack.imgur.com/iQywk.gif" alt="Black background with white dots of different intensity"></p>
<p>I want to use Python to identify all the white peaks and tag their position with a series of numbers in that image. And every peak I should return the following... | 1 | 2016-06-25T03:00:53Z | 38,028,351 | <p>Not sure if you want to spend an age getting every last detail in a sophisticated way with some expensive software, or whether you just want to get started with something very simple. Anyway, you could consider using Imagemagick which is free and installed on most Linux distros and is available for OSX and Windows -... | 0 | 2016-06-25T12:05:52Z | [
"python",
"image",
"image-processing"
] |
Python iterator and zip | 38,024,554 | <p>With <code>x = [1,2,3,4]</code>, I can get an iterator from <code>i = iter(x)</code>.</p>
<p>With this iterator, I can use zip function to create a tuple with two items.</p>
<pre><code>>>> i = iter(x)
>>> zip(i,i)
[(1, 2), (3, 4)]
</code></pre>
<p>Even I can use this syntax to get the same resul... | 3 | 2016-06-25T03:08:08Z | 38,024,578 | <p>Every time you get an item from an iterator, it stays at that spot rather than "rewinding." So <code>zip(i, i)</code> gets the first item from <code>i</code>, then the second item from <code>i</code>, and returns that as a <code>tuple</code>. It continues to do this for each available pair, until the iterator is exh... | 0 | 2016-06-25T03:13:39Z | [
"python",
"iterator",
"zip"
] |
Python iterator and zip | 38,024,554 | <p>With <code>x = [1,2,3,4]</code>, I can get an iterator from <code>i = iter(x)</code>.</p>
<p>With this iterator, I can use zip function to create a tuple with two items.</p>
<pre><code>>>> i = iter(x)
>>> zip(i,i)
[(1, 2), (3, 4)]
</code></pre>
<p>Even I can use this syntax to get the same resul... | 3 | 2016-06-25T03:08:08Z | 38,024,584 | <p>An iterator is like a stream of items. You can only look at the items in the stream one at a time and you only ever have access to the first element. To look at something in the stream, you need to remove it from the stream and once you take something from the top of the stream, it's gone from the stream for good.... | 5 | 2016-06-25T03:15:08Z | [
"python",
"iterator",
"zip"
] |
While Loop Not Breaking In Python | 38,024,602 | <p>I have a program like this:</p>
<pre><code>def read():
while True:
for line in temp1:
if event in line:
print temp1.next()
elif date in line:
print temp1.next()
elif ending in line:
print 'End of file'
br... | 0 | 2016-06-25T03:17:50Z | 38,024,619 | <p>Your <code>break</code> statement only breaks out of the <code>for</code> loop (if it's hit). It doesn't, and indeed, can't break out of the <code>while</code> loop as well. Though I'm not sure what the <code>while</code> loop is there for, since the <code>for</code> loop should iterate over the whole file. Since yo... | 4 | 2016-06-25T03:22:26Z | [
"python",
"while-loop"
] |
While Loop Not Breaking In Python | 38,024,602 | <p>I have a program like this:</p>
<pre><code>def read():
while True:
for line in temp1:
if event in line:
print temp1.next()
elif date in line:
print temp1.next()
elif ending in line:
print 'End of file'
br... | 0 | 2016-06-25T03:17:50Z | 38,024,702 | <p>Add a second break statement on the line after the first break statement, but line it up with your for statement.</p>
| 0 | 2016-06-25T03:39:16Z | [
"python",
"while-loop"
] |
Python - Using subprocess to Pipe R Script, resultant Winerror 2 | 38,024,676 | <p>I'm trying to run an R Script through Python using <code>subprocess</code> but unfortunately, I'm continually getting the following error:</p>
<pre><code>WindowsError: [Error 2] The system cannot find the file specified
</code></pre>
<p>This is extremely frustrating as I've checked the path over everything multipl... | 0 | 2016-06-25T03:33:16Z | 38,026,771 | <p>To solve this most annoying and horrendous problem, I reinstalled R into a directory with no spaces and called <code>Rscript</code> with its full pathing (that is <code>"C:/R/R-3.3.1/bin/Rscript.exe"</code> from <code>C:/Program Files/R/R-3.3.1/bin/Rscript.exe"</code> because <code>Program Files</code> has a space a... | 0 | 2016-06-25T09:05:02Z | [
"python",
"python-2.7",
"python-3.x",
"subprocess"
] |
String index 0 ambiguity | 38,024,680 | <p>Why is <code>''</code> a substring of all strings?</p>
<pre><code>>>> string = 'string'
>>> '' in string
True
</code></pre>
<p>Why is it at index <code>0</code>?</p>
<pre><code>>>> string.index('')
0
</code></pre>
<p>Why is index <code>0</code> ambiguous?</p>
<pre><code>>>> ... | 0 | 2016-06-25T03:35:01Z | 38,024,718 | <p>string.index(substring) returns the index position where substring begins, or -1 if it is not part of the original stirng. </p>
<p>By definition the empty string is a subset of all strings, i.e. all strings begin with the empty string and string.index('') returns 0, the first index of the string. </p>
<p>string[in... | 2 | 2016-06-25T03:42:24Z | [
"python"
] |
String index 0 ambiguity | 38,024,680 | <p>Why is <code>''</code> a substring of all strings?</p>
<pre><code>>>> string = 'string'
>>> '' in string
True
</code></pre>
<p>Why is it at index <code>0</code>?</p>
<pre><code>>>> string.index('')
0
</code></pre>
<p>Why is index <code>0</code> ambiguous?</p>
<pre><code>>>> ... | 0 | 2016-06-25T03:35:01Z | 38,024,754 | <pre><code>>>> string = 'string'
>>> string[0:0] == ''
True
>>> string.index('str')
0
>>> string[string.index('str')] == 'str'
False
</code></pre>
<p>The <a href="https://docs.python.org/2/library/stdtypes.html#str.index" rel="nofollow">documentation</a> says that <code>string.index... | 3 | 2016-06-25T03:47:21Z | [
"python"
] |
Python find if strings are anagram of each other string | 38,024,714 | <p>I am trying to solve the above interview question to check if string are anagram of each other. The implementation is as follows:</p>
<pre><code>NO_OF_CHARS = 256
def areAnagram(str1, str2):
count = [0] * NO_OF_CHARS
i = 0
while (i in str1) and (i in str2):
count[ord(i)]+=1
i += 1
if... | 1 | 2016-06-25T03:41:42Z | 38,024,769 | <p>An easy way to see if strings are comprised of the same characters is to compare them as sorted lists:</p>
<pre><code>def is_anagram(src, trgt):
"""
Determine if trgt is an anagram of src
:param src: (str)
:param trgt: (str)
:returns: (bool) True if trgt is an anagram of src; else False
"""
... | 4 | 2016-06-25T03:51:02Z | [
"python",
"algorithm",
"while-loop"
] |
Python find if strings are anagram of each other string | 38,024,714 | <p>I am trying to solve the above interview question to check if string are anagram of each other. The implementation is as follows:</p>
<pre><code>NO_OF_CHARS = 256
def areAnagram(str1, str2):
count = [0] * NO_OF_CHARS
i = 0
while (i in str1) and (i in str2):
count[ord(i)]+=1
i += 1
if... | 1 | 2016-06-25T03:41:42Z | 38,024,771 | <p>If you want to go for counting the characters, you need to make counts for both strings and compare them</p>
<pre><code>NO_OF_CHARS = 256
def areAnagram(str1, str2):
if len(str1) != len(str2):
return 0
count = [0] * NO_OF_CHARS
for c1,c2 in zip(str1,str2):
count[ord(c1)] +=1
coun... | 2 | 2016-06-25T03:51:29Z | [
"python",
"algorithm",
"while-loop"
] |
Python find if strings are anagram of each other string | 38,024,714 | <p>I am trying to solve the above interview question to check if string are anagram of each other. The implementation is as follows:</p>
<pre><code>NO_OF_CHARS = 256
def areAnagram(str1, str2):
count = [0] * NO_OF_CHARS
i = 0
while (i in str1) and (i in str2):
count[ord(i)]+=1
i += 1
if... | 1 | 2016-06-25T03:41:42Z | 38,025,240 | <p>The canonical way to do this in Python is to use <code>collections.Counter</code>:</p>
<pre><code>from collections import Counter
def areAnagram(str1, str2):
return Counter(str1) == Counter(str2)
</code></pre>
<p>This should take <code>O(N)</code> space and time (where <code>N</code> is <code>max(len(str1), l... | 1 | 2016-06-25T05:15:46Z | [
"python",
"algorithm",
"while-loop"
] |
Python to exe in 1 file | 38,024,935 | <p>So far i have used cx_freeze to convert py to exe but i get many files. Is there a way to get it all into 1 executable? </p>
<p>I have seen that PyinstallerGUI is able to that but it is for python 2.7. Can it be done with python 3.4 as well? </p>
<p>Thank you all.</p>
| 1 | 2016-06-25T04:24:56Z | 38,025,105 | <p>I haven't tried it but, PyInstaller says <a href="https://pythonhosted.org/PyInstaller/operating-mode.html#bundling-to-one-file" rel="nofollow">here</a> it can do that and it supports Python 2.7 and Python 3.3+.</p>
<p>Quoting from the linked page:</p>
<blockquote>
<p><em>PyInstaller</em> can bundle your script ... | 3 | 2016-06-25T04:55:29Z | [
"python",
"exe"
] |
Python to exe in 1 file | 38,024,935 | <p>So far i have used cx_freeze to convert py to exe but i get many files. Is there a way to get it all into 1 executable? </p>
<p>I have seen that PyinstallerGUI is able to that but it is for python 2.7. Can it be done with python 3.4 as well? </p>
<p>Thank you all.</p>
| 1 | 2016-06-25T04:24:56Z | 38,026,380 | <p>Pyinstaller works up to python 3.5. Once you've installed it (type in your terminal <code>pip install pyinstaller</code>), you can do in your terminal:
<code>pyinstaller --onefile script.py</code>
where <code>script.py</code> is the name of script you want to compile into .exe</p>
<p>with <code>--onefile</code> opt... | 1 | 2016-06-25T08:08:06Z | [
"python",
"exe"
] |
Sentiment analysis Python TypeError: expected string or bytes-like object | 38,025,003 | <p>I am doing a sentiment analysis and I want to Add NOT to every word between negation and following punctuation. I am performing the following code: </p>
<pre><code>import re
fin=open("aboveE1.txt",'r', encoding='UTF-8')
transformed = re.sub(r'\b(?:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|c... | 0 | 2016-06-25T04:36:51Z | 38,025,059 | <p><code>re.sub</code> takes in a string, not a file object. Documentation <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">here</a>.</p>
<pre><code>import re
fin=open("aboveE1.txt",'r', encoding='UTF-8')
transformed = ''
for line in fin:
transformed += re.sub(r'\b(?:never|no|nothing... | 0 | 2016-06-25T04:46:07Z | [
"python"
] |
setPricingEngine import pyql | 38,025,037 | <pre><code>european_option = VanillaOption(payoff, exercise)
spot_handle = SimpleQuote(spot_price)
flat_ts = FlatForward(calculation_date, risk_free_rate, day_count)
dividend_yield = FlatForward(calculation_date, dividend_rate, day_count)
flat_vol_ts = BlackConstantVol(calculation_date, cal, volatility, day_count)
b... | 0 | 2016-06-25T04:42:52Z | 38,029,862 | <p>You don't need an additional import. The reason of the error is that the pyql developers have exported some QuantLib with a different name in order to follow <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> and be more idiomatic in Python. The correct call is</p>
<pre><code>european_opti... | 2 | 2016-06-25T15:11:46Z | [
"python",
"quantlib"
] |
django migration - re-creating the database | 38,025,218 | <p>I am running python 2.7 and django 1.8.</p>
<p><a href="http://stackoverflow.com/questions/24983777/cant-add-a-new-field-in-migration-column-does-not-exist">I have this exact issue.</a></p>
<p>The answer, posted as a comment is: <code>What I did is completely remake the db, erase the migration history and folders.... | 0 | 2016-06-25T05:12:48Z | 38,297,213 | <p>Here is what I did to correct this issue:</p>
<p>First, make a script of the data, so that when the database is destroyed and re-created, the data can be easily re-created.</p>
<p>Next run the following script to reset the database (this will delete all the db data and remove the db tables).</p>
<p>Then run the f... | 1 | 2016-07-10T23:04:27Z | [
"python",
"django",
"postgresql",
"django-models",
"django-migrations"
] |
How to merge names with common elements in list? | 38,025,234 | <p>In a list called 'common', I have a bunch of names that have common elements. For instance, my list has these names in it</p>
<pre><code>common = ['Jeremy Paul', 'Paul Stevens', 'John Jordan', 'Jordan Smith',
'Jordan Walker', 'Walker Marshall']
</code></pre>
<p>I want to be able to merge all the names that have c... | 2 | 2016-06-25T05:15:21Z | 38,025,254 | <p>An approach: Split each string up into constituent parts, pair up parts of every item, and check if the first pair ends with the first part of the second pair -- if so insert into a list.</p>
<p>Something like:</p>
<pre><code>>>> common = ['Jeremy Paul', 'Paul Stevens', 'John Jordan', 'Jordan Smith',
...... | 4 | 2016-06-25T05:18:37Z | [
"python",
"regex",
"list",
"loops",
"iteration"
] |
How to merge names with common elements in list? | 38,025,234 | <p>In a list called 'common', I have a bunch of names that have common elements. For instance, my list has these names in it</p>
<pre><code>common = ['Jeremy Paul', 'Paul Stevens', 'John Jordan', 'Jordan Smith',
'Jordan Walker', 'Walker Marshall']
</code></pre>
<p>I want to be able to merge all the names that have c... | 2 | 2016-06-25T05:15:21Z | 38,025,905 | <p>Here is an alternative attempt.</p>
<pre><code>In [6]: b = [i.split() for i in common]
In [7]: [' '.join(x[0])+' '+x[1][-1] for x in [b[n:n+2] for n in range(0, len(b), 2)]]
Out[7]: ['Jeremy Paul Stevens', 'John Jordan Smith', 'Jordan Walker Marshall']
</code></pre>
<p>Concept : Group them in 2 elements and joined... | 0 | 2016-06-25T06:59:45Z | [
"python",
"regex",
"list",
"loops",
"iteration"
] |
Print a 'X' pattern of '*' | 38,025,263 | <p>I'm trying to print this pattern in Python:</p>
<pre><code>* *
* *
* *
*
* *
* *
* *
</code></pre>
<p>And came up with this code:</p>
<pre><code>size = 7
inner_size = size - 3
space=0
for i in range(inner_size):
print (' ' * space + '*' + ' ' * inner_size + '*')
inner_size -=2
s... | 2 | 2016-06-25T05:20:34Z | 38,025,347 | <p>Here's one way to do it:</p>
<pre><code>def pattern(size):
for i in range(size):
print("".join("*" if j == i or size - 1 - j == i else " "
for j in range(size)))
</code></pre>
<p>Details: <code>i</code> is the row index and <code>j</code> is the column index (both zero-based). T... | 3 | 2016-06-25T05:36:03Z | [
"python"
] |
Print a 'X' pattern of '*' | 38,025,263 | <p>I'm trying to print this pattern in Python:</p>
<pre><code>* *
* *
* *
*
* *
* *
* *
</code></pre>
<p>And came up with this code:</p>
<pre><code>size = 7
inner_size = size - 3
space=0
for i in range(inner_size):
print (' ' * space + '*' + ' ' * inner_size + '*')
inner_size -=2
s... | 2 | 2016-06-25T05:20:34Z | 38,025,377 | <p>You asked if it can be done with a '<strong><em>single loop</em>'</strong>. So there ya go:</p>
<pre><code>n = 3
for i in range(-n, n + 1):
print('{}*{}{}'.format(
(n + 1 - abs(i)) * ' ',
(2 * abs(i) - 1) * ' ',
'' if i == 0 else '*'))
</code></pre>
<p>Explanation:</p>
<p>For any given... | 2 | 2016-06-25T05:40:05Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.