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
Python | NumPy | Coordinates - An issue with conversion of geographical coordinates
37,562,165
<p>I have a pretty simple issue: I need to convert the file with geographical coordinates like </p> <pre><code>Lat Long 50 0 50 35 1 40 50 2 50 35 10 20 50 3 1 35 13 22 50 2 38 35 14 40 49 59 6 35 13 22 49 57 14 35 13 21 49 57 10 35 13 0 49 57 0 35 6 20 </code></pre> <p>to the <...
2
2016-06-01T07:29:54Z
37,563,346
<p>If I understand correctly what you have in <code>data</code> array,</p> <pre><code>data = data.T # not strictly necessary, but simplifies following indexing lat = data[0]+data[1]/60.+data[2]/3600. lon = data[3]+data[4]/60.+data[5]/3600. converted = np.vstack((lat,lon)).T np.savetxt(outname, converted) </code></p...
2
2016-06-01T08:29:47Z
[ "python", "numpy", "coordinates", "coordinate-systems", "coordinate-transformation" ]
Getting list of keywords from JSON
37,562,230
<p>I have encountered a problem and I don't understand why it printed out this way.</p> <p>Below is my code, please forgive me for the bad formatting as I am new to programming, this is to open a text file which has a bunch of keywords</p> <pre><code>import urllib2 import json f1 = open('CatList.text') lines = f1.re...
0
2016-06-01T07:33:50Z
37,562,612
<p>Friend, Generally '\n' is used for new line . Same sense , In a file there is hidden '\n' character between each lines. </p> <p>So at <strong>lines = f1.readlines()</strong> it includes '\n' in end of all lines. This is the problem.</p> <p>To avoid this, you should read as <strong>f1.read.splitlines()</strong> . <...
2
2016-06-01T07:52:16Z
[ "python", "json", "python-2.7", "urllib2" ]
Getting list of keywords from JSON
37,562,230
<p>I have encountered a problem and I don't understand why it printed out this way.</p> <p>Below is my code, please forgive me for the bad formatting as I am new to programming, this is to open a text file which has a bunch of keywords</p> <pre><code>import urllib2 import json f1 = open('CatList.text') lines = f1.re...
0
2016-06-01T07:33:50Z
37,562,717
<p>Update the following line </p> <pre><code>url ='https://en.wikipedia.org/w/api.php?action=query&amp;format=json&amp;list=categorymembers&amp;cmtitle='+line+'&amp;cmlimit=100' </code></pre> <p>to</p> <pre><code>url ='https://en.wikipedia.org/w/api.php?action=query&amp;format=json&amp;list=categorymembers&amp;cm...
1
2016-06-01T07:57:05Z
[ "python", "json", "python-2.7", "urllib2" ]
Using Python Interactive as a Programming Calculator
37,562,332
<p>I have used <a href="http://www.analogx.com/contents/download/Programming/pcalc/Freeware.htm" rel="nofollow">AnalogX PCalc</a> for years as my go to calculator for back of the envelope interactive calculations where integer math is important and flexible base input and output is important. For example, when working ...
0
2016-06-01T07:39:37Z
37,566,448
<p>Python standard library provides <code>code</code> and <code>codeop</code> modules so the functionality of REPL can be used in other programs as well.</p> <p>For example here is a sample Python file, extending the standard library classes to provide a new interactive console that converts integer results to other b...
1
2016-06-01T10:45:29Z
[ "python", "math", "numerical" ]
How to return the whole list from a python function
37,562,334
<p>I have a small script as follows:</p> <pre><code>import boto3 ACCESS_KEY= "XXXXXXXXXXXXX" SECRET_KEY= "XXXXXXXXXXXX" regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1'] for region in regions: client = boto3.client('ec2',aws_access_key_id=ACCES...
0
2016-06-01T07:39:48Z
37,562,408
<p>You return your <code>all_EIP</code> in the first iteration of the nested for loop. Indent the return so it gets executed after the outer for and you should have all of what is supposed to get appended.</p> <pre><code>def gather_public_ip(): ACCESS_KEY = config.get('aws','access_key') SECRET_KEY = config.get(...
3
2016-06-01T07:43:25Z
[ "python", "boto3" ]
Locating IP v4 packets in binary data from stdin
37,562,370
<p>I would like to be able to read data from stdin and scan the data for 0x45 which is the start of my IP header. But I can't seem to get my head around how I could identify the start of the IP header! My attempt is as follows, and i belive the problem is in how I read the data and that either the binary data needs to ...
0
2016-06-01T07:41:38Z
37,562,979
<p>It seems you are comparing hex with decimal. You are looking for <code>45</code> I think and compare with <code>0x45</code>.</p> <pre><code>&gt;&gt; print(0x45) 69 </code></pre> <p>So to find the correct part you should compare with something like this</p> <pre><code>for line in sys.stdin: if "45" in line: ...
0
2016-06-01T08:09:59Z
[ "python", "binary", "ip", "stdin" ]
Django - json response allowing for json[i][j] reference rather than json[0].field.field_name
37,562,391
<p>I have Django view returning JSON to JS. </p> <pre><code>def some_view(request, param): my_queryset = SomeModel.objects.filter(...).select_related('related_model') serialized_data = serializers.serialize( "json", [x.some_related_field for x in my_queryset]) return HttpResponse(serialized_data, content_t...
0
2016-06-01T07:42:48Z
37,562,752
<p>The serialized output format depends on the serializer you're using.</p> <p>If you're running Django 1.7+, you can return a <a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects" rel="nofollow">JsonResponse</a> (with <code>safe=False</code>) instead of a <code>HttpResponse</code>...
2
2016-06-01T07:59:03Z
[ "javascript", "python", "json", "django" ]
Pandas union on two columns of set
37,562,559
<p>I have two columns in a data frame containing sets.</p> <p>How do I get a new column where each row contains the union of the items from the respective columns?</p> <p>For example:</p> <pre><code>col1 : [{1,2} , {4,5}] col2 : [{1,6} , {7,5}] union : [{1,2,6}, {4,5,7}] </code></pre> <p>A naive try:</p> <pre><cod...
2
2016-06-01T07:50:18Z
37,562,777
<p>I think you are very close - use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> with <code>axis=1</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame([[{1,2} , {1,6}], [{4,5} , {7,5}]], columns=['col1', 'col2']) df['union'...
1
2016-06-01T08:00:17Z
[ "python", "pandas", "set" ]
string permutation. storing in an array returns same set of permutations?
37,562,571
<p><strong>UPDATED:see below line</strong> Unless I am missing something?</p> <pre><code>from array import array def string_permute(ar, lo, hi, result): if lo == hi: # print ar # this gives correct permutated output, howcome result isn't able to store that? result.append(ar) else: for ...
2
2016-06-01T07:50:44Z
37,562,842
<p>You did not make a copy for array object. So therefore, each time you try to modify the array, it changes for every function call.</p> <p>When you do recursive call each time, make a copy for array object.</p> <pre><code>import copy string_permute(copy.copy(ar), lo+1, hi, result) </code></pre>
3
2016-06-01T08:03:13Z
[ "python" ]
string permutation. storing in an array returns same set of permutations?
37,562,571
<p><strong>UPDATED:see below line</strong> Unless I am missing something?</p> <pre><code>from array import array def string_permute(ar, lo, hi, result): if lo == hi: # print ar # this gives correct permutated output, howcome result isn't able to store that? result.append(ar) else: for ...
2
2016-06-01T07:50:44Z
37,562,877
<p>You are modifying <code>ar</code> inplace, so you end up with <code>result</code> containing multiple copies of same object. Changing <code>result.append(ar)</code> to <code>result.append(ar[:])</code> in <code>string_permute</code> solves the problem. </p>
2
2016-06-01T08:05:32Z
[ "python" ]
Error in `make -j4` in opencv3.1 python ubuntu gnome 16.04
37,562,642
<pre><code> [ 41%] Building CXX object modules/dpm/CMakeFiles/opencv_dpm.dir/src/dpm_feature.cpp.o [ 41%] Building CXX object modules/bioinspired/CMakeFiles/opencv_bioinspired.dir/src/retinacolor.cpp.o [ 41%] Building CXX object modules/ts/CMakeFiles/opencv_ts.dir/src/ocl_test.cpp.o [ 41%] Building CXX o...
1
2016-06-01T07:53:12Z
37,566,817
<p>Guys i had no idea what was wrong but I followed the following steps after getting the error above:</p> <pre><code>sudo apt-get install libopencv-contrib-dev sudo apt-get update &amp;&amp; sudo apt-get upgrade make clean cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES...
1
2016-06-01T11:02:41Z
[ "python", "opencv3.1" ]
Ansible: How to get a registered variable into a python script
37,562,753
<p>I have a simple Ansible playbook that uses the raw module to list the installed choco packages on my windows clients. It looks like this:</p> <pre><code>- name: Get info hosts: win_clones tasks: - name: Get packages list installed on clients ... raw: choco list -lo register: result0 - debug:...
0
2016-06-01T07:59:07Z
37,563,037
<p>You might be able to make a <a href="http://docs.ansible.com/ansible/developing_plugins.html#callbacks" rel="nofollow">callback plugin</a> which extracts the value of interest and saves that to a file you can read back later.</p> <p>Here is an example <a href="https://github.com/ansible/ansible/blob/devel/lib/ansib...
0
2016-06-01T08:12:49Z
[ "python", "json", "ansible" ]
Stop endless while True loop
37,562,769
<p>The following program causes an endless loop. How do I stop the while from continuing once I've read in all the links? Thank you. </p> <pre><code>def findAllURLs(): with open('manylinks.html', 'r') as f: data = f.read() start = data.find('href') while(True): begin = data.fin...
-1
2016-06-01T07:59:51Z
37,562,943
<p>You should modify your code this way :</p> <pre><code>def findAllURLs(): with open('manylinks.html', 'r') as f: data = f.read() start = data.find('href') while(start != -1): begin = data.find('"',start) end = data.find('"',begin+1) print data[begin+1:...
1
2016-06-01T08:08:14Z
[ "python", "python-2.7" ]
Stop endless while True loop
37,562,769
<p>The following program causes an endless loop. How do I stop the while from continuing once I've read in all the links? Thank you. </p> <pre><code>def findAllURLs(): with open('manylinks.html', 'r') as f: data = f.read() start = data.find('href') while(True): begin = data.fin...
-1
2016-06-01T07:59:51Z
37,563,373
<p>There is no need to use a <code>while</code> loop, provided that you are using proper tools to parse HTML. I recommend that you use the <a href="https://pypi.python.org/pypi/beautifulsoup4" rel="nofollow">BeautifulSoup 4</a> library to parse the document:</p> <pre><code>import bs4 def find_all_urls(): with...
2
2016-06-01T08:30:48Z
[ "python", "python-2.7" ]
Deny access to imported module in a module
37,563,026
<p>I have a module in my code called <code>a.py</code> which looks a bit like this:</p> <pre><code>import sqlite3 from sqlite3 import * """The point of importing twice in a different way is to have a.py imported by someone and have all the sqlite3 functions (with some overriden by a.py) but a.py still needs access to ...
0
2016-06-01T08:12:21Z
37,563,309
<p>I'm afraid that you can't! Check here for more details: <a href="http://stackoverflow.com/a/1547163/1548838">http://stackoverflow.com/a/1547163/1548838</a></p> <p>But you still can use <code>import sqlite3 as _sqlite3</code> and use it later like <code>_sqlite3.connect</code>. This will tell your module users (conv...
1
2016-06-01T08:28:07Z
[ "python" ]
Deny access to imported module in a module
37,563,026
<p>I have a module in my code called <code>a.py</code> which looks a bit like this:</p> <pre><code>import sqlite3 from sqlite3 import * """The point of importing twice in a different way is to have a.py imported by someone and have all the sqlite3 functions (with some overriden by a.py) but a.py still needs access to ...
0
2016-06-01T08:12:21Z
37,563,529
<p>What about this? Depending on the goal, it's sometimes possible to hide names inside functions / lambdas.</p> <pre><code>def connect(database): #overriding sqlite3's connect() import sqlite3 print "It worked!" return sqlite3.connect(database) </code></pre> <p>But anyway, I don't think trying to hide modul...
0
2016-06-01T08:38:23Z
[ "python" ]
Spark sum columns from different dataframes
37,563,049
<p>We have two dataframes (note Scala syntax for illustrating),</p> <pre><code>val df1 = sc.parallelize(1 to 4).map(i =&gt; (i,i*10)).toDF("id","x") val df2 = sc.parallelize(2 to 4).map(i =&gt; (i,i*100)).toDF("id","y") </code></pre> <p>How to sum up one column from each frame so that we obtain this new dataframe,<...
0
2016-06-01T08:13:53Z
37,563,320
<pre><code>df3 = df1.join(df2, df1.id == df2.id, "left_outer").select(df1.id, df1.x, df2.y).fillna(0) df3.select("id", (df3.x + df3.y).alias("x_plus_y")).show() </code></pre> <p>This works in Python.</p>
2
2016-06-01T08:28:40Z
[ "python", "scala", "apache-spark", "spark-dataframe" ]
Spark sum columns from different dataframes
37,563,049
<p>We have two dataframes (note Scala syntax for illustrating),</p> <pre><code>val df1 = sc.parallelize(1 to 4).map(i =&gt; (i,i*10)).toDF("id","x") val df2 = sc.parallelize(2 to 4).map(i =&gt; (i,i*100)).toDF("id","y") </code></pre> <p>How to sum up one column from each frame so that we obtain this new dataframe,<...
0
2016-06-01T08:13:53Z
37,564,958
<p>In Scala noticed this solution,</p> <pre><code>val d = sqlContext.sql(""" select df1.id, x, y from df1 left join df2 on df1.id=df2.id""").na.fill(0) </code></pre> <p>to join the frames and replace non available values with zeroes, and then define this UDF,</p> <pre><code>import org.apache.spark.sql.functions im...
0
2016-06-01T09:40:37Z
[ "python", "scala", "apache-spark", "spark-dataframe" ]
Spark sum columns from different dataframes
37,563,049
<p>We have two dataframes (note Scala syntax for illustrating),</p> <pre><code>val df1 = sc.parallelize(1 to 4).map(i =&gt; (i,i*10)).toDF("id","x") val df2 = sc.parallelize(2 to 4).map(i =&gt; (i,i*100)).toDF("id","y") </code></pre> <p>How to sum up one column from each frame so that we obtain this new dataframe,<...
0
2016-06-01T08:13:53Z
37,569,499
<p>You don't even need to use an UDF for that :</p> <pre><code>val df3 = df1.as('a).join(df2.as('b), $"a.id" === $"b.id","left"). select(df1("id"),'x,'y,(coalesce('x, lit(0)) + coalesce('y, lit(0))).alias("x_plus_y")).na.fill(0) df3.show // df3: org.apache.spark.sql.DataFrame = [id: int, x: int, y: int...
1
2016-06-01T13:01:51Z
[ "python", "scala", "apache-spark", "spark-dataframe" ]
MD5 hash With ftplib
37,563,260
<pre><code>&gt;&gt;&gt;import ftplib &gt;&gt;&gt;import hashlib &gt;&gt;&gt;ftp = ftplib.FTP('localhost','username','password') &gt;&gt;&gt;ftp.cwd('Server') '250 Directory successfully changed.' &gt;&gt;&gt;m=hashlib.md5() &gt;&gt;&gt; file = open('Desktop/space.png','rb') &gt;&gt;&gt; m.update("space.png") &gt;&gt;...
0
2016-06-01T08:25:47Z
37,564,045
<p>MD5 of <code>"space.png"</code> will always be <code>f646cdee237bd84e33485eb03c9228ac</code>. You don't explain what you're trying to do exactly. If you're trying to use unique filenames which are MD5 hashes, you can try something like this.</p> <pre><code>import uuid m.update(str(uuid.uuid4())) dd = m.hexdigest() ...
1
2016-06-01T09:01:50Z
[ "python", "python-2.7", "hash", "md5", "ftplib" ]
Static instance variables in python
37,563,356
<p>I am trying to learn about static variables in python. According to <a href="http://stackoverflow.com/questions/68645/static-class-variables-in-python/#answer-27568860">this</a> answer this piece of code should make <code>i</code> unique for all the objects of class <code>Test</code></p> <p>The code:</p> <pre><cod...
2
2016-06-01T08:30:13Z
37,563,653
<p>As noted, the <a href="http://stackoverflow.com/questions/68645/static-class-variables-in-python/#answer-27568860">linked answer</a> gets it wrong.</p> <pre><code>class Test(object): i = 0 t = Test() t.i = 4 print t.i &gt;&gt;&gt; 4 print t.__class__.i &gt;&gt;&gt; 0 </code></pre> <p>Fields declared on the <...
1
2016-06-01T08:43:53Z
[ "python" ]
Static instance variables in python
37,563,356
<p>I am trying to learn about static variables in python. According to <a href="http://stackoverflow.com/questions/68645/static-class-variables-in-python/#answer-27568860">this</a> answer this piece of code should make <code>i</code> unique for all the objects of class <code>Test</code></p> <p>The code:</p> <pre><cod...
2
2016-06-01T08:30:13Z
37,563,756
<pre><code>class Test(object): _i = 3 @property def i(self): return self._i @i.setter def i(self,val): self._i = val if __name__ == '__main__': x1 = Test() x2 = Test() x1.i = 10 print(x1.__dict__) print(Test.__dict__) {'_i': 10} {'i': &lt;property object a...
0
2016-06-01T08:48:28Z
[ "python" ]
Python pip version conflict while installing a package
37,563,363
<p>I'm trying to install <code>python-novaclient==2,22</code> package with pip but every time I try I get this error:</p> <pre><code>Installing collected packages: pbr, positional, keystoneauth1, python-keystoneclient Found existing installation: pbr 1.10.0 Uninstalling pbr-1.10.0: Successfully uninstalled...
0
2016-06-01T08:30:30Z
37,563,493
<p>Guess you use python2, recommend you use conda:</p> <p><code>conda create --name env1 python=2.7</code> and use <code>conda install yourlib</code> really convenient.</p>
0
2016-06-01T08:37:07Z
[ "python", "pip", "openstack-nova" ]
Deleting py.test tmpdir directory after successful test case
37,563,396
<p>I'm running tests that create a lot of large files during execution. For this purpose I would like to delete the tmpdir directory if a test has passed. But if a test fails the contents of tmpdir should be left unchanged.</p> <p>I know how to determine the result of the test:</p> <pre><code>from _pytest.runner impo...
0
2016-06-01T08:32:00Z
37,563,591
<p>You should <a href="https://pytest.org/latest/tmpdir.html" rel="nofollow">create a tmpdir fixture</a> that creates the tempdir, passes it into your code and afterwards deletes it.</p> <p>Additionally, the fixture must be set to always delete the tempdir, even on failure. Otherwise you may leave behind an unclean st...
1
2016-06-01T08:41:00Z
[ "python", "py.test" ]
Deleting py.test tmpdir directory after successful test case
37,563,396
<p>I'm running tests that create a lot of large files during execution. For this purpose I would like to delete the tmpdir directory if a test has passed. But if a test fails the contents of tmpdir should be left unchanged.</p> <p>I know how to determine the result of the test:</p> <pre><code>from _pytest.runner impo...
0
2016-06-01T08:32:00Z
38,100,500
<p>you can retrieve easily your tmpdir from <em>funcargs</em> of your actual item.</p> <p>In your case:</p> <pre><code>from _pytest.runner import runtestprotocol def pytest_runtest_protocol(item, nextitem): reports = runtestprotocol(item, nextitem=nextitem) for report in reports: if report.when == 'c...
0
2016-06-29T13:06:40Z
[ "python", "py.test" ]
Element is not currently visible and so may not be interacted with Firefox and Python
37,563,504
<p>Hi all I am trying to write a script to mimic clicking on a website. However, I face this error: </p> <blockquote> <p>Traceback (most recent call last): File "D:/YetLin/testbb.py", line 44, in yearselect.select_by_value("2") File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", ...
2
2016-06-01T08:37:46Z
37,563,670
<p>I've had the same problem before. The fact is that the select element is hidden, in fact the class is hidden-field. The selenium driver cannot see it.</p>
0
2016-06-01T08:44:52Z
[ "javascript", "python", "selenium" ]
Element is not currently visible and so may not be interacted with Firefox and Python
37,563,504
<p>Hi all I am trying to write a script to mimic clicking on a website. However, I face this error: </p> <blockquote> <p>Traceback (most recent call last): File "D:/YetLin/testbb.py", line 44, in yearselect.select_by_value("2") File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", ...
2
2016-06-01T08:37:46Z
37,581,900
<p>Managed to get it :) posting my answers here if anyone might need it.</p> <p>What I did was to use the search text box to get the option that I wanted.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-...
1
2016-06-02T02:58:29Z
[ "javascript", "python", "selenium" ]
Area intersection in Python
37,563,526
<p>I have a code that takes a condition C as an input, and computes the solution to my problem as an 'allowed area' A on the (x,y) space. This area is made of several 'tubes', which are defined by 2 lines that can never cross.</p> <p>The final result I'm looking for must satisfy k conditions {C1, .., Ck}, and is ther...
4
2016-06-01T08:38:20Z
37,581,271
<p>Problem solved with Shapely! </p> <p>I defined each tube as a <code>Polygon</code>, and an area A is a <code>MultiPolygon</code> object built as the union of its tubes. </p> <p>The <code>intersection</code> method then computes the solution I was looking for (the overlap between all areas). </p> <p>The whole thin...
2
2016-06-02T01:28:54Z
[ "python", "numpy", "matplotlib", "intersection", "area" ]
Run a single method in a TestCase class
37,563,664
<pre><code>class TestVehicle(TestCase): def test_speed(self): #checks for speed def test_fuel(self): #checks fuel quantity </code></pre> <p>I have the above test class with two test methods, but while testing I want to run <em>only one</em> of the two methods. How can I achieve this using </p...
0
2016-06-01T08:44:37Z
37,564,350
<p>You can give the function name too:</p> <pre><code>unittest.defaultTestLoader.loadTestsFromName('TestVehicle.test_speed') </code></pre> <p>This would only run the <code>test_speed</code> test.</p>
0
2016-06-01T09:16:01Z
[ "python", "python-unittest" ]
Dealing with accuracy in Python math operations
37,563,797
<p>I was trying to write a simple program to determine if input integer is a power of two.</p> <p>I had following code. It will fail the test case for <code>n=536870912</code> (<code>536870912</code> is the <code>2^29</code>).</p> <p>I tried with formating the number, <code>format(y,'12g')</code> the output is clo...
4
2016-06-01T08:50:23Z
37,563,900
<p>If you want to compare floats and allow for a little floating-point inaccuracy, you would normally check if they are within a certain allowable distance of each other (<code>if abs(x-y) &lt; epsilon</code>).</p> <p>However, if you want to find out if an <em>integer</em> is a power of 2, you can do it like this:</p>...
3
2016-06-01T08:55:23Z
[ "python" ]
Dealing with accuracy in Python math operations
37,563,797
<p>I was trying to write a simple program to determine if input integer is a power of two.</p> <p>I had following code. It will fail the test case for <code>n=536870912</code> (<code>536870912</code> is the <code>2^29</code>).</p> <p>I tried with formating the number, <code>format(y,'12g')</code> the output is clo...
4
2016-06-01T08:50:23Z
37,563,915
<p>The way to go about comparing floating point numbers for equality is <code>abs(a - b) &lt; tolerance</code>, where <code>tolerance = 1e-6</code> or some similar small number. In your case it would just be <code>abs(y) &lt; 1e-6</code>.</p> <p>For more info check out <a href="https://en.wikipedia.org/wiki/Floating_p...
2
2016-06-01T08:55:49Z
[ "python" ]
Dealing with accuracy in Python math operations
37,563,797
<p>I was trying to write a simple program to determine if input integer is a power of two.</p> <p>I had following code. It will fail the test case for <code>n=536870912</code> (<code>536870912</code> is the <code>2^29</code>).</p> <p>I tried with formating the number, <code>format(y,'12g')</code> the output is clo...
4
2016-06-01T08:50:23Z
37,564,101
<p>If you need accuracy and you don't want to reinvent the accuracy-wheel yourself, you could have a look at <a href="http://www.numpy.org/" rel="nofollow">NumPy</a>, which is precisely designed for this kind of purpose (accurately making complex mathematical operations on big numbers of any kind).</p> <pre><code>impo...
1
2016-06-01T09:04:17Z
[ "python" ]
Django Rest Framework viewsets queyset duplicate
37,563,996
<p>Can I use same <strong><em>queryset</em></strong> for two different <strong>ModelViewSet</strong> classes?</p> <p>I try to use same <strong><em>queryset</em></strong> but django rest framework duplicate my API route.</p> <p><em>views.py</em></p> <pre><code>class PlannerAgentViewSet(viewsets.ModelViewSet): qu...
1
2016-06-01T08:59:21Z
37,564,337
<p>Of course you can do it, but you have to manually set the <code>base_name</code> for your routes to change those uris.</p> <p>In your case :</p> <pre><code>router.register(r'planner_agent', views.PlannerAgentViewSet, base_name='planner_agent') router.register(r'planner_client', views.PlannerClientViewSet, base_nam...
0
2016-06-01T09:15:37Z
[ "python", "django", "api", "rest", "django-rest-framework" ]
Python IP address prefix matching
37,564,027
<p>I am trying to match the following ranges of IP prefixes <code>10.[0-255], 192.168, 172.[16-31]</code> with the following regex statements:</p> <pre><code>if not ((re.match("^10\.([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$", event["vpcprefix"])) or (event["vpcprefix"] == "192.168") or (re.match("^172\.(1[...
0
2016-06-01T09:00:54Z
37,564,459
<p>You have three patterns. Clearly only the first has any chance of being true, and within that the closest option between the <code>|</code>'s is <code>[01][0-9][0-9]</code>. But that's three digits, and <code>10</code> is two. Consider <code>[01]?[0-9]?[0-9]</code>.</p>
1
2016-06-01T09:21:27Z
[ "python", "regex" ]
Python IP address prefix matching
37,564,027
<p>I am trying to match the following ranges of IP prefixes <code>10.[0-255], 192.168, 172.[16-31]</code> with the following regex statements:</p> <pre><code>if not ((re.match("^10\.([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$", event["vpcprefix"])) or (event["vpcprefix"] == "192.168") or (re.match("^172\.(1[...
0
2016-06-01T09:00:54Z
37,564,540
<p>How about:</p> <pre><code>if not ((event["vpcprefix"].split('.')[0] == '10') or (event["vpcprefix"] == "192.168") or (event["vpcprefix"].split('.')[0] == '172')): #do stuff </code></pre> <p>don't think you really need the regex here.</p>
-1
2016-06-01T09:24:51Z
[ "python", "regex" ]
Does a python decorator just decorate the following function or all functions beneath?
37,564,070
<p>I've got a class definition as follows:</p> <pre><code>class myClass(object): @lru_cache(maxsize=None) def f1(self): return 1 def f2(self): return 2 </code></pre> <p>What I want to know is, does the <code>@lru_cache</code> decorator apply to all functions beneath until it hits another ...
0
2016-06-01T09:03:06Z
37,564,120
<p>Decorators only apply to the function following it, if it was the other way, what would happen if i didn't want to decorate the function? so they only apply to the following function.</p> <p>So you have to use <code>@lru_cahce</code> on the <code>f2</code> function if you want to cache it.</p>
1
2016-06-01T09:05:33Z
[ "python", "python-3.x" ]
Does a python decorator just decorate the following function or all functions beneath?
37,564,070
<p>I've got a class definition as follows:</p> <pre><code>class myClass(object): @lru_cache(maxsize=None) def f1(self): return 1 def f2(self): return 2 </code></pre> <p>What I want to know is, does the <code>@lru_cache</code> decorator apply to all functions beneath until it hits another ...
0
2016-06-01T09:03:06Z
37,564,323
<p>You can easily test this out yourself, by definining a decorator that will tell you whether you decorated something. For example this one:</p> <pre><code>def myDecorator (f): print('Decorated {0}'.format(f.__name__)) return f </code></pre> <p>Then, when used with your class:</p> <pre><code>class MyClass: ...
5
2016-06-01T09:14:47Z
[ "python", "python-3.x" ]
Does a python decorator just decorate the following function or all functions beneath?
37,564,070
<p>I've got a class definition as follows:</p> <pre><code>class myClass(object): @lru_cache(maxsize=None) def f1(self): return 1 def f2(self): return 2 </code></pre> <p>What I want to know is, does the <code>@lru_cache</code> decorator apply to all functions beneath until it hits another ...
0
2016-06-01T09:03:06Z
37,591,827
<p>In addition to poke's answer: how about looking at the formal syntax of function's definition?</p> <p>See <a href="https://docs.python.org/3/reference/compound_stmts.html#function-definitions" rel="nofollow">https://docs.python.org/3/reference/compound_stmts.html#function-definitions</a>.</p> <pre><code>funcdef ::...
0
2016-06-02T12:26:02Z
[ "python", "python-3.x" ]
Why does SPARK \PYSPARK compute everything even if result is accessed with limit command?
37,564,073
<p>I have mysql table stored in dataframe_mysql</p> <pre><code>dataframe_mysql = sqlContext.read.format("jdbc").options(... dataframe_mysql.registerTempTable('dataf') groupedtbl=sqlContext.sql("""SELECT job_seq_id,first(job_dcr_content) as firststage,last(job_dcr_content) as laststage, first(...
2
2016-06-01T09:03:12Z
37,569,793
<p>There are quite a few different problems here. Some are related to the data source you use, other to the query and finally there some introduced by using Python UDFs with Spark &lt; 2.0.0.</p> <p>Step by step:</p> <ul> <li><p>with JDBC data source the only the simple predicates are pushed-down to the source. It me...
2
2016-06-01T13:14:21Z
[ "python", "apache-spark", "pyspark" ]
Plotting Lists in Python
37,564,318
<p>I'm trying to make a Plot of two lists, once shall have the time measured with timeit and the other the amount of times i ran through the loop. I only get an empty plot so i figured that something is wrong. Could somebody perhaps tell me where the mistake is? The functions are not really important but I will post th...
1
2016-06-01T09:14:35Z
37,564,414
<p>I improve the main function, you had cleared lists on an every iteration:</p> <pre><code>if __name__ == "__main__": count = 10 ListCounts = [] ListTime = [] while count &lt; 1000: RandomSequences = generateSequences(count) First20Chars, RandomChoices = generatePrefixes(5, RandomSequ...
1
2016-06-01T09:19:28Z
[ "python", "list", "matplotlib" ]
How do you specify the SOAP server URL in Python zeep
37,564,475
<p>I'm using the Python zeep library but the documentation seems a bit thin. I'd like to be able to specify the URL of the SOAP server but at the moment I can only do this by hacking the WSDL file.</p>
1
2016-06-01T09:22:05Z
37,577,681
<p>I've just added this feature (<a href="https://github.com/mvantellingen/python-zeep/commit/08a757c35ad34defc401baea04b23ae889e2ee1a" rel="nofollow">https://github.com/mvantellingen/python-zeep/commit/08a757c35ad34defc401baea04b23ae889e2ee1a</a>)</p> <p>See the docs <a href="http://docs.python-zeep.org/en/latest/in-...
1
2016-06-01T19:56:32Z
[ "python", "soap" ]
Treat optional arguments just like -h
37,564,503
<p>How can I tell <code>argparse</code> to treat optional arguments just like <code>-h</code>, <code>--help</code>?</p> <p><strong>test.py</strong></p> <pre><code>def test(): print '## This is my test' import argparse parser = argparse.ArgumentParser(prog='test.py') parser.add_argument('-t', '--test', action='st...
4
2016-06-01T09:23:18Z
37,564,716
<p>Exiting funcitonality of help is defined in <code>argparse._HelpAction</code> <code>__call__</code> method.</p> <pre><code>class _HelpAction(Action): def __init__(self, option_strings, dest=SUPPRESS, default=SUPPRESS, help=None): super(...
2
2016-06-01T09:31:36Z
[ "python", "python-2.7", "argparse" ]
Treat optional arguments just like -h
37,564,503
<p>How can I tell <code>argparse</code> to treat optional arguments just like <code>-h</code>, <code>--help</code>?</p> <p><strong>test.py</strong></p> <pre><code>def test(): print '## This is my test' import argparse parser = argparse.ArgumentParser(prog='test.py') parser.add_argument('-t', '--test', action='st...
4
2016-06-01T09:23:18Z
37,564,871
<p>A simpler solution, define <a href="https://docs.python.org/3/library/argparse.html#nargs" rel="nofollow">nargs</a>:</p> <pre><code>parser.add_argument('req', nargs='?', help='Otherwise required') </code></pre> <p><code>?</code> means 0 or more. </p> <p>And then exit after runing your test:</p...
0
2016-06-01T09:37:18Z
[ "python", "python-2.7", "argparse" ]
Treat optional arguments just like -h
37,564,503
<p>How can I tell <code>argparse</code> to treat optional arguments just like <code>-h</code>, <code>--help</code>?</p> <p><strong>test.py</strong></p> <pre><code>def test(): print '## This is my test' import argparse parser = argparse.ArgumentParser(prog='test.py') parser.add_argument('-t', '--test', action='st...
4
2016-06-01T09:23:18Z
37,564,878
<p>The parameters of the last positional argument is not initialized correctly to achieve what you want.</p> <pre><code>parser.add_argument('req', nargs='?', default="truc", help='Otherwise required') </code></pre> <p>Please have a look to Python documentation for further details. But basically, the <code>nargs='?'</...
1
2016-06-01T09:37:34Z
[ "python", "python-2.7", "argparse" ]
Removing characters in chain according to an other column
37,564,617
<p>I have a df like : </p> <pre><code>products price abc|abc|abc|abc|abc 1|2|10|20|30 abc|abc|deg| 3|8|5 abc|abc|abc|abc|abc|abc 10|11|12|13|14|15|16|17|18 </code></pre> <p>Explication : Each rows is a basket buy by a customers. All products is seperate by '|', so ...
0
2016-06-01T09:27:39Z
37,565,655
<p>Use <code>str.split('|', expand=True)</code> to create a mask on price then recombine:</p> <pre><code>have_products = df.products.str.split('|', expand=True).notnull() get_price = df.price.str.split('|', expand=True)[have_p] df.price = get_price.apply(lambda x: '|'.join(x.dropna().astype(str)), axis=1) print df ...
0
2016-06-01T10:09:33Z
[ "python", "numpy", "pandas" ]
Can't find `FlaskWebProject` files in Azure set-up
37,564,673
<p>I am trying to run through the creation of a Flask web app in Azure using this instruction page.</p> <p><a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-python-create-deploy-flask-app/" rel="nofollow">Creating Web apps with Flask in Azure</a></p> <p>In the "Application Overveiw" section,...
0
2016-06-01T09:29:51Z
37,567,817
<p>Your initial GitHub repository is empty, so you need to clone the repository. The process is described in the same article you mentioned, but a little later.</p> <p>Basically:</p> <p>1) Go to the deployment source and configure the deployment source - for example, local github</p> <p>2) Go to Settings => Propert...
1
2016-06-01T11:49:55Z
[ "python", "azure", "flask" ]
PyQt How to remove a layout from a layout
37,564,728
<pre><code>datainputHbox = QHBoxLayout() layout = QVBoxLayout(self) layout.addLayout(datainputHbox) pagedatainputdeletboxbutton1.clicked.connect(lambda:self.boxdelete(datainputHbox)) def boxdelete(self, box): </code></pre> <p>This is the PyQt proragm How write boxdelete funtion in order to remove datainputHbox form...
-1
2016-06-01T09:32:08Z
37,575,246
<p>You can remove <code>QLayouts</code> by getting their corresponding <code>QLayoutItem</code> and removing it. You should also be storing references to your Layouts, otherwise there is no other way to access them later on unless you know the widget they belong to.</p> <pre><code>datainputHbox = QHBoxLayout() self.v...
1
2016-06-01T17:31:18Z
[ "python", "qt", "pyqt", "pyqt4", "pyqt5" ]
Python property on a list
37,564,798
<p>I am new to Python and I just discovered the properties. It works just fine when I try it on a simple variable but I cannot make it work on a list. When executing the code below it will call two times the getter and not the setter. I know that in my example the property has no added value but it is to simplify.</p> ...
3
2016-06-01T09:34:37Z
37,565,050
<p>Your <code>c.x[1] = 4</code> is in fact split into two operations:</p> <ol> <li>get the "x" property of c (=> getter)</li> <li>set item on the resulting object.</li> </ol> <p>There is no easy way how to get out of this. But anyway, in the end it does what you wanted, no?</p> <p>The setter would be called, if you ...
0
2016-06-01T09:43:47Z
[ "python", "python-3.x" ]
Python property on a list
37,564,798
<p>I am new to Python and I just discovered the properties. It works just fine when I try it on a simple variable but I cannot make it work on a list. When executing the code below it will call two times the getter and not the setter. I know that in my example the property has no added value but it is to simplify.</p> ...
3
2016-06-01T09:34:37Z
37,565,158
<p>The setter/getter are only used if you directly get or set the property:</p> <pre><code>c.x # getter c.x = [1,2,3] # setter </code></pre> <p>If you modify an element in the property you get the property and then set the corresponding element. Your example is equivalent to</p> <pre><code>d = c.x # ...
2
2016-06-01T09:48:20Z
[ "python", "python-3.x" ]
Possible to bind multiple variables to a tkinter messagebox
37,564,801
<p>I am looking to bind multiple variables into a tkinter messagebox. Is this possible? I do have some sample code that I put together plus it's error code.</p> <pre><code> lines = ['Principal Amount: %s', 'Rate: %s', 'Time: %s years.', 'Compounded: %s times a year.'] % (principal, rate, time, compound) tkinter...
0
2016-06-01T09:34:59Z
37,565,517
<p>The problem is not with the messagebox but with your definition of <em>lines</em> as mentioned in the error message:</p> <pre><code>TypeError: unsupported operand type(s) for %: 'list' and 'tuple' </code></pre> <p>This works:</p> <pre><code>tkinter.messagebox.showinfo('Compound Interest Result:', "\n".join(["test...
3
2016-06-01T10:03:09Z
[ "python", "user-interface", "python-3.x", "tkinter" ]
Pythonic way to generate a list of list
37,564,849
<p>What would be the most pythonic way of achieving the transformation from the following input:</p> <pre><code> input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] </code></pre> <p>to the desired output: </p> <pre><code>output = [[('a',1),('a',10)],[('c',31),('c',45)]] </code></pre> <p>where I have gro...
1
2016-06-01T09:36:29Z
37,565,049
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>. My solution is not one-liner, but more readable.</p> <pre><code>import itertools lists_in = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] lists_out = list() for name, group...
2
2016-06-01T09:43:47Z
[ "python", "comprehensive-list" ]
Pythonic way to generate a list of list
37,564,849
<p>What would be the most pythonic way of achieving the transformation from the following input:</p> <pre><code> input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] </code></pre> <p>to the desired output: </p> <pre><code>output = [[('a',1),('a',10)],[('c',31),('c',45)]] </code></pre> <p>where I have gro...
1
2016-06-01T09:36:29Z
37,565,091
<p>Using a 1-liner list comprehension: </p> <pre><code>&gt;&gt;&gt; L=[('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] &gt;&gt;&gt; [list(filter(lambda x:x[0]==i, L)) for i in set(map(lambda x:x[0], L)) if len(list(filter(lambda x:x[0]==i, L)))&gt;1] [[('a', 1), ('a', 10)], [('c', 31), ('c', 45)]] </code></pre...
3
2016-06-01T09:45:40Z
[ "python", "comprehensive-list" ]
Pythonic way to generate a list of list
37,564,849
<p>What would be the most pythonic way of achieving the transformation from the following input:</p> <pre><code> input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] </code></pre> <p>to the desired output: </p> <pre><code>output = [[('a',1),('a',10)],[('c',31),('c',45)]] </code></pre> <p>where I have gro...
1
2016-06-01T09:36:29Z
37,565,095
<p>Use <code>groupby</code> from <code>itertools</code> and list comprehension. This will give you a simple one liner: </p> <pre><code>from itertools import groupby filter(lambda x: len(x)&gt;1, [list(g) for i,g in groupby(input, key=lambda x: x[0])]) [[('a', 1), ('a', 10)], [('c', 31), ('c', 45)]] </code></pre>
4
2016-06-01T09:45:47Z
[ "python", "comprehensive-list" ]
Pythonic way to generate a list of list
37,564,849
<p>What would be the most pythonic way of achieving the transformation from the following input:</p> <pre><code> input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] </code></pre> <p>to the desired output: </p> <pre><code>output = [[('a',1),('a',10)],[('c',31),('c',45)]] </code></pre> <p>where I have gro...
1
2016-06-01T09:36:29Z
37,565,130
<p>There is nothing wrong with the following:</p> <pre><code>input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] d = {} for i in input: if i[0] in d: d[i[0]].append(i) else: d[i[0]] = [i] print([d[k] for k in d if len(d[k]) &gt; 1]) </code></pre> <p>Don't forget, you have to mantain a balanc...
1
2016-06-01T09:47:06Z
[ "python", "comprehensive-list" ]
Pythonic way to generate a list of list
37,564,849
<p>What would be the most pythonic way of achieving the transformation from the following input:</p> <pre><code> input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] </code></pre> <p>to the desired output: </p> <pre><code>output = [[('a',1),('a',10)],[('c',31),('c',45)]] </code></pre> <p>where I have gro...
1
2016-06-01T09:36:29Z
37,565,202
<p>Here is one solution:</p> <pre><code>&gt;&gt;&gt; input_list = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)] &gt;&gt;&gt; [[x for x in input_list if x[0]==a] for a in {x[0] for x in input_list if [k[0] for k in input].count(x[0])&gt;1}] </code></pre> <p>will print</p> <pre><code>&gt;&gt;&gt; [[('a', 1),...
1
2016-06-01T09:49:58Z
[ "python", "comprehensive-list" ]
selenium cannot screenshot a web element
37,564,932
<p><a href="http://i.stack.imgur.com/pXgkz.png" rel="nofollow"><img src="http://i.stack.imgur.com/pXgkz.png" alt="enter image description here"></a></p> <p>I can screenshot a whole page using Firefox.get_screenshot_as_file('2.png'),but when I screenshot a web element using passage.screenshot('1.png'),it alway raise th...
1
2016-06-01T09:39:44Z
37,565,356
<p>You're getting this exception because you cannot take a screenshot of just an element in selenium without some third-party libraries or your own code to handle this. See <a href="http://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python">This stackoverflow post</a><...
2
2016-06-01T09:56:23Z
[ "python", "selenium", "firefox" ]
selenium cannot screenshot a web element
37,564,932
<p><a href="http://i.stack.imgur.com/pXgkz.png" rel="nofollow"><img src="http://i.stack.imgur.com/pXgkz.png" alt="enter image description here"></a></p> <p>I can screenshot a whole page using Firefox.get_screenshot_as_file('2.png'),but when I screenshot a web element using passage.screenshot('1.png'),it alway raise th...
1
2016-06-01T09:39:44Z
37,565,807
<p>The screenshot of a web element is not implemented in the Firefox driver. A workaround would be to crop the targeted element from the screenshot:</p> <pre><code>import StringIO from selenium import webdriver from PIL import Image driver = webdriver.Firefox() driver.get('http://stackoverflow.com') # get the logo e...
3
2016-06-01T10:16:30Z
[ "python", "selenium", "firefox" ]
Why does slice assignment in dataframes consider indices?
37,564,977
<p>Coming from numpy, I would expect this snippet</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.rand(10)) df2 = pd.DataFrame(np.arange(10)) df1[4:6] = df2[5:7] print(df1) </code></pre> <p>to yield something along the lines of</p> <pre><code> 0 0 0.851412 1 0.533122 ...
2
2016-06-01T09:41:17Z
37,565,384
<p>The <code>index</code> is what makes a <code>pandas</code> <code>dataframe</code> something more than a <code>numpy</code> <code>ndarray</code>. You may have tripped over a seemingly minor inconvenience, but that same characteristic allows for many powerful operations that cannot be accomplished with <code>numpy</c...
2
2016-06-01T09:57:23Z
[ "python", "numpy", "pandas" ]
Use tornado future to fetch url, two different ways get different results
37,565,024
<p>I want to use tornado to fetch batch urls. So my code shows below:</p> <pre><code>from tornado.concurrent import Future from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop class BatchHttpClient(object): def __init__(self, urls, timeout=20): self.async_http_...
0
2016-06-01T09:43:01Z
37,566,072
<p>In your first code snippet, the problem is that by the time your callbacks execute, the value of <code>future</code> is the last value set by the loop. In other words, when this executes:</p> <pre><code>def f_callback(f1): future.set_result(f1.result()) </code></pre> <p>the value of <code>future</code>...
1
2016-06-01T10:29:07Z
[ "python", "tornado", "future" ]
Use tornado future to fetch url, two different ways get different results
37,565,024
<p>I want to use tornado to fetch batch urls. So my code shows below:</p> <pre><code>from tornado.concurrent import Future from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop class BatchHttpClient(object): def __init__(self, urls, timeout=20): self.async_http_...
0
2016-06-01T09:43:01Z
37,603,810
<p>Louis's answer is correct, but I'd like to suggest a few simpler alternatives. </p> <p>First, you could use <code>functools.partial</code> instead of a <code>make_callback</code> wrapper function:</p> <pre><code>def __mid(self): results = [] for url in self.urls: future = Future() ...
0
2016-06-02T23:40:12Z
[ "python", "tornado", "future" ]
using CiscoConfParse to find ACL applied to VTY and then check ACL for log statement
37,565,117
<p>I have the code to find the name of the 'access-class' on the 'line vty'</p> <p>After that I am able to find the ACL but then I want to check each line of the ACL to verify that the 'deny' and 'permit' statements have the 'log' keyword. And print a report of OPEN if there is no 'log' statement or NOT A FINDING if t...
1
2016-06-01T09:46:34Z
37,573,978
<p>I wrote up a proof of concept on this:</p> <pre><code>#!/usr/bin/env python import re from ciscoconfparse import CiscoConfParse def main(): cisco_file = 'cisco_ipsec.txt' cisco_cfg = CiscoConfParse(cisco_file) vty_acl = cisco_cfg.find_objects(r'access-class') # Find the ACL name acl_name = ''...
1
2016-06-01T16:19:25Z
[ "python", "ciscoconfparse" ]
using CiscoConfParse to find ACL applied to VTY and then check ACL for log statement
37,565,117
<p>I have the code to find the name of the 'access-class' on the 'line vty'</p> <p>After that I am able to find the ACL but then I want to check each line of the ACL to verify that the 'deny' and 'permit' statements have the 'log' keyword. And print a report of OPEN if there is no 'log' statement or NOT A FINDING if t...
1
2016-06-01T09:46:34Z
37,586,816
<pre><code>from ciscoconfparse import CiscoConfParse input_file = 'some_site.conf' parse = CiscoConfParse(input_file) ## Build a list of vty ACLs here (and flag if a vty doesn't have one) vty_acl_names = set([]) for vtyobj in parse.find_objects(r'^line\svty'): vty_acl_name = vtyobj.re_match_iter_typed('access-cl...
0
2016-06-02T08:43:08Z
[ "python", "ciscoconfparse" ]
Result from function call is not a proper array of floats, fsolve, sympy
37,565,127
<p>I'm trying to use fsolve but it returns Result from function call is not a proper array of floats here is the code</p> <p>If I do it like this, it doesn't work.</p> <pre><code> from sympy import * B=symbols('B') L=0.97 a = 0.04 b= 0.029 m = 4.8 I = 3.14*(a/2)*(b/2)**3/4 E = 10**...
1
2016-06-01T09:47:03Z
37,565,681
<p>Use <a href="http://docs.sympy.org/latest/modules/utilities/lambdify.html" rel="nofollow"><code>lambdify</code></a> to convert the symbolic expression into a function which can be evaluated numerically:</p> <pre><code>func = sy.lambdify(B, detA) </code></pre> <hr> <pre><code>import sympy as sy import math from sc...
1
2016-06-01T10:10:47Z
[ "python", "scipy", "sympy" ]
Why is pandas groupby filter is slower than merge?
37,565,292
<p>I've noticed that Pandas <code>groupby().filter()</code> is slow for large datasets. Much slower than the equivalent <code>merge</code>. Here's my example:</p> <pre><code>size = 50000000 df = pd.DataFrame( { 'M' : np.random.randint(10,size=size), 'A' : np.random.randn(size), 'B' :np.random.randn(size)}) %%time gb...
0
2016-06-01T09:54:30Z
37,573,794
<p>Using <code>%%prun</code>, you see that the faster <code>merge</code> relies on <code>inner_join</code>, <code>pandas.hashtable.Int64Factorizer</code> whereas the slower <code>filter</code> uses <code>groupby_indices</code> and <code>sort</code> (showing only calls consuming more than 0.02s):</p> <pre><code> ...
1
2016-06-01T16:09:31Z
[ "python", "performance", "pandas" ]
Extracting rasters from multiple NetCDF files based on date values in Python
37,565,305
<p>I have multiple NetCDF files (one for each year) that contain daily rainfall values for Australia. </p> <p>At present I am able to extract the specific days I want by reading from a .csv file that contains the list of dates I want. From this it then outputs each day as a raster file.</p> <p>However, the script I h...
1
2016-06-01T09:54:47Z
37,565,713
<p>If the question is really about python command line arguments you could add something like:</p> <pre><code>import sys year = int(sys.argv[1]) nc_name = 'pre.%d.nc' % (year,) </code></pre> <p>and then use this <code>nc_name</code>as filepathargument in your <code>arcpy.MakeNetCDFRasterLayer_md</code>call</p> <p>Th...
1
2016-06-01T10:12:06Z
[ "python", "raster", "netcdf" ]
socket.gethostbyname not working for my ddns hostname
37,565,565
<p>I have the following code to ping my ddns hostname and return if the host is up or down. I then tried adding the <code>socket.gethostbyname</code> which works for my normal hostname <code>www.iamsimonsmale.co.uk</code> but not <code>http://ssmale.ddns.net</code>.</p> <p>I have tried to remove the <code>http://</cod...
0
2016-06-01T10:05:24Z
37,601,990
<p>Query for the address without the <code>http://</code> part:</p> <pre><code>ip = socket.gethostbyname('ssmale.ddns.net') </code></pre> <p>And then use the full address in your requests query:</p> <pre><code>response = requests.get("http://ssmale.ddns.net") </code></pre> <p>Works on my machine:</p> <pre><code>&g...
0
2016-06-02T20:58:17Z
[ "python", "sockets", "dns", "ping" ]
Python: comparing two iterables element wise with different type
37,565,591
<p>I'd like to compare two sorted lists element wise and handle each case differently: </p> <ol> <li>If both iterables contain the an element, I'd like to call <code>update_func</code>.</li> <li>If only the left iterable contains an element, I'd like to call <code>left_surplus_func</code>.</li> <li>If only the right i...
0
2016-06-01T10:06:39Z
37,566,873
<p>You can simplify the <code>try</code> statements at the begining of your <code>while</code> loop by using the default argument of the <code>next</code> built-in function.</p> <pre><code>def compare_iterables_element_wise(left, right, compare_func, left_surplus_func, update_func, right_surplus_...
1
2016-06-01T11:05:39Z
[ "python", "list", "functional-programming", "itertools", "iterable" ]
Hierarchial Clustering in python using DTW distance
37,565,595
<p>I am trying to use DTW(dynamic time warping) distance to create hierarchical clustering in python.I am able to compute distances using DTW package but not sure of supplying userdefined distance to hierarchial clustering in scipy.</p> <p>Any thoughts on how to proceed would be a great help. thanks</p>
0
2016-06-01T10:06:55Z
37,570,179
<p>Please study the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html#sklearn.cluster.AgglomerativeClustering" rel="nofollow">scikit learn documentation</a>.</p> <blockquote> <p><strong>affinity</strong> : string or callable, default: “euclidean”</p> <blo...
0
2016-06-01T13:30:00Z
[ "python", "cluster-analysis" ]
How to kill this threading.Timer?
37,565,773
<p>I have launched a thread using a <code>Timer</code> object. Now, I want to stop this thread but I can't. I have used <code>cancel()</code>, but it doesn't work. I don't know why.</p> <pre><code>import threading import time import sys as system def Nop(): print("do nothing") return 0 def function(): try:...
1
2016-06-01T10:14:40Z
37,566,349
<p>The problem here can be solved by reading <a href="https://docs.python.org/2/library/threading.html#timer-objects" rel="nofollow">the documentation</a> more carefully. A timer thread's <code>cancel</code> method "... will only work if the timer is still in its waiting stage."</p> <p>By the time you call <code>t.can...
1
2016-06-01T10:41:39Z
[ "python", "multithreading", "timer" ]
How to let the user select an input from a finite list?
37,565,793
<p>I'm quite new of python and programming, so I'm sorry if it's a "noob question". Anyway, is it possible to ask the selection between multiple choice in python, without a if loop?</p> <p>Stupid example: </p> <pre><code>print "Do you want to enter the door" raw_input ("Yes or not") </code></pre> <p>And the user can...
-1
2016-06-01T10:16:02Z
37,566,008
<p>One possible way to achieve what you appear to require is with a <code>while</code> loop.</p> <pre><code>print "Do you want to enter the door" response = None while response not in {"yes", "no"}: response = raw_input("Please enter yes or no: ") # Now response is either "yes" or "no" </code></pre>
2
2016-06-01T10:26:07Z
[ "python", "multiple-choice" ]
How to let the user select an input from a finite list?
37,565,793
<p>I'm quite new of python and programming, so I'm sorry if it's a "noob question". Anyway, is it possible to ask the selection between multiple choice in python, without a if loop?</p> <p>Stupid example: </p> <pre><code>print "Do you want to enter the door" raw_input ("Yes or not") </code></pre> <p>And the user can...
-1
2016-06-01T10:16:02Z
37,567,304
<p>If you need to do this on a regular basis, there is a convenient library for this purpose that may help you achieve better user experience easily : <a href="https://pypi.python.org/pypi/inquirer" rel="nofollow">inquirer</a></p> <p><strong>Disclaimer : As far as i know, it won't work on Windows without some hacks.</...
1
2016-06-01T11:25:19Z
[ "python", "multiple-choice" ]
Python : How to project a 3D unstructured mesh to 2D?
37,566,016
<p>From an unstructured mesh (<code>X,Y,Z + connectivity</code>), I wish to create a 2D array corresponding to Z projection (top-view) on plane(<code>X,Y</code>). At this end, I have used plot_trisurf from matplotlib (for 3D representation .. and it works) and then I have tried to use contourf(<code>X, Y, Z, zdir='z'<...
0
2016-06-01T10:26:28Z
37,566,678
<p>You may interpolate your data to grid by <code>scipy.interpolate</code> (X,Y,Z - some set of data). This function interpolate unstructured D-dimensional data (<a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.griddata.html" rel="nofollow">http://docs.scipy.org/doc/scipy-0.16.1/ref...
0
2016-06-01T10:55:52Z
[ "python", "matplotlib", "3d", "mesh", "projection" ]
Python : How to project a 3D unstructured mesh to 2D?
37,566,016
<p>From an unstructured mesh (<code>X,Y,Z + connectivity</code>), I wish to create a 2D array corresponding to Z projection (top-view) on plane(<code>X,Y</code>). At this end, I have used plot_trisurf from matplotlib (for 3D representation .. and it works) and then I have tried to use contourf(<code>X, Y, Z, zdir='z'<...
0
2016-06-01T10:26:28Z
37,582,466
<p>You can use <code>tricontour</code>. You can find <a href="http://matplotlib.org/examples/pylab_examples/tricontour_demo.html" rel="nofollow">some examples</a> in the documentation. This is an example that they present there:</p> <p><a href="http://i.stack.imgur.com/Wh1wI.png" rel="nofollow"><img src="http://i.stac...
0
2016-06-02T04:04:41Z
[ "python", "matplotlib", "3d", "mesh", "projection" ]
Python argparse option concatenation
37,566,040
<p>Normally you can concatenate options like '-abbb', which will expand to '-a -b -b -b'. Counts would be 1 for a, abd 3 for b.</p> <p>However when mixing prefix_chars I see something different ...</p> <pre><code>import argparse parser = argparse.ArgumentParser( prefix_chars='-+' ) parser.add_argument( '-x', action='...
1
2016-06-01T10:27:42Z
37,575,135
<p>This was patched in late 2010, in early 2.7</p> <p><a href="http://bugs.python.org/issue9352" rel="nofollow">http://bugs.python.org/issue9352</a></p> <p>================</p> <p>I'm not aware of bug/issues or code changes that would affect this, but I could dig into it.</p> <p>For a start, strings of single prefi...
1
2016-06-01T17:23:08Z
[ "python", "argparse" ]
Python not resizing height of an image
37,566,101
<p>I want to resize some images and here is my code.</p> <pre><code>import os from PIL import Image size = 300, 300 for f in os.listdir('.'): if f.endswith('.png'): i = Image.open(f) fn, fext = os.path.splitext(f) i.thumbnail(size, Image.ANTIALIAS) i.save('output/{}{}'.format(fn, ...
-1
2016-06-01T10:30:44Z
37,566,271
<p><code>Image.thumbnail()</code> is designed to keep the aspect ratio of the original image. If you want the output image to be exactly 300x300 px, use <code>Image.resize()</code> instead.</p>
1
2016-06-01T10:37:30Z
[ "python", "image", "image-resizing" ]
How to find all terms in an expression in Sympy
37,566,132
<p>I have an expression as: <code>1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2</code></p> <p>What I need is a list that contain the terms in this expression.<br> i.e. <code>[1/(x+1), 4*x/(x-1), 3, -4*x**2 , 10*x**2]</code></p> <p><strong>update</strong>: It should not collect like terms. Therefore the list should have -4*x** 2...
9
2016-06-01T10:32:09Z
37,568,026
<p>In this case it is very easy:</p> <pre><code>&gt;&gt;&gt; expr = 1/(x+1)+4*x/(x-1)+3-4*x**2 &gt;&gt;&gt; expr.args ⎛ 1 2 4⋅x ⎞ ⎜3, ─────, -4⋅x , ─────⎟ ⎝ x + 1 x - 1⎠ </code></pre>
1
2016-06-01T11:59:24Z
[ "python", "sympy" ]
How to find all terms in an expression in Sympy
37,566,132
<p>I have an expression as: <code>1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2</code></p> <p>What I need is a list that contain the terms in this expression.<br> i.e. <code>[1/(x+1), 4*x/(x-1), 3, -4*x**2 , 10*x**2]</code></p> <p><strong>update</strong>: It should not collect like terms. Therefore the list should have -4*x** 2...
9
2016-06-01T10:32:09Z
37,589,893
<p>Based on the question and comments, if you can get the expression as a string, you can do something like this if you want to avoid term collection.</p> <pre><code>(sympify("1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2", evaluate=False)).args </code></pre> <p>this will return all the terms without collecting like terms.</p>
1
2016-06-02T10:57:20Z
[ "python", "sympy" ]
How to find all terms in an expression in Sympy
37,566,132
<p>I have an expression as: <code>1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2</code></p> <p>What I need is a list that contain the terms in this expression.<br> i.e. <code>[1/(x+1), 4*x/(x-1), 3, -4*x**2 , 10*x**2]</code></p> <p><strong>update</strong>: It should not collect like terms. Therefore the list should have -4*x** 2...
9
2016-06-01T10:32:09Z
37,603,053
<p>The right way to do this is <code>Add.make_args</code>. This is the same things as <code>expr.args</code> from Bjoern's answer, except if the expression is not an <code>Add</code> (a single term), it still gives that term, instead of traversing into that expression. </p> <pre><code>In [20]: expr = 1/(x+1)+4*x/(x-1)...
2
2016-06-02T22:17:16Z
[ "python", "sympy" ]
Register multiple admin classes for django-import-export
37,566,157
<p>I would like to have different export formats for a model, so one of them includes additional metadata not present in the others.</p> <p>I can create a ModelResource subclass for both export formats, but I would like to allow the user select them from the admin interface.</p> <p>It is something like this:</p> <pr...
1
2016-06-01T10:32:53Z
37,567,776
<p>You can add a proxy model, like this:</p> <pre><code>class IngredientColourRelationWithMetadataExport(IngredientColourRelation): class Meta: proxy = True verbose_name = "IngredientColourRelation (Exports Metadata)" </code></pre> <p>This model will share the same database table and return the sa...
0
2016-06-01T11:48:21Z
[ "python", "django", "admin", "django-import-export" ]
Call an external command in Python
37,566,176
<p>How can I call an external command (as if I'd typed it at the Unix shell) from within a Python script?</p> <p>I tried this code:</p> <pre><code>from subprocess import call call(["ls", "-l"]) </code></pre> <p>and it works. But when I try this code in a Python script:</p> <pre><code>from subprocess import call cal...
-1
2016-06-01T10:33:41Z
37,566,428
<pre><code>call([...], shell=True) </code></pre> <p>What's happening at the moment is that the rest of the arguments you're providing, <code>'2&gt;&amp;1', '|', 'sed', '-n', 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\1#p']</code> are being interpreted by <code>sox</code> as arguments, because there isn't a shell to in...
1
2016-06-01T10:44:44Z
[ "python", "shell", "command", "subprocess", "sox" ]
Call an external command in Python
37,566,176
<p>How can I call an external command (as if I'd typed it at the Unix shell) from within a Python script?</p> <p>I tried this code:</p> <pre><code>from subprocess import call call(["ls", "-l"]) </code></pre> <p>and it works. But when I try this code in a Python script:</p> <pre><code>from subprocess import call cal...
-1
2016-06-01T10:33:41Z
37,566,462
<p>You can also use <code>os.system</code>:</p> <pre><code>import os os.system("sox ../../data/opsoroassistant/rec.wav -n stat 2&gt;&amp;1 | sed -n 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\1#p'") </code></pre>
0
2016-06-01T10:46:16Z
[ "python", "shell", "command", "subprocess", "sox" ]
Call an external command in Python
37,566,176
<p>How can I call an external command (as if I'd typed it at the Unix shell) from within a Python script?</p> <p>I tried this code:</p> <pre><code>from subprocess import call call(["ls", "-l"]) </code></pre> <p>and it works. But when I try this code in a Python script:</p> <pre><code>from subprocess import call cal...
-1
2016-06-01T10:33:41Z
37,566,503
<p>The arguments in the call function should be in the same string as the command.</p> <pre><code>call('sed -arg1 -arg2 -argn') </code></pre>
-2
2016-06-01T10:47:31Z
[ "python", "shell", "command", "subprocess", "sox" ]
Call an external command in Python
37,566,176
<p>How can I call an external command (as if I'd typed it at the Unix shell) from within a Python script?</p> <p>I tried this code:</p> <pre><code>from subprocess import call call(["ls", "-l"]) </code></pre> <p>and it works. But when I try this code in a Python script:</p> <pre><code>from subprocess import call cal...
-1
2016-06-01T10:33:41Z
37,566,520
<p>another option (easier to use) is os.system('your original command')</p> <pre><code>import os os.system("sox ../../data/opsoroassistant/rec.wav -n stat 2&gt;&amp;1 | sed -n 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\1#p'") </code></pre>
0
2016-06-01T10:48:38Z
[ "python", "shell", "command", "subprocess", "sox" ]
Python to parse html data and store into the database
37,566,197
<p>a This is trouble me for two days, I am new one to python, I want to Parse the html data as the following link:<a href="http://movie.walkerplus.com/list/2015/12/" rel="nofollow">http://movie.walkerplus.com/list/2015/12/</a> </p> <p>and then store the data into the postgresql database named movie_db, and there is ta...
-1
2016-06-01T10:34:31Z
37,581,144
<p>I know this error. It means you are trying to insert string values into array columns. You can verify the SQL as below.</p> <pre><code>sql2 = cur.mogrify(SQL, obj) print sql2 </code></pre> <p>Your directors and roles fetched from html are list of strings. So after zip function the obj contains dir and roles as str...
1
2016-06-02T01:11:36Z
[ "python", "html", "postgresql", "insert", "beautifulsoup" ]
django - Mulitple excludes in template filter
37,566,267
<p>I have a custom template tag for filtering. The <code>get_files_by_type</code> works perfectly, but now i want to do an "exclude type" tag too. However, I don't know how to format this one, as the exclude may be 1 or more tags.</p> <p>How would I do this in the function and how do I need to format the template? i.e...
1
2016-06-01T10:37:23Z
37,567,968
<p>This would work:</p> <pre><code>{% exclude_files_by_type Site.sitefiles_set.all "Site Plan, Cabinet Photo" as files %} </code></pre> <p>and your assignment tag:</p> <pre><code>@register.assignment_tag def exclude_files_by_type(SiteFiles, types): type_list = [type.strip() for type in types.split(',')] retu...
1
2016-06-01T11:56:42Z
[ "python", "django" ]
Custom POS tagging with spacy
37,566,470
<p>Alright so right now i have a code to do custom tagging with nltk. I use NLTK's POS tagger as a backoff with a trigram tagger where i train my own tagged sentences with custom tags. This works decently but i want to be able to do the same with spacy's POS tagger. Is there a way to do this?</p> <p>Here is my code:</...
0
2016-06-01T10:46:37Z
37,831,380
<pre><code>from spacy.en import English oNlp = English() oDoc = oNlp(sUnicodeInputText) loTokens = [o for o in oDoc] </code></pre> <p><code>loTokens</code> here contains a list of all tokens extracted by spacy. Each token has properties that you can use. To get the POS, use the <code>.pos_</code> attribute. For e...
0
2016-06-15T09:26:23Z
[ "python", "nltk", "spacy" ]
plot the histogram of one coloumn data from a txt file
37,566,582
<p>I need to read data from a file which has only one column. Then plot the barred histogram of the data. However, by the following code the figure shows me only a line in zero and nothing more. </p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib f= np.loadtxt('data Ties', unpack='Fal...
1
2016-06-01T10:52:04Z
37,567,192
<p>you got the arguments to <code>linspace</code> backwards - it is defined as <code>linspace(start, end, n)</code>, so you should write</p> <pre><code>bins = np.linspace(0, 100000, 50) </code></pre>
0
2016-06-01T11:20:12Z
[ "python", "numpy", "matplotlib" ]
plot the histogram of one coloumn data from a txt file
37,566,582
<p>I need to read data from a file which has only one column. Then plot the barred histogram of the data. However, by the following code the figure shows me only a line in zero and nothing more. </p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib f= np.loadtxt('data Ties', unpack='Fal...
1
2016-06-01T10:52:04Z
37,567,323
<p>Need to set proper number of bins, i.e.:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib f= np.loadtxt('data', unpack='False') # set bins' interval for your data # You have following intervals: # 1st col is number of data elements in [0,10000); # 2nd col is number of data elem...
0
2016-06-01T11:26:19Z
[ "python", "numpy", "matplotlib" ]
data clean-up in python using large (1.7gig) csv files
37,566,586
<p>I'm trying to do some data clean-up using python. I have some large <code>(1 - 2gigs) csv</code> files that I want to sort by some attribute (e.g. date, time), and then output another <code>csv</code> file with this info with the purpose of making it able to be used in excel. </p> <p>As I iterate through the rows, ...
0
2016-06-01T10:52:13Z
37,567,089
<p>If you don't need to hold the whole file content in memory, you can just process each line and immediately write it to the output file. Also, in your example you parse the CSV and then generate CSV again, but you don't seem to make use of parsed data. If that is correct, you could simply do this:</p> <pre><code>def...
0
2016-06-01T11:15:44Z
[ "python", "csv", "memory", "bigdata" ]
Numpy optimization with Numba
37,566,639
<p>I have two sets of points on a sphere, labelled 'obj' and 'ps' in the code example below. I would like to identify all 'obj' points that are closer than a certain angular distance from a 'ps' point.</p> <p>My take on this is to represent each point by a 3D unit vector, and to compare their dot products to cos(maxim...
3
2016-06-01T10:54:18Z
37,580,762
<p>Unlike <code>list.append</code> you should never call <code>numpy.append</code> in a loop! This is because even for appending a single element the whole array needs to be copied. Because you're only interested in the unique <code>obj</code> you could use a Boolean array to flag the matches found so far.</p> <p>As f...
3
2016-06-02T00:16:28Z
[ "python", "numpy", "numba" ]
How to count the 'number of time a field is edited or updated' in Odoo 8?
37,566,668
<p>I want to count how many times a field is edited in a form, the count should be passed to another field called 'Number of Edits' in the same form.</p>
0
2016-06-01T10:55:32Z
37,569,797
<p>This code Works fine.. </p> <pre><code>def write(self, cr, uid, ids, vals, context=None): quotation_obj=self.browse(cr, uid, ids,context=context) if partner_id: count = quotation_obj.number_of_edits + 1 vals.update({'number_of_edits': count}) return super(sale_order, sel...
0
2016-06-01T13:14:37Z
[ "python", "count", "field", "openerp", "odoo-8" ]
How to save created Zip file to file system in python?
37,566,679
<p>Using python zipfile module I created a zip file as follows:</p> <pre><code>s = StringIO() zip_file = zipfile.ZipFile(s, "w") zip_file.write('/local/my_files/my_file.txt') s.seek(0) </code></pre> <p>and now, I want this <code>zip_file</code> to be saved in my file system at path <code>/local/my_files/</code> as <c...
0
2016-06-01T10:55:53Z
37,566,862
<pre><code>zip_file = zipfile.ZipFile("/local/my_files/my_file.zip", "w") zip_file.write('/local/my_files/my_file.txt') zip_file.close() </code></pre> <p>The first argument of the <code>ZipFile</code> object initialization is the path to which you want to save the zip file.</p>
2
2016-06-01T11:04:52Z
[ "python", "python-2.7", "zipfile" ]
How to save created Zip file to file system in python?
37,566,679
<p>Using python zipfile module I created a zip file as follows:</p> <pre><code>s = StringIO() zip_file = zipfile.ZipFile(s, "w") zip_file.write('/local/my_files/my_file.txt') s.seek(0) </code></pre> <p>and now, I want this <code>zip_file</code> to be saved in my file system at path <code>/local/my_files/</code> as <c...
0
2016-06-01T10:55:53Z
37,567,215
<p>If you need to use StringIO, just try this code:</p> <pre><code>from StringIO import StringIO import zipfile s = StringIO() with zipfile.ZipFile(s, "w", compression=zipfile.ZIP_DEFLATED) as zf: zf.write('/local/my_files/my_file.txt') with open('/local/my_files/my_file.zip', 'wb') as f_out: f_out.write(s.g...
0
2016-06-01T11:21:13Z
[ "python", "python-2.7", "zipfile" ]
Python multiline regex delimiter
37,566,680
<p>Having this multiline variable:</p> <pre><code>raw = ''' CONTENT = ALL TABLES = TEST.RAW_1 , TEST.RAW_2 , TEST.RAW_3 , TEST.RAW_4 PARALLEL = 4 ''' </code></pre> <p>The structure is always <code>TAG = CONTENT</code>, both strings are NOT fixed and <code>CONTENT</code> could contain new line...
1
2016-06-01T10:55:55Z
37,566,748
<p>You can use a positive lookahead to make sure you lazily match the value correctly:</p> <pre><code>(\w+)\s=\s(.+?)(?=$|\n[A-Z]) ^^^^^^^^^^^^ </code></pre> <p>To be used with a DOTALL modifier so that a <code>.</code> could match a newline symbol. The <code>(?=$|\n[A-Z])</code> lookahead will requir...
1
2016-06-01T10:59:19Z
[ "python", "regex", "multiline", "multilinestring" ]
Retrieving column from a SQLalchemy relationship
37,566,707
<p>I'm working on some wxpython widgets that integrate SQLalchemy, CRUD stuff. I've got a wx.ComboBox that lists the rows of a table linked by a relationship.</p> <pre><code>class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) class Cat...
0
2016-06-01T10:57:34Z
37,578,179
<p>You can get the column associated with a relationship by inspecting the <code>.prop</code> attribute:</p> <pre><code>&gt;&gt;&gt; Thing.category.prop.local_columns set([Column('category_id', Integer(), ForeignKey('category.id'), table=&lt;thing&gt;)]) &gt;&gt;&gt; Thing.category.prop.remote_side set([Column('id', I...
0
2016-06-01T20:28:08Z
[ "python", "sqlalchemy", "foreign-keys", "relationship" ]
pymssql package does not work with lambda in aws
37,566,890
<p>How do we create a pymssql package for lambda. I tried creating it using pip install pymssql -t . When I run my lambda function it complaints saying that Unable to import module 'lambda_function': No module named lambda_function</p> <p>I follow the steps on this link <a href="http://docs.aws.amazon.com/lambda/lat...
0
2016-06-01T11:06:20Z
37,691,571
<p>Finally i could do it. It didnt worked with windows packages so used ubuntu to package freetds.so file and it worked.</p>
0
2016-06-08T00:37:20Z
[ "python", "aws-lambda", "pymssql" ]
How to modify Python dictionary value and create the list of dictionaries?
37,566,954
<p>I want to modify dictionary and to create a list that contains dictionaries with the modified values. I tried:</p> <pre><code>mylist = [] mydict = {"one": 10, "two": 20, "three": 30} for i in [111, 222, 333]: mydict["two"] = i mylist.append(mydict) </code></pre> <p>mylist returns:</p> <pre><code>[{'three': ...
2
2016-06-01T11:09:14Z
37,567,083
<p>That's because you are just creating multiple references to same object (your dictionary) and by assigning the throwaway variable <code>i</code> to your keys which holds 333 at the last iteration and assign it to the <code>two</code> key, all of your dictionary names will point to same object with item <code>('two'...
4
2016-06-01T11:15:20Z
[ "python", "list", "dictionary", "append" ]
How to Skip the login password prompt if not entered
37,567,036
<p>How to Skip the login password prompt if not entered or password is wrong.. I have Below python fabric code.. which works fine but stucks with wrong passwords..</p> <pre><code>import sys from fabric.api import * env.skip_bad_hosts=True env.command_timeout=60 env.user = 'test' env.shell = "/bin/sh -c" env.warn_only ...
0
2016-06-01T11:13:21Z
37,808,041
<p>You can use this parameters - </p> <pre><code>with settings(abort_on_prompts=True): </code></pre> <p>This parameter terminate the program when prompt the user for input. You can read about it <a href="http://docs.fabfile.org/en/1.11/usage/env.html#abort-on-prompts" rel="nofollow">here</a>. </p> <p>I don't know if...
0
2016-06-14T09:27:27Z
[ "python", "fabric" ]
How to Skip the login password prompt if not entered
37,567,036
<p>How to Skip the login password prompt if not entered or password is wrong.. I have Below python fabric code.. which works fine but stucks with wrong passwords..</p> <pre><code>import sys from fabric.api import * env.skip_bad_hosts=True env.command_timeout=60 env.user = 'test' env.shell = "/bin/sh -c" env.warn_only ...
0
2016-06-01T11:13:21Z
37,972,301
<p>When I want to dodge a password prompt but continue my script on fail, I use <code>abort_on_prompts=True</code> and catch the <code>SystemExit</code> exception that is raised by abort_on_prompt.</p> <pre><code>try : with settings(abort_on_prompts=True): output=sudo("/monitor.sh",shell=False) except SystemExi...
0
2016-06-22T15:23:52Z
[ "python", "fabric" ]
Google Appengine: Requests Alternative
37,567,054
<p>I have a non-GAE application/request-handler that uses the Python requests module in a to post an uploaded imaged via a POST request, as binary:</p> <pre><code>headers = {"MyAuth" : "xyz"} r = requests.post(base_uri, data=open('0.jpg')), headers=headers) </code></pre> <p>The user uploads an image, the uploaded ima...
0
2016-06-01T11:14:16Z
37,567,169
<p>Commonly used module for making HTTP requests on app engine is <a href="https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.api.urlfetch" rel="nofollow">urlfetch</a>, it is available in the default runtime via <code>google.appengine.api.urlfetch</code>. Supposedly urllib2 and/or urllib3 are also ...
1
2016-06-01T11:18:51Z
[ "python", "google-app-engine", "python-requests", "urllib3" ]