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
Extract a number from a string, after a certain character
39,481,788
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p> <pre><code>s = "abcdef,12" v = "gbhjjj,699" </code></pre> <p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p> <p>I tried <code>s[-2:]</code> and <c...
1
2016-09-14T02:53:01Z
39,481,834
<p>Using <code>split</code> is superior because it is very clear and fast:</p> <pre><code>&gt;&gt;&gt; s = "abcdef,12" &gt;&gt;&gt; s.split(',')[1] '12' </code></pre> <p>Another way is with <code>index</code> or <code>find</code>:</p> <pre><code>&gt;&gt;&gt; s = "abcdef,12" &gt;&gt;&gt; s[s.find(',')+1:] '12' </code...
1
2016-09-14T02:58:38Z
[ "python" ]
Extract a number from a string, after a certain character
39,481,788
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p> <pre><code>s = "abcdef,12" v = "gbhjjj,699" </code></pre> <p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p> <p>I tried <code>s[-2:]</code> and <c...
1
2016-09-14T02:53:01Z
39,481,897
<p>Maybe you can try with a <a href="https://docs.python.org/3.5/library/re.html" rel="nofollow">regular expression</a></p> <pre><code>import re input_strings = ["abcdef,12", "gbhjjj,699"] matcher = re.compile("\d+$") for input_string in input_strings: is_matched = matcher.search(input_string) if is_matched...
1
2016-09-14T03:05:55Z
[ "python" ]
Extract a number from a string, after a certain character
39,481,788
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p> <pre><code>s = "abcdef,12" v = "gbhjjj,699" </code></pre> <p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p> <p>I tried <code>s[-2:]</code> and <c...
1
2016-09-14T02:53:01Z
39,482,263
<p>I like <code>.partition()</code> for this kind of thing:</p> <pre><code>for text in ('gbhjjj,699', 'abcdef,12'): x, y, z = text.partition(',') number = int(z) print(number) </code></pre> <p>Unlike <code>.split()</code> it will always return three values.</p> <p>I'll sometimes do this to emphasize t...
1
2016-09-14T03:55:35Z
[ "python" ]
Extract a number from a string, after a certain character
39,481,788
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p> <pre><code>s = "abcdef,12" v = "gbhjjj,699" </code></pre> <p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p> <p>I tried <code>s[-2:]</code> and <c...
1
2016-09-14T02:53:01Z
39,484,260
<p>Assuming:</p> <ul> <li>You <em>know</em> there is a comma in the string, so you don't have to search the entire string to find out if there is or not.</li> <li>You know the pattern is <code>'many_not_digits,few_digits'</code> so there is a big imbalance between the size of the left/right parts either side of the co...
1
2016-09-14T06:59:20Z
[ "python" ]
Extract a number from a string, after a certain character
39,481,788
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p> <pre><code>s = "abcdef,12" v = "gbhjjj,699" </code></pre> <p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p> <p>I tried <code>s[-2:]</code> and <c...
1
2016-09-14T02:53:01Z
39,485,269
<p>If you are worried about using split from the left because of lots of unwanted characters in the beginning, use rsplit.</p> <pre><code>s = "abcdef,12" s.rsplit(",", 1)[-1] </code></pre> <p>Here, rsplit will start splitting the string from the right and the optional second argument we used will stop rsplit to proce...
2
2016-09-14T07:57:04Z
[ "python" ]
Django Model to Associative Array
39,481,796
<p>Is there any way to convert a django models to an associative array using a loop for HttpResponse.</p> <pre><code>class Guest(models.Model): fname = models.CharField(max_length=200) mname = models.CharField(max_length=200, default="", blank=True, null=True) lname = models.CharField(max_length=200) g...
0
2016-09-14T02:53:56Z
39,483,007
<pre><code>guest = Guest.objects.get(pk=1) print guest.__dict__ </code></pre>
0
2016-09-14T05:25:18Z
[ "python", "django" ]
Django Model to Associative Array
39,481,796
<p>Is there any way to convert a django models to an associative array using a loop for HttpResponse.</p> <pre><code>class Guest(models.Model): fname = models.CharField(max_length=200) mname = models.CharField(max_length=200, default="", blank=True, null=True) lname = models.CharField(max_length=200) g...
0
2016-09-14T02:53:56Z
39,483,048
<pre><code>SomeModel.objects.filter(id=pk).values()[0] </code></pre> <p>You will get</p> <pre><code>{ "fname" : "sample", "mname" : "sample", "lname" : "sample", ... } </code></pre> <p>I discourage the using of <code>__dict__</code> because you will get extra fields that you don't care about.</p> <...
1
2016-09-14T05:28:50Z
[ "python", "django" ]
How to find characters ahead of word using re?
39,481,838
<p>So I would like to obtain the number that is ahead of the word pies. How would I do this?</p> <pre><code>import re string='latin 1,394 pies' m = re.search('', string) print(m.group(0)) #want 1,394 </code></pre>
-3
2016-09-14T02:59:02Z
39,481,883
<pre><code>In [137]: import re ...: string='latin 1,394 pies' ...: m = re.search(r'([\d,]+) pies', string) ...: print(m.group(1)) ...: 1,394 ([\d,]+) pies </code></pre> <p><img src="https://www.debuggex.com/i/gXGzdV9i3-VyuTBM.png" alt="Regular expression visualization"></p> <p><a href="https:/...
0
2016-09-14T03:03:48Z
[ "python", "regex" ]
Python: Replacing character error with read in file
39,481,870
<p>Goal: I just want to take the comma away as that is the only character that will screw up my (course required) file parsing for bayesian analysis (i.e word,2,4) instead of say (i.e. word,,2,4)</p> <p>So I'm currently trying to read in an email in the form of a text file from the Enron public corpus online and build...
1
2016-09-14T03:02:54Z
39,486,810
<p>If you just want to remove the extra comma and as you said nothing is working out you can use the simple split and join (assuming comma is the only delimiter here)</p> <pre><code>','.join([s for s in 'word,,2,4'.split(',') if s]) </code></pre>
2
2016-09-14T09:21:09Z
[ "python", "spam", "bayesian" ]
Python: Replacing character error with read in file
39,481,870
<p>Goal: I just want to take the comma away as that is the only character that will screw up my (course required) file parsing for bayesian analysis (i.e word,2,4) instead of say (i.e. word,,2,4)</p> <p>So I'm currently trying to read in an email in the form of a text file from the Enron public corpus online and build...
1
2016-09-14T03:02:54Z
39,537,047
<p>So I ended up using another implementation that I found useful as well. It turns out, for some reason, python retains any prior information it had for any previous strings that were originally present. So i've learned its always a good idea to just re-assign it to a different(new) variable as follows:</p> <pre><cod...
0
2016-09-16T17:23:33Z
[ "python", "spam", "bayesian" ]
In Ansible is there a way to use with_items and host variables at the same time?
39,481,925
<p>So I have 3 hosts I want to run a playbook on. Each host needs 3 files (all with the same names).</p> <p>the files are going to be</p> <ul> <li>lacpbond.100</li> <li>lacpbond.200</li> <li>lacpbond.300</li> </ul> <p>Each file has a unique IP address that goes into it based on the vars/ file.</p> <p>The task look...
1
2016-09-14T03:10:07Z
39,482,320
<p>Your question is a bit unclear (in part because of the issue I pointed out in my comment), but if I understand what you're asking, you can just do something like:</p> <pre><code>IPADDR={{host.SVIS[item.vlan].ipv4}} </code></pre> <p>See the <a href="http://jinja.pocoo.org/docs/dev/templates/#variables" rel="nofollo...
1
2016-09-14T04:04:42Z
[ "python", "ansible", "ansible-playbook" ]
Fixing Negative Assertion for end of string
39,482,021
<p>I am trying to accept a capture group only if the pattern matches and there is not a specific word before the end of the group. I've tried a # of approaches and none seem to work, clearly I'm not getting the concept:</p> <p><a href="https://regex101.com/r/iP2xY0/3" rel="nofollow">https://regex101.com/r/iP2xY0/3</a>...
0
2016-09-14T03:22:36Z
39,494,466
<p>I would recommend putting your negative look-ahead at the beginning of your pattern. This first checks if your reject word exists in your string and only if it isn't there does it try to match the rest of the string:</p> <p><code>(?!.*Rejected.*)RC:\*.*?(?P&lt;Capture&gt;(Bob|David|Ted|Alice)).*</code></p> <p><a h...
0
2016-09-14T15:34:46Z
[ "python", "regex-negation", "regex-lookarounds" ]
How to pass named arguments into python function from hy
39,482,091
<p>I am trying to use a python function with named arguments from hy.</p> <p>I'm using the NLTK library as well.</p> <p>In python I would do something like this</p> <pre><code>from nltk.corpus import brown brown.words(categories='news') </code></pre> <p>to get a list of words in the 'news' category.</p> <p>I would...
0
2016-09-14T03:30:49Z
39,482,128
<p>Found the answer in the docs. </p> <p><a href="http://docs.hylang.org/en/latest/language/api.html#defn" rel="nofollow">defn documentation</a></p> <p>It would be done like this</p> <pre><code>(.words brown :categories "news") </code></pre>
0
2016-09-14T03:37:39Z
[ "python", "hy" ]
Changing image on button click
39,482,273
<p>this is my first python programming code. I am trying to change the image on click of a button. I have 2 buttons, <kbd>Start Conversation</kbd> &amp; <kbd>Stop Conversation</kbd>. </p> <p>When the form loads there is no image. when <em>Start</em> button is clicked, ABC image will be displayed. When the <em>Stop</em...
1
2016-09-14T03:56:58Z
39,483,467
<p>The most important issue is that you do not clear your canvas before the new image is created. Start your (button) functions with:</p> <pre><code>canvas.delete("all") </code></pre> <p>However, the same goes for your canvas; you keep creating it. Better split the creation of the canvas and setting the image:</p> <...
1
2016-09-14T06:04:28Z
[ "python", "python-2.7", "tkinter" ]
Unable to scrape the content though it appears in the inspect element
39,482,313
<p>I have been trying to scrape the user reviews from the cnet page. The pros and cons of the user reviews information. (<a href="http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/" rel="nofollow">http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/</a>)</p> <p>I have used selenium to dynamically loa...
-3
2016-09-14T04:03:02Z
39,487,260
<p>That page has quite a bit of JavaScript so I think using selenium is going to be your best bet to load all of the content. In your current code you are only waiting 2 seconds which may not be enough time. I would recommend using an explicit wait that returns when the comment section elements have completely loaded.<...
0
2016-09-14T09:41:47Z
[ "python", "selenium", "web-scraping" ]
model IntegerField() to django-template with ordinal
39,482,332
<p>I have a model with IntegerField()</p> <pre><code>class Room(models.Model): type = models.CharField(max_length=50) floor = models.IntegerField() </code></pre> <p>And i would like it to display in a template with ordinal suffix.</p> <pre><code>{% for room in rooms %} &lt;div&gt; &lt;p&gt; {{ ro...
-1
2016-09-14T04:06:39Z
39,482,578
<p>You can use <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/humanize/#ordinal" rel="nofollow">ordinal</a> function from django.contrib.humanize package</p>
1
2016-09-14T04:39:43Z
[ "python", "django" ]
How to completely restart a python program
39,482,411
<p>For a project, i used a Raspberry Pi (running dexter industries modified raspbian) and Brick Pi to run lego motors. I wroted a program with python and it works great and all, but i need the entire program to run repeatedly if the pressure sensor was not pressed. I tried calling the function sensorValue() (which dete...
0
2016-09-14T04:17:41Z
39,482,687
<p>try this </p> <pre><code>import BrickPi,time BrickPiSetup() BrickPi.MotorEnable[PORT_A] = 1 BrickPi.SensorType[PORT_4] = TYPE_SENSOR_TOUCH BrickPiSetupSensors() z = 0 def mainprogram(): print ("running") while x == 1: z = z + 1 print ("the plate has been pressed for %s seconds" % z) ...
1
2016-09-14T04:51:17Z
[ "python", "raspberry-pi", "lego" ]
py.test : How do I access a test_function's parameter from within an @pytest.fixture
39,482,428
<p>My objective is to gain access to a test_function's "args" from within a pytest.fixture that lives in conftest.py, in order to pytest.skip() if a certain condition is met.</p> <p>Here is the conftest.py code:</p> <pre class="lang-py prettyprint-override"><code># conftest.py import pytest def pytest_generate_tests...
0
2016-09-14T04:20:28Z
39,482,692
<p>Adding the parameter to the fixture as well as the test function seems to work.</p> <p>Test code:</p> <pre><code>import pytest def pytest_generate_tests(metafunc): if 'param1' in metafunc.fixturenames: metafunc.parametrize("param1", [0, 1, 'a', 3, 4]) @pytest.fixture(autouse=True, scope="function") d...
1
2016-09-14T04:51:54Z
[ "python", "automated-tests", "py.test" ]
Why does pyinstaller generated cx_oracle application work on fresh CentOS machine but not on one with Oracle client installed?
39,482,504
<p>I wrote a python application that uses <code>cx_Oracle</code> and then generates a pyinstaller bundle (folder/single executable). I should note it is on 64 bit linux. I have a custom spec file that includes the Oracle client libraries so everything that is needed is in the bundle. </p> <p>When I run the bundled ...
0
2016-09-14T04:30:16Z
39,503,038
<p>One thing that you may be running into is the fact that if you used the instant client RPMs when you built cx_Oracle an RPATH would have been burned into the shared library. You can examine its contents and change it using the chrpath command. You can use the special path $ORIGIN in the modified RPATH to specify a p...
1
2016-09-15T04:18:09Z
[ "python", "pyinstaller", "cx-oracle" ]
Converting a Text file to JSON format using Python
39,482,614
<p>I am not new to programming but not good at python data structures. I would like to know a way to convert a text file into JSON format using python since I heard using python the task is much easier with a module called <code>import.json</code>.</p> <p>The file looks like </p> <pre><code> Source Target Value ...
0
2016-09-14T04:44:10Z
39,482,884
<p>You can read it as a <code>csv</code> file and convert it into <code>json</code>. But, be careful with spaces as you've used it as separator, the values with spaces should be carefully handled. Otherwise, if possible make the separator <code>,</code> instead of <code>space</code>.</p> <p>the working code for what y...
0
2016-09-14T05:12:35Z
[ "python", "json" ]
Python way to convert argument list to string
39,482,695
<p>I've inherited some Python code that constructs a string from the string arguments passed into <code>__init__</code>:</p> <pre><code>self.full_tag = prefix + number + point + suffix </code></pre> <p>Maybe I'm just over-thinking it but is this the best way to concatenate the arguments? I know it's possible to do so...
2
2016-09-14T04:52:07Z
39,483,084
<p>The documentation recommends <code>join</code> for better performance over <code>+</code>:</p> <blockquote> <p><a href="https://docs.python.org/2/library/stdtypes.html#index-22" rel="nofollow">6. ... For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear conc...
2
2016-09-14T05:32:20Z
[ "python", "python-2.7" ]
Python way to convert argument list to string
39,482,695
<p>I've inherited some Python code that constructs a string from the string arguments passed into <code>__init__</code>:</p> <pre><code>self.full_tag = prefix + number + point + suffix </code></pre> <p>Maybe I'm just over-thinking it but is this the best way to concatenate the arguments? I know it's possible to do so...
2
2016-09-14T04:52:07Z
39,483,180
<p><em>Pythonic</em> way is to follow <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">The Zen of Python</a>, which has several things to say about this case:</p> <ul> <li><p>Beautiful is better than ugly.</p></li> <li><p>Simple is better than complex.</p></li> <li><p>Readability counts.</p></li> </u...
3
2016-09-14T05:41:45Z
[ "python", "python-2.7" ]
How to print DataFrame on single line
39,482,722
<p>With:</p> <pre><code>import pandas as pd df = pd.read_csv('pima-data.csv') print df.head(2) </code></pre> <p>the print is automatically formatted across multiple lines:</p> <pre><code> num_preg glucose_conc diastolic_bp thickness insulin bmi diab_pred \ 0 6 148 72 35...
1
2016-09-14T04:54:27Z
39,482,727
<p>You need set:</p> <pre><code>pd.set_option('expand_frame_repr', False) </code></pre> <p><code>option_context</code> context manager has been exposed through the top-level API, allowing you to execute code with given option values. Option values are restored automatically when you exit the with block:</p> <pre><co...
3
2016-09-14T04:55:13Z
[ "python", "pandas", "dataframe" ]
parse table using beautifulsoup in python
39,482,760
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p> <p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228...
1
2016-09-14T04:58:16Z
39,482,791
<p>If the data is really structured like a table, there's a good chance you can read it into pandas directly with pd.read_table(). Note that it accepts urls in the filepath_or_buffer argument. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html" rel="nofollow">http://pandas.pydata.org/...
1
2016-09-14T05:02:18Z
[ "python", "web-scraping", "beautifulsoup" ]
parse table using beautifulsoup in python
39,482,760
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p> <p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228...
1
2016-09-14T04:58:16Z
39,483,767
<p>There seems to be a pattern. After every 7 tr(s), there is a new line. So, what you can do is keep a counter starting from 1, when it touches 7, append a new line and restart it to 0.</p> <pre><code>counter = 1 for tr in find_all("tr"): for td in tr.find_all("td"): # place code counter = counter + 1...
0
2016-09-14T06:26:40Z
[ "python", "web-scraping", "beautifulsoup" ]
parse table using beautifulsoup in python
39,482,760
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p> <p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228...
1
2016-09-14T04:58:16Z
39,483,922
<pre><code>from __future__ import print_function import re import datetime from bs4 import BeautifulSoup soup = "" with open("/tmp/a.html") as page: soup = BeautifulSoup(page.read(),"html.parser") table = soup.find('div', {'style': 'overflow:auto; border:1px #cccccc solid;'}).find('table') trs = table.find_all('t...
0
2016-09-14T06:37:41Z
[ "python", "web-scraping", "beautifulsoup" ]
parse table using beautifulsoup in python
39,482,760
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p> <p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228...
1
2016-09-14T04:58:16Z
39,484,094
<pre><code>count = 0 string = "" for td in soup.find_all("td"): string += "\""+td.text.strip()+"\"," count +=1 if(count % 9 ==0): print string[:-1] + "\n\n" # string[:-1] to remove the last "," string = "" </code></pre> <p>as the table is not in the proper required format we shall just go with the td rather th...
1
2016-09-14T06:47:34Z
[ "python", "web-scraping", "beautifulsoup" ]
How do I import tables from another database in sqlite using Python?
39,482,796
<p>How do I import data from a column in another table in another database into the current database's table's column? </p> <p>I tried using the "ATTACH" command, but I'm only allowed to execute one statement at a time. </p> <pre><code> cursor.execute( "ATTACH DATABASE other.db AS other;\ INSERT INTO...
0
2016-09-14T05:02:48Z
39,485,832
<p>In place of <code>execute</code> you may want to do an <code>executescript</code>. Like so...</p> <pre><code>cursor.executescript("""ATTACH DATABASE 'other.db' AS other; INSERT INTO table (column1) SELECT column1 FROM other.table;""") </code></...
1
2016-09-14T08:29:27Z
[ "python", "sqlite" ]
How do I import tables from another database in sqlite using Python?
39,482,796
<p>How do I import data from a column in another table in another database into the current database's table's column? </p> <p>I tried using the "ATTACH" command, but I'm only allowed to execute one statement at a time. </p> <pre><code> cursor.execute( "ATTACH DATABASE other.db AS other;\ INSERT INTO...
0
2016-09-14T05:02:48Z
39,486,211
<p>I had to call <code>execute</code> twice, and enclose <code>other.db</code> is single quotations </p> <pre><code> cursor.execute("ATTACH DATABASE 'other.db' AS other;") cursor.execute("\ INSERT INTO table \ (ID) \ SELECT ID \ FROM other.table ;") </code></pre>
0
2016-09-14T08:49:49Z
[ "python", "sqlite" ]
why output list is empty in my code in Python 2.7
39,482,800
<p>Using Python 2.7 and trying to do simple tokenization on UTF-8 encoded files. The output of <code>a</code> seems a byte string, which is expected, since after <code>tk[0].encode('utf-8')</code>, it converts from Python <code>unicode</code> type to <code>str/byte</code>. My major confusion is why output of <code>b</c...
1
2016-09-14T05:03:02Z
39,482,843
<p>It appears that <code>jieba.tokenize()</code> returns a generator. A generator can be iterated over only once. Better do</p> <pre><code> b = [tk[0] for tk in segment_list] a = [tk.encode('utf-8') for tk in b] </code></pre>
1
2016-09-14T05:07:54Z
[ "python", "python-2.7", "unicode" ]
Why is my decimal to binary program returning the value backwards and in a table format?
39,482,836
<p>I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.</p> <pre><code>number = int(input('Enter a number in base 10: ')) base2 = '' while(number &gt; 0): rem = number % 2 number = number // 2 base2 = srt(number) + str(rem) print(rem) #This w...
0
2016-09-14T05:07:03Z
39,482,942
<p>Your code prints the lowest bit of remaining number on separate lines so that's why you see them in reverse order. You could change your code to store bits to an array and then after the loop print them in reverse order:</p> <pre><code>number = int(input('Enter a number in base 10: ')) base2 = [] while(number &gt; ...
0
2016-09-14T05:18:48Z
[ "python", "binary", "decimal", "converter", "data-conversion" ]
Why is my decimal to binary program returning the value backwards and in a table format?
39,482,836
<p>I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.</p> <pre><code>number = int(input('Enter a number in base 10: ')) base2 = '' while(number &gt; 0): rem = number % 2 number = number // 2 base2 = srt(number) + str(rem) print(rem) #This w...
0
2016-09-14T05:07:03Z
39,484,013
<p>Some modifications to your code:</p> <pre><code>number = int(input('Enter a number in base 10: ')) base2 = '' while(number &gt; 0): rem = number % 2 number = number // 2 # can be number //= 2, or number &gt;&gt;= 1 base2 += str(rem) #print(rem) # no need to print print(base2[::-1]) </code></pre> <...
0
2016-09-14T06:43:06Z
[ "python", "binary", "decimal", "converter", "data-conversion" ]
Python - NumPy Array Logical XOR operation byte wise
39,482,865
<p>I am reading an image via Pillow and converting it to a numpy array.</p> <pre><code> A = numpy.asarray(Image.open( ImageNameA).convert("L")) B = numpy.asarray(Image.open( ImageNameB).convert("L")) print A [[255 255 255 ..., 255 255 255] [255 255 255 ..., 255 255 255] [255 2...
1
2016-09-14T05:09:56Z
39,483,395
<p>From the question title, I suppose the function you meant to use is actualy <code>numpy.bitwise_xor</code> it will output arrays in the 0-255 range as you expect. </p> <p><code>logical_xor</code> treats all number above 1 as <code>True</code> and 0 as <code>False</code> and always outputs a boolean array (only 0s a...
2
2016-09-14T05:57:26Z
[ "python", "numpy", "pillow" ]
Is there an equivalent to python reduce() function in scala?
39,482,883
<p>I've just started learning Scala and functional programming and I'm trying to convert the following from Python to Scala:</p> <pre><code>def immutable_iterative_fibonacci(position): if (position ==1): return [1] if (position == 2): return [1,1] next_series = lambda series, _: series +...
3
2016-09-14T05:12:27Z
39,483,031
<p>Summary of Python <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce</code></a>, for reference:</p> <pre><code>reduce(function, iterable[, initializer]) </code></pre> <h2>Traversable</h2> <p>A good type to look at is <a href="http://www.scala-lang.org/api/current/index.h...
9
2016-09-14T05:27:28Z
[ "python", "scala", "lambda", "functional-programming", "reduce" ]
Print leading zeros of a floating point number
39,482,902
<p>I am trying to print something:</p> <pre><code>&gt;&gt;&gt; print "%02i,%02i,%02g" % (3, 4, 5.66) 03,04,5.66 </code></pre> <p>However this is not correct. If you notice, the zeroes get correctly pre-pended to all the integer floating points (the first two numbers). I need it such that there will be one leading ze...
3
2016-09-14T05:14:15Z
39,482,975
<p>Use different format i.e. <code>f</code>:</p> <pre><code>print "%02i,%02i,%05.2f" % (3, 4, 5.66) ^^^^^^ </code></pre> <p>or with <code>g</code>:</p> <pre><code> print "%02i,%02i,%05.3g" % (3, 4, 5.66) ^^^^^^ </code></pre> <p>But I would stick to <code>f</code>. I guess th...
4
2016-09-14T05:22:57Z
[ "python" ]
Print leading zeros of a floating point number
39,482,902
<p>I am trying to print something:</p> <pre><code>&gt;&gt;&gt; print "%02i,%02i,%02g" % (3, 4, 5.66) 03,04,5.66 </code></pre> <p>However this is not correct. If you notice, the zeroes get correctly pre-pended to all the integer floating points (the first two numbers). I need it such that there will be one leading ze...
3
2016-09-14T05:14:15Z
39,482,976
<p>For <code>g</code>, specify and width and precision:</p> <pre><code>&gt;&gt;&gt; print "%02i,%02i,%05.3g" % (3, 4, 5.66) 03,04,05.66 </code></pre> <h3>f versus g</h3> <p>The difference between <code>f</code> and <code>g</code> is illustrated here:</p> <pre><code>&gt;&gt;&gt; print "%07.1f, %07.1f, %07.1f" % (1.2...
5
2016-09-14T05:22:57Z
[ "python" ]
Print leading zeros of a floating point number
39,482,902
<p>I am trying to print something:</p> <pre><code>&gt;&gt;&gt; print "%02i,%02i,%02g" % (3, 4, 5.66) 03,04,5.66 </code></pre> <p>However this is not correct. If you notice, the zeroes get correctly pre-pended to all the integer floating points (the first two numbers). I need it such that there will be one leading ze...
3
2016-09-14T05:14:15Z
39,482,977
<p>The format <code>%02g</code> specifies minimum width of 2. You can use <code>%0m.n</code> syntax where <code>m</code> is the minimum width and <code>n</code> is the number of decimals. What you need is this:</p> <pre><code>&gt;&gt;&gt; print "%02i,%02i,%05.2f" % (3, 4, 5.66) 03,04,05.66 </code></pre>
4
2016-09-14T05:22:58Z
[ "python" ]
Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
39,482,968
<p>So for example</p> <pre><code>['John','John','Mike','Mike','Kate','Kate'] </code></pre> <p>Should return:</p> <pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)] </code></pre> <p>How can I write code so there is order instead of those three pairs just being in random order?</p> <p>I need to sort the list of tupl...
2
2016-09-14T05:21:49Z
39,483,009
<p>This works:</p> <pre><code>&gt;&gt;&gt; names = ['John','John','Mike','Mike','Kate','Kate'] &gt;&gt;&gt; sorted(Counter(names).items(), key=lambda item: (-item[1], item[0])) [('John', 2), ('Kate', 2), ('Mike', 2)] </code></pre> <p>The counter's items will give you tuples of <code>(name, count)</code>. Normally yo...
2
2016-09-14T05:25:24Z
[ "python", "python-3.x" ]
Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
39,482,968
<p>So for example</p> <pre><code>['John','John','Mike','Mike','Kate','Kate'] </code></pre> <p>Should return:</p> <pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)] </code></pre> <p>How can I write code so there is order instead of those three pairs just being in random order?</p> <p>I need to sort the list of tupl...
2
2016-09-14T05:21:49Z
39,483,086
<p>There are two ways to do this. In the first method, a sorted list is returned. In the second method, the list is sorted in-place.</p> <pre><code>import operator # Method 1 a = [('Mike', 2), ('John', 2), ('Kate', 2), ('Arvind', 5)] print(sorted(a, key = lambda x : (x[0],))) # Method 2 a = [('Mike', 2), ('John', 2)...
0
2016-09-14T05:32:28Z
[ "python", "python-3.x" ]
Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
39,482,968
<p>So for example</p> <pre><code>['John','John','Mike','Mike','Kate','Kate'] </code></pre> <p>Should return:</p> <pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)] </code></pre> <p>How can I write code so there is order instead of those three pairs just being in random order?</p> <p>I need to sort the list of tupl...
2
2016-09-14T05:21:49Z
39,483,440
<p>You can sort your result using <code>sorted()</code> function using the <code>key</code> argument to define how to sort the items:</p> <pre><code>result = [('John', 2), ('Kate', 2), ('Mike', 3)] sorted_result = sorted(result, key=lambda x: (-x[1], x[0])) </code></pre> <p>As you want to sort the result in descendin...
2
2016-09-14T06:01:01Z
[ "python", "python-3.x" ]
Django upload limits
39,483,099
<p>I want to make've limited the number of users on the upload file. For example: Every day, users are limited to 1 image file. </p> <p><strong>Views</strong></p> <pre><code>class Upload(views.LoginRequiredMixin, generic.CreateView): model = Posts form_class = UploadForm template_name = 'icerik_yukle.html' def form...
0
2016-09-14T05:33:26Z
39,483,176
<p>Check if exists a record for the current day and if it has a valid picture for the user. If there is, raise an exception</p> <pre><code>def form_valid(self, form): from datetime import datetime query = Gonderi.objects.filter(created__date=datetime.now().date(), author=requ...
2
2016-09-14T05:41:38Z
[ "python", "django" ]
How to get only word for selected tag in NLTK Part of Speech (POS) tagging?
39,483,108
<p>Sorry I am new to Pandas and NLTK. I'm trying to build set of customize returned POS. My data contents:</p> <pre><code> comment 0 [(have, VERB), (you, PRON), (pahae, VERB)] 1 [(radio, NOUN), (television, NOUN), (lid, NOUN)] 2 [(yes, ADV), (you're, ADJ)] 3 [(ooi, ADJ), (work, NOUN), (b...
2
2016-09-14T05:34:24Z
39,483,414
<p>You can use <code>list comprehension</code> and then replace empty <code>list</code> to <code>[NaN]</code>:</p> <pre><code>df = pd.DataFrame({'comment': [ [('have', 'VERB'), ('you', 'PRON'), ('pahae', 'VERB')], [('radio', 'NOUN'), ('television', 'NOUN'), ('lid', 'NOUN')], [('yes', 'ADV'), ("...
1
2016-09-14T05:58:51Z
[ "python", "list", "pandas", "tuples", "nltk" ]
How to get only word for selected tag in NLTK Part of Speech (POS) tagging?
39,483,108
<p>Sorry I am new to Pandas and NLTK. I'm trying to build set of customize returned POS. My data contents:</p> <pre><code> comment 0 [(have, VERB), (you, PRON), (pahae, VERB)] 1 [(radio, NOUN), (television, NOUN), (lid, NOUN)] 2 [(yes, ADV), (you're, ADJ)] 3 [(ooi, ADJ), (work, NOUN), (b...
2
2016-09-14T05:34:24Z
39,483,488
<h3>Setup reference</h3> <pre><code>s = pd.Series([ [('have', 'VERB'), ('you', 'PRON'), ('pahae', 'VERB')], [('radio', 'NOUN'), ('television', 'NOUN'), ('lid', 'NOUN')], [('yes', 'ADV'), ("you're", 'ADJ')], [('ooi', 'ADJ'), ('work', 'NOUN'), ('barisan', 'ADJ')], [('national', 'A...
1
2016-09-14T06:05:41Z
[ "python", "list", "pandas", "tuples", "nltk" ]
PyQt window closes after opening
39,483,114
<p>I have two files, namely <em>main.py</em> and <em>client_window.py</em>. I want to show the client window after the progress bar completes its progress. But I find that the client window opens and closes immediately. Can someone suggest how to change the code, so that I'll grasp the correct logic?</p> <p>This is <e...
0
2016-09-14T05:35:28Z
39,516,110
<p>You need to keep a reference to the client window, otherwise it will be garbage-collected as soon as <code>onProgress</code> returns:</p> <pre><code>def onProgress(self, i): self.progressBar.setValue(i) if self.progressBar.value() == 100: self.client_window = client_window.main() else: s...
0
2016-09-15T16:31:55Z
[ "python", "qt", "python-3.x", "pyqt", "pyqt4" ]
"sqlalchemy.exc.InvalidRequestError Entity '<class ''>' has no property ... " exception after updating database
39,483,136
<p>I am trying to update row in SQLite table by id. </p> <p>I have class</p> <pre><code>class newTestCaseData(Base): __tablename__ = 'test_cases' __table_args__ = {"useexisting": True} failure_datails = Column('failure_details', String) exec_status = Column('exec_status', String) execution_durat...
1
2016-09-14T05:38:10Z
39,492,593
<p>There is spelling mistake in the "failure_datails"</p>
0
2016-09-14T14:09:33Z
[ "python", "sqlite", "sqlalchemy" ]
How to get the edge object data of a vertex in orient db using python
39,483,354
<pre><code>import pyorient # create connection client = pyorient.OrientDB("localhost", 2424) # open databse client.db_open( "Apple", "admin", "admin" ) requiredObj = client.command(' select from chat where app_cat=appCategory and module=module and type=type and prob_cat=problemCategory ') print requiredObj[0] <...
0
2016-09-14T05:54:02Z
39,484,619
<p>You could use </p> <pre><code>requiredObj = client.command(' select expand(out()[0]) from chat where app_cat=appCategory and module=module and type=type and prob_cat=problemCategory ') print(requiredObj[0]) </code></pre> <p>Hope it helps</p>
0
2016-09-14T07:19:18Z
[ "python", "orientdb" ]
Why MATLAB/Numpy/Scipy performance is slow and doesn't reach CPU capabilities (flops)?
39,483,409
<p>First of all, I know there are multiple threads that touch this issue, however I could not get a straight answer and encountered some flops miscalculations.</p> <p>I have prepared a MATLAB and Python benchmark of element-wise multiplication. This is the simplest and most forward way one can easily calculate the flo...
1
2016-09-14T05:58:38Z
39,496,508
<p>Well, in this case you're being limited by memory bandwidth, not CPU power. Assuming:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/DDR3_SDRAM#JEDEC_standard_modules" rel="nofollow">PC3-12800 RAM</a> in dual channel mode; </li> <li>for every multiplication (single precision) 12 bytes need to be transferred be...
2
2016-09-14T17:36:18Z
[ "python", "performance", "matlab", "numpy", "scipy" ]
How to access pandas multiindex by element within a nested dict?
39,483,417
<p>I have a dict of types of regions, within each a dict of sub-regions, and within each of those a pandas dataframe object, indexed to the period from which I need to compute each parameter (column) time series. Additionally, I need it in two units.</p> <p>So I created something like this:</p> <pre><code>regions = ...
1
2016-09-14T05:59:06Z
39,483,830
<p>specify both index and column in <code>loc</code><br> Try</p> <pre><code>for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end): for region in regions: for sub_region in sub_regions: for parameter in parameters: for unit in units: unit_af = np.rando...
2
2016-09-14T06:31:05Z
[ "python", "pandas", "dictionary", "multi-index" ]
How to make dtype converter function in Pandas?
39,483,427
<p>I would like to make functions and pass pipe or apply method in <code>pandas</code> to avoid recursive assignment and for practice.</p> <p>Here is my example dataframe.</p> <pre><code>A 0 1 1 2 2 3 3 4 </code></pre> <p>And I defined my converter function,to pass pipe method.</p> <pre><code>def converter(df,cols,...
1
2016-09-14T05:59:57Z
39,483,474
<p>You need add <code>[]</code> for select columns:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3,4]}) print (df) A 0 1 1 2 2 3 3 4 def converter(df,cols,types): df[cols]=df[cols].astype(types) return df print (converter(df, 'A', float)) A 0 1.0 1 2.0 2 3.0 3 4.0 </code></pre>
1
2016-09-14T06:04:46Z
[ "python", "pandas", "indexing", "dataframe", "casting" ]
get_dummies split character
39,483,546
<p>I have data labelled which I need to apply one-hot-encoding: <code>'786.2'</code>, <code>'ICD-9-CM|786.2'</code>, <code>'ICD-9-CM'</code>, <code>'786.2b|V13.02'</code>, <code>'V13.02'</code>, <code>'279.12'</code>, <code>'ICD-9-CM|V42.81'</code> is labels. The <code>|</code> mean that the document have 2 labels at t...
2
2016-09-14T06:10:17Z
39,483,690
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> and then select first item...
4
2016-09-14T06:20:28Z
[ "python", "pandas", "one-hot-encoding" ]
How do I fix plotting my boxplot?
39,483,639
<p>I am trying to plot my boxplot but I am getting a 'nonetype attribute error.' </p> <p>Please, how can I fix this? </p> <p>My Code:</p> <pre><code>Failed = train_df['Fees'][train_df['Passedornot'] == 0] Passed = train_df['Fees'][train_df['Passedornot'] ==1] average_fees = DataFrame([mean(Passed), mean(Failed)]) ...
1
2016-09-14T06:16:50Z
39,484,737
<p>Not sure what happens there, but I think your <code>average_fees</code> is not a proper pandas dataframe. Furthermore, my compiler is complaining about <code>kind='bp'</code>. That is one of the reasons why the community always asks for a fully functional working example.</p> <p>Here is a working snippet for Python...
0
2016-09-14T07:26:17Z
[ "python", "dataframe" ]
Is using type as dictionary keys considered good practice in Python?
39,483,667
<p>I have a lookup table like this:</p> <pre><code>lookup = { "&lt;class 'Minority.mixin'&gt;": report_minority, "&lt;class 'Majority.mixin'&gt;": report_majority, } def report(o): h = lookup[str(type(o))] h() </code></pre> <p>It looks awkward to me as the <code>key</code> is precariously linked to how <code...
0
2016-09-14T06:19:09Z
39,484,819
<p>Take a look at that script, I don't think it's perfect but it works and I think it's more elegant than your solution :</p> <pre><code>#!/usr/bin/env python3 class Person: pass def display_person(): print("Person !") class Car: pass def display_car(): print("Car !") lookup = { Person: displa...
0
2016-09-14T07:31:10Z
[ "python", "python-3.x", "dictionary" ]
Is using type as dictionary keys considered good practice in Python?
39,483,667
<p>I have a lookup table like this:</p> <pre><code>lookup = { "&lt;class 'Minority.mixin'&gt;": report_minority, "&lt;class 'Majority.mixin'&gt;": report_majority, } def report(o): h = lookup[str(type(o))] h() </code></pre> <p>It looks awkward to me as the <code>key</code> is precariously linked to how <code...
0
2016-09-14T06:19:09Z
39,487,963
<p>Just remove the <code>str</code> from the lookup and from the dictionary. So</p> <pre><code>lookup = { Minority.mixin : report_minority, Majority.mixin : report_majority, } def report(o): h = lookup[type(o)] h() </code></pre> <p>This fixes your immediate concern and is fairly reasonable code. Howev...
1
2016-09-14T10:18:44Z
[ "python", "python-3.x", "dictionary" ]
Is using type as dictionary keys considered good practice in Python?
39,483,667
<p>I have a lookup table like this:</p> <pre><code>lookup = { "&lt;class 'Minority.mixin'&gt;": report_minority, "&lt;class 'Majority.mixin'&gt;": report_majority, } def report(o): h = lookup[str(type(o))] h() </code></pre> <p>It looks awkward to me as the <code>key</code> is precariously linked to how <code...
0
2016-09-14T06:19:09Z
39,488,179
<p>The question would more be <em>why are you doing this in the first place</em>? What advantage do <em>you</em> think using strings has?</p> <p>Class objects are hashable, so you can use <code>Minority.mixin</code> and <code>Majority.mixin</code> <em>directly</em> as keys. And when you do so, you ensure that the key ...
2
2016-09-14T10:30:27Z
[ "python", "python-3.x", "dictionary" ]
How to improve performance of pymongo queries
39,483,692
<p>I inherited an old Mongo database. Let's focus on the following two collections <em>(removed most of their content for better readability)</em>:</p> <p>Collection user</p> <pre><code>db.user.find_one({"email": "[email protected]"}) {'lastUpdate': datetime.datetime(2016, 9, 2, 11, 40, 13, 160000), 'creationTime': dat...
0
2016-09-14T06:20:40Z
39,485,092
<p>Instead of running two aggregates for all users separately you can just get both aggregates for all users with <a href="http://api.mongodb.com/python/current/examples/aggregation.html" rel="nofollow"><code>db.collection.aggregate()</code></a>.</p> <p>And instead of a <code>(email, userId)</code> tuples we make it a...
1
2016-09-14T07:46:23Z
[ "python", "mongodb", "python-3.x", "pymongo", "pymongo-3.x" ]
How to write numpy arrays to .txt file, starting at a certain line?
39,483,774
<p>I need to write 3 numpy arrays into a txt file. The head of the file looks like that:</p> <pre><code>#Filexy #time operation1 operation2 </code></pre> <p>The numpy arrays look like the following:</p> <pre><code>time = np.array([0,60,120,180,...]) operation1 = np.array([12,23,68,26,...)] operation2 = np.array([10...
5
2016-09-14T06:27:06Z
39,483,844
<p>Try this:</p> <pre><code>f = open(name_of_the_file, "a") np.savetxt(f, data, newline='\n') f.close() </code></pre>
0
2016-09-14T06:32:28Z
[ "python", "numpy", "writetofile" ]
How to write numpy arrays to .txt file, starting at a certain line?
39,483,774
<p>I need to write 3 numpy arrays into a txt file. The head of the file looks like that:</p> <pre><code>#Filexy #time operation1 operation2 </code></pre> <p>The numpy arrays look like the following:</p> <pre><code>time = np.array([0,60,120,180,...]) operation1 = np.array([12,23,68,26,...)] operation2 = np.array([10...
5
2016-09-14T06:27:06Z
39,483,874
<p>I'm not sure what you tried, but you need to use the <code>header</code> parameter in <code>np.savetxt</code>. Also, you need to concatenate your arrays properly. The easiest way to do this is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html" rel="nofollow"><code>np.c_</code></a>, wh...
4
2016-09-14T06:34:11Z
[ "python", "numpy", "writetofile" ]
Python: Acessing each frame within a while loop
39,483,882
<p>In Psychopy/Python: within a while loop, I need to read in some information (using pyserial) and append it to a list on every frame. </p> <pre><code>t = trialClock.getTime() while True: line = ser.readline() #read in line if line: lines.append(line) #append to list ... </code></pre> <p>Ho...
0
2016-09-14T06:35:03Z
39,484,026
<p>You need to have a:</p> <pre><code>win.flip() </code></pre> <p>at the end of your code within the while loop so that the loop only iterates once per frame refresh. i.e. the code pauses at that point until the screen is actually redrawn, limiting your loop to 60 Hz (assuming your screen refreshes at that rate).</p>...
0
2016-09-14T06:44:07Z
[ "python", "psychopy" ]
MATLAB sort() vs Numpy argsort() - how to match results?
39,484,073
<p>I'm porting a MATLAB code to Python's Numpy.</p> <p>In MATLAB (Octave, actually), I have something like:</p> <pre><code>&gt;&gt; someArr = [9, 8, 7, 7] &gt;&gt; [~, ans] = sort(someArr, 'descend') ans = 1 2 3 4 </code></pre> <p>So in Numpy I'm doing:</p> <pre><code>&gt;&gt;&gt; someArr = np.array([9,...
1
2016-09-14T06:46:17Z
39,484,418
<p>You can choose between different sorting algorithms. Changing it to <code>heapsort</code> worked for me:</p> <pre><code>&gt;&gt; np.argsort(someArr, kind="heapsort")[::-1] array([0, 1, 2, 3], dtype=int32) </code></pre> <p>Edit: This only works for a few test cases I looked at. For <code>[9, 8, 7, 7, 4, 1, 1]</code...
0
2016-09-14T07:08:46Z
[ "python", "matlab", "sorting", "numpy" ]
MATLAB sort() vs Numpy argsort() - how to match results?
39,484,073
<p>I'm porting a MATLAB code to Python's Numpy.</p> <p>In MATLAB (Octave, actually), I have something like:</p> <pre><code>&gt;&gt; someArr = [9, 8, 7, 7] &gt;&gt; [~, ans] = sort(someArr, 'descend') ans = 1 2 3 4 </code></pre> <p>So in Numpy I'm doing:</p> <pre><code>&gt;&gt;&gt; someArr = np.array([9,...
1
2016-09-14T06:46:17Z
39,484,419
<p>In order to make this work, we need to be a little bit clever. <code>numpy</code> doesn't have the <code>'descend'</code> analog. You're mimicking it by reversing the results of the sort (which is ultimately you're undoing).</p> <p>I'm not sure how <code>matlab</code> accomplishes it, but they claim to use a <a h...
3
2016-09-14T07:08:46Z
[ "python", "matlab", "sorting", "numpy" ]
setting distances between (labels, values)
39,484,247
<p>I have to mention that I am a beginner by dealing with data frames, and I am grateful for any tips :)</p> <p>I have a dataframe contains names of files and their sizes (~8000 records). I am trying to figure out which bunch of files can be deleted or moved. so I tried to plot names vs. size.</p> <p><strong>the pro...
0
2016-09-14T06:58:12Z
39,486,130
<p>As I said in the comments, I don't think a graph is the best way to do this. I would start by simplifying the dataframe to get the average size of each file:</p> <pre><code>average_size = df.groupby('files')['size'].mean() </code></pre> <p>You can then get the top 10 files (for instance) with:</p> <pre><code>aver...
2
2016-09-14T08:45:38Z
[ "python", "database", "pandas", "seaborn" ]
Python - How to sum all combinations of a list of numbers in order to reach a goal. Use of number is optional
39,484,255
<p>I have a list of numbers</p> <pre><code>lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68] </code></pre> <p>that I would like to sum in various ways in order to try and reach the goal number of 8276. I also need to see whether throwing away the cents or rounding helps reaching the goal. Note that use of a nu...
1
2016-09-14T06:58:50Z
39,484,348
<p>You're trying to sum all the combinations with given length instead of calculating a sum of a single combination. Instead you should loop over the combinations and check the sum for each one:</p> <pre><code>from itertools import combinations lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68] for i in xrange(1...
3
2016-09-14T07:04:25Z
[ "python", "sum", "combinations", "permutation" ]
Python - How to sum all combinations of a list of numbers in order to reach a goal. Use of number is optional
39,484,255
<p>I have a list of numbers</p> <pre><code>lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68] </code></pre> <p>that I would like to sum in various ways in order to try and reach the goal number of 8276. I also need to see whether throwing away the cents or rounding helps reaching the goal. Note that use of a nu...
1
2016-09-14T06:58:50Z
39,485,563
<p>Since you mention:</p> <blockquote> <p>I also need to see whether throwing away the cents or rounding helps reaching the goal. </p> </blockquote> <p>..the code below will show the closest n- combinations, and the absolute difference they show to the targeted number. </p> <p>Works on both <code>python3</code>and...
1
2016-09-14T08:13:51Z
[ "python", "sum", "combinations", "permutation" ]
Python - How to sum all combinations of a list of numbers in order to reach a goal. Use of number is optional
39,484,255
<p>I have a list of numbers</p> <pre><code>lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68] </code></pre> <p>that I would like to sum in various ways in order to try and reach the goal number of 8276. I also need to see whether throwing away the cents or rounding helps reaching the goal. Note that use of a nu...
1
2016-09-14T06:58:50Z
39,507,297
<p>Here is a solution if you want to consider the cases where you can throw away the cents, or you can round to the nearest whole number. This requirement turned a simple solution to a pretty complicated one. In order to account for the above requirement, I expanded each number to include the additional possible cases....
0
2016-09-15T09:17:22Z
[ "python", "sum", "combinations", "permutation" ]
Matrices addition in numpy
39,484,262
<p>I need to calculate the sum of a list of matrices, however, I can't use <code>np.sum</code>, even with <code>axis=0</code>, I don't know why. The current solution is a loop, but is there a better way for that? </p> <pre><code>import numpy as np SAMPLE_SIZES = [10, 100, 1000, 10000] ITERATIONS = 1 MEAN = np.array([1...
1
2016-09-14T06:59:23Z
39,494,065
<p>If you just want to compute the empirical covariance then I would suggest using <code>numpy.cov(xs.T)</code>. </p> <p>Otherwise, the last 3 lines can be replaced by:</p> <pre><code>xm = xs - np.mean(xs, axis=0) sigma = np.inner(xm.T. xm.T) / (sample_size-1) </code></pre>
0
2016-09-14T15:15:02Z
[ "python", "numpy" ]
Matrices addition in numpy
39,484,262
<p>I need to calculate the sum of a list of matrices, however, I can't use <code>np.sum</code>, even with <code>axis=0</code>, I don't know why. The current solution is a loop, but is there a better way for that? </p> <pre><code>import numpy as np SAMPLE_SIZES = [10, 100, 1000, 10000] ITERATIONS = 1 MEAN = np.array([1...
1
2016-09-14T06:59:23Z
39,496,912
<p>Read up about numpy <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a>.</p> <pre><code>xs = np.random.multivariate_normal(MEAN, COVARIANCE, size=sample_size) </code></pre> <p><code>xs</code> now has shape <code>(sample_size, 2)</code>, which means you can just ...
3
2016-09-14T18:04:09Z
[ "python", "numpy" ]
Why does spark-submit in YARN cluster mode not find python packages on executors?
39,484,389
<p>I am running a <code>boo.py</code> script on AWS EMR using <code>spark-submit</code> (Spark 2.0).</p> <p>The file finished successfully when I use</p> <pre><code>python boo.py </code></pre> <p>However, it failed when I run</p> <pre><code>spark-submit --verbose --deploy-mode cluster --master yarn boo.py </code><...
3
2016-09-14T07:06:38Z
39,484,684
<p>When you are running spark, part of the code is running on the driver, and part is running on the executors.</p> <p>Did you install boto3 on the driver only, or on driver + all executors (nodes) which might run your code?</p> <p>One solution might be - to install boto3 on all executors (nodes)</p> <p><strong>how ...
2
2016-09-14T07:23:07Z
[ "python", "apache-spark", "pyspark" ]
CSV file creation error in python
39,484,395
<p>I am getting some error while writing contents to csv file in python</p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf8') import csv a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']] f3 = open('test_'+...
0
2016-09-14T07:06:52Z
39,484,546
<p>You have error message - just read it. The file test_1/1/2013_.csv doesn't exist.</p> <p>In the file name that you create - you use a[0][0] and in this case it result in 1/1/2013. Probably this two signs '/' makes that you are looking for this file in bad directory. Check where are this file (current directory - or...
1
2016-09-14T07:15:58Z
[ "python", "csv" ]
CSV file creation error in python
39,484,395
<p>I am getting some error while writing contents to csv file in python</p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf8') import csv a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']] f3 = open('test_'+...
0
2016-09-14T07:06:52Z
39,484,788
<p>It's probably due to the directory not existing - Python will create the file for you if it doesn't exist already, but it won't automatically create directories.</p> <p>To ensure the path to a file exists you can combine <a href="https://docs.python.org/3/library/os.html#os.makedirs" rel="nofollow">os.makedirs</a> ...
0
2016-09-14T07:29:02Z
[ "python", "csv" ]
Python csv reader multi-character quotechar?
39,484,436
<p>I am dealing with Concordance loadfiles and have to edit them and thus I am using Python for that. The columns are delimited by the pilcrow char <code>¶</code> and have <code>þ</code> as the quotechar.</p> <p>The problem is the quotechar, the csv module in python only accepts a single-char quote (there is no issu...
0
2016-09-14T07:09:28Z
39,484,696
<p>The Concordance file format is 8-bit encoded, and the <code>¶</code> and <code>þ</code> characters are encoded in Latin-1, really. That means they are encoded to binary values 0xB6 and 0xFE, respectively.</p> <p>The Python 2 <code>csv</code> module accepts those bytes quite happily:</p> <pre><code>csv.reader(fil...
2
2016-09-14T07:23:54Z
[ "python", "csv" ]
are set of strings all substrings of another set
39,484,571
<p>I have many sets of strings and wish to test them against sets of substrings. I wish to identify which sets contain all of the substrings.</p> <pre><code>set1 = {'A123', 'B234', 'C345'} set2 = {'A123', 'F234', 'H345'} substring_set1 = {'A', 'B'} </code></pre> <p>So something like this in pseudocode:</p> <pre><cod...
0
2016-09-14T07:16:57Z
39,485,276
<p>The following approach looks clean enough to me:</p> <pre><code>&gt;&gt;&gt; all(any(x in v for v in set1) for x in substring_set1) True &gt;&gt;&gt; all(any(x in v for v in set2) for x in substring_set1) False </code></pre>
3
2016-09-14T07:57:21Z
[ "python", "python-3.x" ]
How to assign data array to a variable whos name is stored within another array?
39,484,712
<p>I have a series of loops set-up which each create an array of arrays, and where the sub-array contains two variable names and two data arrays.</p> <p>For example:</p> <pre><code>r1_radial_ZZ = np.array([ ["cCoh_AB", "Var_AB", trA_z.data, trB_z.data], ["cCoh_AC", "Var_AC", trA_z.data, ...
0
2016-09-14T07:24:44Z
39,503,306
<p>The answer was to use the variable names in <code>first_array</code> to generate keys in an empty dictionary to which I could assign the data generated by the <code>calculation()</code> function:</p> <pre><code>def calculation(x, y): x2 = 2*x y2 = 2*y return "double", x2, y2 def dict_example(): ...
0
2016-09-15T04:48:50Z
[ "python", "numpy" ]
how to connect to page and check a word exist in page
39,484,812
<p>i want connect to a site by <code>urllib2</code> in every 5 second and get all html after this i want check a word is in page or not </p> <p>for example i want connect to <a href="http://google.com" rel="nofollow">google</a> every 5 second and check google is in page or not</p> <p>i try this code :</p> <pre><cod...
-3
2016-09-14T07:30:42Z
39,484,852
<p>your code have error </p> <p>change your code to this :</p> <pre><code>import urllib2 import time while true: values = urllib2.urlopen("http://google.com").read() if "google" in values: print("google is in my address") else: print("google not in my address") time.sleep(5) </code></...
1
2016-09-14T07:32:48Z
[ "python" ]
UTF-8 and colour printing woes…
39,484,912
<p>I have a console program that outputs in wonderful colour. For errors, the following code is used with some trivial examples at the bottom.</p> <pre><code># coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_liter...
0
2016-09-14T07:36:37Z
39,485,140
<p>The <a href="http://docs.python.org/library/stdtypes.html#str.encode" rel="nofollow">encode()</a> takes an optional argument defining the error handling:</p> <pre><code>str.encode([encoding[, errors]]) </code></pre> <p>From the docs:</p> <blockquote> <p>Return an encoded version of the string. Default encoding ...
1
2016-09-14T07:49:21Z
[ "python", "python-2.7", "utf-8" ]
How to pass *args or **kwargs itself to the target function of threading.Target?
39,484,973
<p>A function accepts <code>*args</code> and <code>**kwargs</code>:</p> <pre><code>def b(num, *args, **kwargs): print('num', num) print('args', args) print('kwargs', kwargs) </code></pre> <p>calling it as <code>b(5, *[1, 2], **{'a': 'b'})</code> produces the following output:</p> <pre><code>num 5 args (1...
-1
2016-09-14T07:39:50Z
39,484,974
<pre><code>threading.Thread(target=b, args=[5, 1, 2], kwargs={'a': 'b'}).start() </code></pre> <p>gives the expected output. Another option is to use functools. The following code also passes arguments correctly:</p> <pre><code>threading.Thread(target=functools.partial(b, 5, *[1, 2], **{'a': 'b'})).start() </code></p...
1
2016-09-14T07:39:50Z
[ "python", "python-multithreading" ]
Python won't break from a while True
39,485,007
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p> <pre><code>from random import randint import sys value = int(randint(1,10)) lives = int(5) userinp = int(0) if lives == 0: print("no lives :("...
-3
2016-09-14T07:41:36Z
39,485,041
<p>You have to break the <code>while</code> when <code>lives == 0</code>, either by a <code>break</code> or by changing the while condition.</p>
0
2016-09-14T07:43:35Z
[ "python" ]
Python won't break from a while True
39,485,007
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p> <pre><code>from random import randint import sys value = int(randint(1,10)) lives = int(5) userinp = int(0) if lives == 0: print("no lives :("...
-3
2016-09-14T07:41:36Z
39,485,066
<p>A <code>while True</code> is an infinite loop, consuming 100% of all CPU cycles and will never break - since a <code>while &lt;condition&gt;</code> only ends when the condition becomes <code>False</code>, but that can never be, because it is always <code>True</code>!</p> <p>Try not fighting the nature of your loop:...
1
2016-09-14T07:45:07Z
[ "python" ]
Python won't break from a while True
39,485,007
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p> <pre><code>from random import randint import sys value = int(randint(1,10)) lives = int(5) userinp = int(0) if lives == 0: print("no lives :("...
-3
2016-09-14T07:41:36Z
39,485,121
<p>Your loop essentially looks like:</p> <pre><code>while True: if lives != 0: # do stuff with lives </code></pre> <p>This is an infinite loop. The loop wont break even if <code>lives == 0</code>, because this condition is tested as part of the loop block, not as the loop condition. You should simply do :...
2
2016-09-14T07:48:18Z
[ "python" ]
Python won't break from a while True
39,485,007
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p> <pre><code>from random import randint import sys value = int(randint(1,10)) lives = int(5) userinp = int(0) if lives == 0: print("no lives :("...
-3
2016-09-14T07:41:36Z
39,486,128
<p>This is my solution, you can set the <code>break</code> condition specifically to end your while loop if a specific event occurs.</p> <pre><code>while lives &gt; 0: print(value) print("You currently have: ", lives, " lives left") userinp = input("Please enter a number from 1 to 10: ") if int(userinp...
0
2016-09-14T08:45:36Z
[ "python" ]
Python GeoIP2 AddressNotFoundError
39,485,054
<p>Im trying to use Python GeoIP to convert IP address to Geo details using Maxmind Database.</p> <pre><code>import urllib2 import csv import geoip2.database db = geoip2.database.Reader("GeoLite2-City.mmdb") target_url="http://myip/all.txt" data = urllib2.urlopen(target_url) for line in data: response = db.cit...
0
2016-09-14T07:44:24Z
39,487,501
<p>The problem here is the exception happening in db.city call, not in values printing, so you could try this:</p> <pre><code>import urllib2 import csv import geoip2.database db = geoip2.database.Reader("GeoLite2-City.mmdb") target_url="http://myip/all.txt" data = urllib2.urlopen(target_url) for line in data: try:...
1
2016-09-14T09:54:30Z
[ "python", "exception", "exception-handling", "geoip", "maxmind" ]
Python square brackets between function name and arguments: func[...](...)
39,485,083
<p>I was learning how to accelerate python computations on GPU from <a href="https://nbviewer.jupyter.org/gist/harrism/f5707335f40af9463c43" rel="nofollow">this notebook</a>, where one line confuses me:</p> <pre><code>mandel_kernel[griddim, blockdim](-2.0, 1.0, -1.0, 1.0, d_image, 20) </code></pre> <p>Here, <code>man...
4
2016-09-14T07:46:00Z
39,486,357
<p>This is valid python syntax, i'll try to break it down for you:</p> <p><code>mandel_kernel</code> is a dict, whose keys are 2-tuples (griddim, blockdim) and values are method (which is valid since methods are objects in python)</p> <p><code>mandel_kernel[griddim, blockdim]</code> therefore 'returns' (or evaluates ...
5
2016-09-14T08:56:49Z
[ "python", "python-decorators", "numba", "numba-pro" ]
Python CGI Script "Cannot allocate memory" Import Error
39,485,160
<p>I have a simple CGI script on a shared 64bit Ubuntu hosting environment.</p> <pre><code>#!/kunden/homepages/14/d156645139/htdocs/htdocs/anaconda2/bin/python # -*- coding: UTF-8 -*- import sys import cgi import cgitb cgitb.enable() import numpy from pandas_datareader.yahoo.daily import YahooDailyReader </code></pre...
0
2016-09-14T07:50:20Z
39,543,359
<p>I was able to increase the RAM of the machine to a guaranteed 2GB which solved the problem.</p>
0
2016-09-17T05:59:11Z
[ "python", "pandas" ]
Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors
39,485,178
<p>What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be inte...
7
2016-09-14T07:51:00Z
39,485,650
<p>Here's a super short solution using the <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.interpolation.zoom.html" rel="nofollow">zoom function</a> from <code>scipy.ndimage</code>. I define a 2x2 RGB image with the intial colors (here random ones) and simply zoom it to 256x256, <code>...
4
2016-09-14T08:18:54Z
[ "python", "numpy", "image-processing" ]
Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors
39,485,178
<p>What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be inte...
7
2016-09-14T07:51:00Z
39,486,574
<p>Here's a very short way to do it with <strong>ImageMagick</strong> which is installed on most Linux distros and is available for OSX and Windows. There are also Python bindings. Anyway, just at the command line, create a 2x2 square with the colours at the 4 corners of your image, then let ImageMagick expand and inte...
2
2016-09-14T09:09:08Z
[ "python", "numpy", "image-processing" ]
Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors
39,485,178
<p>What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be inte...
7
2016-09-14T07:51:00Z
39,515,362
<p>Here are 3 ways to do this bilinear interpolation. The first version does all the arithmetic in pure Python, the second uses <a href="https://python-pillow.org/" rel="nofollow">PIL</a> image composition, the third uses Numpy to do the arithmetic. As expected, the pure Python is significantly slower than the other ap...
2
2016-09-15T15:49:59Z
[ "python", "numpy", "image-processing" ]
How can I test a form with FileField in Django?
39,485,189
<p>I have this form:</p> <pre><code># forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['book_title', 'language', 'author', 'release_year', 'genre', 'ages', 'cover'] </code></pre> <p><strong>Type of fields:</strong> Where <code>book_title</code> and <code>author</code>...
0
2016-09-14T07:51:36Z
39,485,485
<p>Either you create a file in your repository, so it is there physically, or you mock your test for your file.</p> <p>Try <a href="https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html" rel="nofollow">THIS</a> </p> <hr> <p><strong>EDIT</strong></p> <p>Try to pass full path </p> <pre><cod...
0
2016-09-14T08:09:04Z
[ "python", "django", "python-3.x", "django-forms", "django-testing" ]
How can I test a form with FileField in Django?
39,485,189
<p>I have this form:</p> <pre><code># forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['book_title', 'language', 'author', 'release_year', 'genre', 'ages', 'cover'] </code></pre> <p><strong>Type of fields:</strong> Where <code>book_title</code> and <code>author</code>...
0
2016-09-14T07:51:36Z
39,489,599
<p><strong>I find the problem</strong> This is my code:</p> <pre><code>#test_forms.py from .. import forms from django.core.files.uploadedfile import SimpleUploadedFile import os TEST_DIR = os.path.dirname(os.path.abspath(__file__)) TEST_DATA_DIR = os.path.join(TEST_DIR, 'data') class TestBookForm: def test_for...
0
2016-09-14T11:44:35Z
[ "python", "django", "python-3.x", "django-forms", "django-testing" ]
Better way to write so many values in files Python (Lack of memory in a device)
39,485,365
<p>I have a question about file output in Python. I was designing a software that reads values from 3 sensors. Each sensors read 100 values for 1 second, and between each process, I have to print them in file. </p> <pre><code>time_memory = [k + i/100 for i in range(100)] # dividing 1 second into 100 intervals x = [1...
1
2016-09-14T08:02:33Z
39,485,513
<p>One suggestion would be to write the data in binary mode. This should be faster than the text mode (it also needs less space). Therefore you have to open a file in binary mode like this:</p> <pre><code>f = open('filename.data', 'wb') </code></pre>
-1
2016-09-14T08:10:05Z
[ "python", "file", "data-acquisition" ]
Calling from the same class, why is one treated as bound method while the other plain function?
39,485,440
<p>I have the following code snippet in Python 3:</p> <pre><code>from sqlalchemy.ext.declarative import declared_attr from sqlalchemy import Column, Integer, String, Unicode, UnicodeText from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method import arrow datetimeString_format = { "UTC": "%Y-%m-%d %H:%M...
0
2016-09-14T08:06:38Z
39,487,502
<p>What you have is not a regular <code>property</code> here, you have a <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html" rel="nofollow">SQLAlchemy <code>@hybrid_property</code> object</a>. Quoting the documentation there:</p> <blockquote> <p>“hybrid” means the attribute has distinct beh...
1
2016-09-14T09:54:30Z
[ "python", "function", "python-3.x", "methods", "sqlalchemy" ]
Django Tutorial 1 - ImportError: No module named apps
39,485,505
<p>I am following this Tutorial: <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial02/" rel="nofollow">https://docs.djangoproject.com/en/1.10/intro/tutorial02/</a></p> <p>In subsection <em>"Activating models"</em> i should add some code in the </p> <blockquote> <p>mysite/settings.py</p> </blockquote> <...
1
2016-09-14T08:09:49Z
39,485,750
<p>You're using a newer version of Django, who doesn't create the app.py configuration file in the folder because the old structure is different. You've two options:</p> <p>1) Change the documentation version to 1.8</p> <p>2) [RECOMMENDED] use the latest version of Django</p>
3
2016-09-14T08:24:30Z
[ "python", "django" ]
Failed to find HDF5 dataset data - Single Label Regression Using Caffe and HDF5 data
39,485,515
<p>I was using @shai 's code for creating my hdf5 file which is available here: </p> <p><a href="http://stackoverflow.com/questions/31774953/test-labels-for-regression-caffe-float-not-allowed/31808324#31808324">Test labels for regression caffe, float not allowed?</a></p> <p>My data is grayscale images (1000 images fo...
0
2016-09-14T08:10:41Z
39,503,530
<p>I solved the problem making following changes to the code:</p> <pre><code>H.create_dataset( 'data', data=X ) # note the name X given to the dataset! Replaced X by data H.create_dataset( 'label', data=y ) # note the name y given to the dataset! Replaced y by label </code></pre> <p>The error was gone.</p> <p>I'm st...
0
2016-09-15T05:11:07Z
[ "python", "regression", "caffe", "hdf5" ]
Python: urllib2.URLError: <urlopen error [Errno 10060]
39,485,564
<p>I have some problem with reading some urls.</p> <p>I try to use answer from this question <a href="http://stackoverflow.com/questions/5620263/using-an-http-proxy-python">Using an HTTP PROXY - Python </a> but it didn't help and I get an error <code>urllib2.URLError: &lt;urlopen error [Errno 10060]</code></p> <p>I h...
0
2016-09-14T08:13:56Z
39,486,250
<p>Some of proxies didn't work. And I use <code>urllib</code> instead <code>urllib2</code> and </p> <pre><code>for url in urls: proxies = {'http': 'http://109.172.106.3:9999', 'http': 'http://62.113.208.183:3128', 'http': 'http://178.22.148.122:3129', 'http': 'http://217.17.46.162:3128'} url = 'http://www.' + ...
0
2016-09-14T08:51:46Z
[ "python", "urllib2" ]
Reverse characters of string in subset of 3
39,485,624
<p>Let say my string is as:</p> <pre><code>x = 'abcdefghi' </code></pre> <p>I want to reverse it in subsets of 3, so that my output is:</p> <pre><code>x = 'cbafedihg' </code></pre> <p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p> <p>Below is my code based on converting the <c...
0
2016-09-14T08:17:17Z
39,485,639
<p>The above code can be written using <code>string slicing</code> and <code>list comprehension</code> as:</p> <pre><code># Here x[i*3:i*3+3][::-1] will reverse the substring of 3 chars &gt;&gt;&gt; ''.join([x[i*3:i*3+3][::-1] for i in range(len(x)/3)]) 'cbafedihg' </code></pre> <p>Based on the comment by <a href="ht...
6
2016-09-14T08:17:58Z
[ "python", "string", "python-2.7" ]
Reverse characters of string in subset of 3
39,485,624
<p>Let say my string is as:</p> <pre><code>x = 'abcdefghi' </code></pre> <p>I want to reverse it in subsets of 3, so that my output is:</p> <pre><code>x = 'cbafedihg' </code></pre> <p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p> <p>Below is my code based on converting the <c...
0
2016-09-14T08:17:17Z
39,486,323
<p>Simply swap the elements of list with step as 3:</p> <pre><code>&gt;&gt;&gt; string_list = list(x) &gt;&gt;&gt; string_list[::3], string_list[2::3] = string_list[2::3], string_list[::3] &gt;&gt;&gt; ''.join(string_list) 'cbafedihg' </code></pre>
1
2016-09-14T08:55:17Z
[ "python", "string", "python-2.7" ]
Reverse characters of string in subset of 3
39,485,624
<p>Let say my string is as:</p> <pre><code>x = 'abcdefghi' </code></pre> <p>I want to reverse it in subsets of 3, so that my output is:</p> <pre><code>x = 'cbafedihg' </code></pre> <p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p> <p>Below is my code based on converting the <c...
0
2016-09-14T08:17:17Z
39,486,947
<p>Writing a function that is more readable and flexible?</p> <pre><code>def get_string(input_str, step=3): output = "" i = 0 for _ in list(input_str): if i == len(input_str): return output elif i+step-1 &gt;= len(input_str): output += input[len(input_str)-1:i-1:-1] ...
0
2016-09-14T09:27:23Z
[ "python", "string", "python-2.7" ]
How to create a loop from this code?
39,485,625
<p>I have a python routine which puts PDF pages in booklet spread order. I'm trying to improve the code: there's a bit where I'm doing almost the same thing twice. When I write out the iteration, it works, but when I try to make it more general with more loops, it doesn't. The code puts two PDF pages onto a larger PDF ...
0
2016-09-14T08:17:22Z
39,488,897
<p>This now works. I have no idea what has changed.</p> <p>Many thanks for looking at it.</p>
0
2016-09-14T11:06:33Z
[ "python", "logic" ]
split cell to rows by pipe python
39,485,728
<p>I am trying to split a cell into 2 rows by pipe ("|").</p> <p>For instance:</p> <pre><code>ID Site Category Queries 1 0 38037 antique+wall+telephone|antique+wall+phone </code></pre> <p>will become:</p> <pre><code>ID Site Category Queries 1 0 38037 antique+wall+telephon...
2
2016-09-14T08:23:21Z
39,485,857
<p>You can use .split()</p> <pre><code>input = "antique+wall+telephone|antique+wall+phone" output = input.split('|') </code></pre> <p>output will be a list of elements either side of the '|'</p> <p>so output would be</p> <pre><code>("antique+wall+telephone", "antique+wall+phone") </code></pre> <p>and then you can ...
0
2016-09-14T08:31:15Z
[ "python" ]
split cell to rows by pipe python
39,485,728
<p>I am trying to split a cell into 2 rows by pipe ("|").</p> <p>For instance:</p> <pre><code>ID Site Category Queries 1 0 38037 antique+wall+telephone|antique+wall+phone </code></pre> <p>will become:</p> <pre><code>ID Site Category Queries 1 0 38037 antique+wall+telephon...
2
2016-09-14T08:23:21Z
39,485,928
<p>Here's one way:</p> <pre><code>&gt;&gt;&gt; id, site, category, queries ('1', '0', '38037', 'antique+wall+telephone|antique+wall+phone') &gt;&gt;&gt; for query in queries.split('|'): ... print id, site, category, query ... 1 0 38037 antique+wall+telephone 1 0 38037 antique+wall+phone </code></pre>
2
2016-09-14T08:34:40Z
[ "python" ]
split cell to rows by pipe python
39,485,728
<p>I am trying to split a cell into 2 rows by pipe ("|").</p> <p>For instance:</p> <pre><code>ID Site Category Queries 1 0 38037 antique+wall+telephone|antique+wall+phone </code></pre> <p>will become:</p> <pre><code>ID Site Category Queries 1 0 38037 antique+wall+telephon...
2
2016-09-14T08:23:21Z
39,489,374
<p>Using talend, You can also use tNormalize component : you just have to specify the column to normalize in the dropdown menu. Be careful if you want to use "|" as the item separator, as it is a reserved character, you have to escape it using "\|". <a href="http://i.stack.imgur.com/IuYbI.png" rel="nofollow"><img src="...
0
2016-09-14T11:32:48Z
[ "python" ]
python running coverage on never ending process
39,485,731
<p>I have a multi processed web server with processes that never end, I would like to check my code coverage on the whole project in a live environment (not only from tests).</p> <p>The problem is, that since the processes never end, I don't have a good place to set the <code>cov.start() cov.stop() cov.save()</code> h...
4
2016-09-14T08:23:37Z
39,488,674
<p>Since you are willing to run your code differently for the test, why not add a way to end the process for the test? That seems like it will be simpler than trying to hack coverage.</p>
0
2016-09-14T10:55:34Z
[ "python", "multithreading", "python-multiprocessing", "coverage.py" ]