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
Getting "TypeError: must be a string, not function"
38,711,475
<p>I'm using a microcontroller to control a lightbulb based on a user input time, and I'm running this function in a thread. I keep getting an error at the line <code>time.sleep(1)</code>:</p> <blockquote> <p>TypeError: must be a string, not function</p> </blockquote> <pre><code>def light(): while True: ...
1
2016-08-02T03:49:46Z
38,714,093
<p>Problem was caused by me accidentally naming a variable and the function the same name. Changing the names fixed it. Thanks everyone for your help!</p>
0
2016-08-02T07:19:53Z
[ "python", "multithreading" ]
error when import panda the second time in mac python 2.7
38,711,504
<p>I cannot use <code>import pandas as pd</code> the second time. At the beginning, I type this it worked very well. After I close the terminal, reopen it, and type it again, it is said 'pd' is not defined...</p> <p>This happened both in Apple Python and Anaconda. I have tried deleting one and only use the other, but ...
-1
2016-08-02T03:54:32Z
38,711,552
<p>I am not sure I understand your question, but if this behavior is what you mean, this is normal behavior. I do not have pandas, but with any other library should be the same:</p> <pre><code>&gt;&gt;&gt; import requests as pd &gt;&gt;&gt; print pd.__version__ 2.9.1 &gt;&gt;&gt; exit() Abel-Guzman-Sanchezs-MacBook-Ai...
0
2016-08-02T04:01:00Z
[ "python" ]
How to compute the probability of a value given a list of samples from a distribution in Python?
38,711,541
<p>Not sure if this belongs in statistics, but I am trying to use Python to achieve this. I essentially just have a list of integers:</p> <pre><code>data = [300,244,543,1011,300,125,300 ... ] </code></pre> <p>And I would like to know the probability of a value occurring given this data. I graphed histograms of the da...
7
2016-08-02T03:58:48Z
38,712,122
<p>Here is one possible solution. You count the number of occurrences of each value in the original list. The future probability for a given value is its past rate of occurrence, which is simply the # of past occurrences divided by the length of the original list. In Python it's very simple:</p> <p>x is the given l...
3
2016-08-02T05:05:35Z
[ "python", "matplotlib", "scipy", "probability", "probability-density" ]
How to compute the probability of a value given a list of samples from a distribution in Python?
38,711,541
<p>Not sure if this belongs in statistics, but I am trying to use Python to achieve this. I essentially just have a list of integers:</p> <pre><code>data = [300,244,543,1011,300,125,300 ... ] </code></pre> <p>And I would like to know the probability of a value occurring given this data. I graphed histograms of the da...
7
2016-08-02T03:58:48Z
38,712,171
<p>Since you don't seem to have a specific distribution in mind, but you might have a lot of data samples, I suggest using a non-parametric density estimation method. One of the data types you describe (time in ms) is clearly continuous, and one method for non-parametric estimation of a probability density function (PD...
5
2016-08-02T05:11:08Z
[ "python", "matplotlib", "scipy", "probability", "probability-density" ]
How to compute the probability of a value given a list of samples from a distribution in Python?
38,711,541
<p>Not sure if this belongs in statistics, but I am trying to use Python to achieve this. I essentially just have a list of integers:</p> <pre><code>data = [300,244,543,1011,300,125,300 ... ] </code></pre> <p>And I would like to know the probability of a value occurring given this data. I graphed histograms of the da...
7
2016-08-02T03:58:48Z
38,712,299
<p>OK I offer this as a starting point, but estimating densities is a very broad topic. For your case involving the amount of characters in a sequence, we can model this from a straight-forward frequentist perspective using <em>empirical probability</em>. Here, probability is essentially a generalization of the concept...
3
2016-08-02T05:23:34Z
[ "python", "matplotlib", "scipy", "probability", "probability-density" ]
Can somebody explain to how to do this last step in this tutorial
38,711,542
<p>I am attempting to add search functionality to my Django app by using haystack and elasticsearch, and after doing some searching on google I came across this tutorial:</p> <p><a href="http://www.techstricks.com/django-haystack-and-elasticsearch-tutorial/" rel="nofollow">http://www.techstricks.com/django-haystack-an...
1
2016-08-02T03:58:51Z
38,714,730
<p>There is work in progress to support to match <code>django urls</code> in haystack github issues. If found any errors when you are trying to use without url then please add <code>url</code>. Hopefully they will upgrade to the latest docs soon.</p>
0
2016-08-02T07:52:41Z
[ "python", "django", "elasticsearch", "django-haystack" ]
How to create an animation which cycles through a series of matpyplot.pyplot imshows
38,711,548
<p>I would like to convert the following code into an animation which cycles through the x values rather than just returning one x value like it currently does. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt def sliceplot(file_glob,xslice): """User inputs location of binary data file and s...
0
2016-08-02T04:00:04Z
38,742,320
<p>Is something like this what you like to do? My example below -- based on <a href="http://matplotlib.org/examples/animation/dynamic_image.html" rel="nofollow">this</a> example -- is using some dummy-image from the function <code>generate_image</code>, defined in the script. From what I understand of your question y...
0
2016-08-03T11:29:54Z
[ "python", "animation", "matplotlib", "imshow" ]
Python Permission Error when reading
38,711,568
<pre><code>import os import rarfile file = input("Password List Directory: ") rarFile = input("Rar File: ") passwordList = open(os.path.dirname(file+'.txt'),"r") </code></pre> <p>with this code I am getting the error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Nick L\Desktop\Programming\...
1
2016-08-02T04:03:12Z
38,712,079
<p>You're trying to open a <em>directory</em>, not a file, because of the call to <code>dirname</code> on this line:</p> <pre class="lang-python3 prettyprint-override"><code>passwordList = open(os.path.dirname(file+'.txt'),"r") </code></pre> <p>To open the file instead of the directory containing it, you want somet...
2
2016-08-02T05:00:39Z
[ "python", "windows", "python-3.x", "permissions", "file-permissions" ]
Python Permission Error when reading
38,711,568
<pre><code>import os import rarfile file = input("Password List Directory: ") rarFile = input("Rar File: ") passwordList = open(os.path.dirname(file+'.txt'),"r") </code></pre> <p>with this code I am getting the error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Nick L\Desktop\Programming\...
1
2016-08-02T04:03:12Z
38,712,311
<p>os.path.dirname() will return the Directory in which the file is present not the file path. For example if file.txt is in path= 'C:/Users/Desktop/file.txt' then os.path.dirname(path)wil return 'C:/Users/Desktop' as output, while the open() function expects a file path. You can change the current working directory to...
1
2016-08-02T05:24:31Z
[ "python", "windows", "python-3.x", "permissions", "file-permissions" ]
Django JSon response format, nested fields
38,711,624
<p>I just made an ajax request to a DJango View, it give me back the data, but i don't know how to get only the fields that i want.</p> <p>This is the part of my view:</p> <pre><code>if request.method == 'POST': txt_codigo_producto = request.POST.get('codigobarras_producto') response_data = {} ...
0
2016-08-02T04:10:26Z
38,711,736
<p>You are doing multiple encoding, i.e. first you using serializers.serialize and then json.dumps.</p> <p>Use only json.dumps and content_type as json like this, without using serializers.</p> <pre><code>response_dict = {'your_data_key': 'and your values'} return HttpResponse( json.dumps(response_dat...
1
2016-08-02T04:23:22Z
[ "python", "json", "ajax", "django" ]
Django JSon response format, nested fields
38,711,624
<p>I just made an ajax request to a DJango View, it give me back the data, but i don't know how to get only the fields that i want.</p> <p>This is the part of my view:</p> <pre><code>if request.method == 'POST': txt_codigo_producto = request.POST.get('codigobarras_producto') response_data = {} ...
0
2016-08-02T04:10:26Z
38,713,020
<p>Answer to your first question:- You can change your queries as follows:</p> <pre><code>resp_producto=Producto.objects.filter(codigobarras_producto=txt_codigo_producto).only('requiredField') resp_inventario=InventarioProducto.objects.filter(producto_codigo_producto__in=resp_producto).only('requiredField').order_by('...
0
2016-08-02T06:17:28Z
[ "python", "json", "ajax", "django" ]
Service inside docker container stops after some time
38,711,658
<p>I have deployed a rest service inside a docker container using uwsgi and nginx. When I run this python flask rest service inside docker container, for first one hour service works fine but after sometime somehow nginx and rest service stops for some reason.</p> <p>Has anyone faced similar issue? Is there any know f...
0
2016-08-02T04:14:49Z
38,712,037
<p>Consider doing a <code>docker ps -a</code> to get the stopped container's identifier. <code>-a</code> here just means listing <strong>all</strong> of the containers you got on your machine.</p> <p>Then do <code>docker inspect</code> and look for the <code>LogPath</code> attribute. Open up the container's log file ...
1
2016-08-02T04:56:10Z
[ "python", "rest", "nginx", "docker" ]
Regex find word including "-"
38,711,686
<p>I have the below regex (from this link: <a href="http://stackoverflow.com/questions/10380992/get-python-dictionary-from-string-containing-key-value-pairs">get python dictionary from string containing key value pairs</a>)</p> <pre><code>r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)" </code></pre> <p>Here is the explanati...
0
2016-08-02T04:17:10Z
38,711,726
<p>You could try something such as this:</p> <pre><code>r"\b([\w\-]+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)" </code></pre> <p>Note the <code>[\w\-]+</code>, which allows matching both a word character and a dash.</p> <p>For readability in the future, you may also want to investigate <a href="https://docs.python.org/3/librar...
1
2016-08-02T04:21:43Z
[ "python", "regex" ]
How to specify multiple auth in Python's requests module?
38,711,778
<p>I want to access a BASIC auth protected website via a proxy which requires NTLM authentication. I am using Python's requests module to access the website. How can I specify multiple authentication for a request in requests module? i.e. I need to provide NTLM credentials for proxy authentication and BASIC credentials...
0
2016-08-02T04:29:40Z
38,711,928
<p>To use HTTP Basic Auth with your proxy, use the <code>http://user:password@host:port/</code> syntax:</p> <p><code>proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}</code></p>
0
2016-08-02T04:44:50Z
[ "python", "authentication", "python-requests" ]
How to specify multiple auth in Python's requests module?
38,711,778
<p>I want to access a BASIC auth protected website via a proxy which requires NTLM authentication. I am using Python's requests module to access the website. How can I specify multiple authentication for a request in requests module? i.e. I need to provide NTLM credentials for proxy authentication and BASIC credentials...
0
2016-08-02T04:29:40Z
38,715,744
<p>Try to add <code>HTTPBasicAuth</code> as follow:</p> <pre><code>import requests from requests_ntlm import HttpNtlmAuth from requests.auth import HTTPBasicAuth proxies = {'https': 'https://myproxy.com:8080', 'http': 'http://myproxy.com:8080'} auth = (HttpNtlmAuth('ntlm_username','ntlm_secret'), HTTPBasicAuth('user_...
0
2016-08-02T08:46:17Z
[ "python", "authentication", "python-requests" ]
python multiprocessing pool timeout
38,711,840
<p>I want to use <a href="https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool" rel="nofollow">multiprocessing.Pool</a>, but multiprocessing.Pool can't abort a task after a timeout. I found <a href="http://stackoverflow.com/questions/29494001/how-can-i-abort-a-task-in-a-multiprocessing-poo...
1
2016-08-02T04:36:17Z
38,792,237
<p>There is no implicit risk in stopping a running job, the OS will take care of correctly terminating the process.</p> <p>If your job is writing on files, you might end up with lots of truncated files on your disk.</p> <p>Some small issue might also occur if you write on DBs or if you are connected with some remote ...
2
2016-08-05T14:55:02Z
[ "python", "multithreading", "multiprocessing", "python-multithreading", "python-multiprocessing" ]
Segmentation fault writing xarray datset to netcdf or dataframe
38,711,915
<p>I get a segmentation fault working with a xarray dataset that was created from multiple grib2 files. The fault occurs when writing out to a netcdf as well as when writing to a dataframe. Any suggestions on what is going wrong are appreciated.</p> <pre><code>files = os.listdir(download_dir) </code></pre> <p>Example...
0
2016-08-02T04:43:47Z
38,712,685
<p><s>PyNIO doesn't play well with multithreading. Try adding <code>lock=True</code> to <code>open_mfdataset</code> (we should probably set this by default).</s></p> <p>Try adding <code>proprocess=lambda x: x.load()</code> to the <code>open_mfdataset</code> call. This will ensure that each dataset is fully loaded into...
0
2016-08-02T05:54:52Z
[ "python", "python-xarray" ]
How to compute correclty cross validation scores in scikit-learn?
38,711,932
<p>I am doing a classification task. Nevertheless, I am getting slightly different results:</p> <pre><code>#First Approach kf = KFold(n=len(y), n_folds=10, shuffle=True, random_state=False) pipe= make_pipeline(SVC()) for train_index, test_index in kf: X_train, X_test = X[train_index], X[test_index] y_train, y_...
2
2016-08-02T04:45:40Z
38,714,998
<p>For any classification task its always good to use StratifiedKFold cross validation split. In stratified KFold, you have equal number of samples from each class for your classification problem. </p> <p><a href="http://i.stack.imgur.com/IhA9o.png" rel="nofollow"><img src="http://i.stack.imgur.com/IhA9o.png" alt="Str...
2
2016-08-02T08:06:34Z
[ "python", "python-3.x", "machine-learning", "scikit-learn" ]
How to compute correclty cross validation scores in scikit-learn?
38,711,932
<p>I am doing a classification task. Nevertheless, I am getting slightly different results:</p> <pre><code>#First Approach kf = KFold(n=len(y), n_folds=10, shuffle=True, random_state=False) pipe= make_pipeline(SVC()) for train_index, test_index in kf: X_train, X_test = X[train_index], X[test_index] y_train, y_...
2
2016-08-02T04:45:40Z
38,715,192
<p>First, as explained in the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.cross_val_score.html" rel="nofollow">documentation</a> and shown in some <a href="http://scikit-learn.org/stable/auto_examples/exercises/plot_cv_diabetes.html#example-exercises-plot-cv-diabetes-py" rel="nofo...
2
2016-08-02T08:18:07Z
[ "python", "python-3.x", "machine-learning", "scikit-learn" ]
Is this behavior documented in Django's field validators for foreign keys?
38,711,947
<p>This is an example Python 2 code:</p> <pre><code>from django.db import models def my_validator(value): assert isinstance(value, (int, long)) class Foo(models.Model): name = models.CharField(...) # irrelevant here class Bar(models.Model): name = models.CharField(...) # irrelevant here foo = models...
1
2016-08-02T04:46:45Z
38,712,244
<p>Yes - this is implicitly referred to in the documentation for <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.to_field" rel="nofollow"><code>ForeignKey.to_field</code></a>:</p> <blockquote> <p>The field on the related object that the relation is to. By default, Django...
3
2016-08-02T05:18:34Z
[ "python", "django" ]
Is this behavior documented in Django's field validators for foreign keys?
38,711,947
<p>This is an example Python 2 code:</p> <pre><code>from django.db import models def my_validator(value): assert isinstance(value, (int, long)) class Foo(models.Model): name = models.CharField(...) # irrelevant here class Bar(models.Model): name = models.CharField(...) # irrelevant here foo = models...
1
2016-08-02T04:46:45Z
38,714,016
<p>I'm not sure that @<strong>solarissmoke</strong> answer is relevant to the question. </p> <p>IMO, <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/#validating-objects" rel="nofollow">validation</a> is not invoked at <code>objects.create</code>, if you want to validate your model before creating i...
1
2016-08-02T07:16:30Z
[ "python", "django" ]
Function that depends on the row number
38,711,966
<p>In pandas, is it possible to reference the row number for a function. I am not talking about .iloc.</p> <p>iloc takes a location i.e. a row number and returns a dataframe value.</p> <p>I want to access the location number in the dataframe. </p> <p>For instance, if the function is in the cell that is 3 rows down...
2
2016-08-02T04:48:13Z
38,712,603
<p>Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['c', 'd']) df </code></pre> <p><a href="http://i.stack.imgur.com/xwmXc.png" rel="nofollow"><img src="http://i.stack.imgur.com/xwmXc.png" alt="enter image description here"></a></p> <p>And the row <code>row</cod...
2
2016-08-02T05:48:26Z
[ "python", "pandas", "numbers", "row" ]
Function that depends on the row number
38,711,966
<p>In pandas, is it possible to reference the row number for a function. I am not talking about .iloc.</p> <p>iloc takes a location i.e. a row number and returns a dataframe value.</p> <p>I want to access the location number in the dataframe. </p> <p>For instance, if the function is in the cell that is 3 rows down...
2
2016-08-02T04:48:13Z
38,721,746
<p>Sorry I couldnt add a code sample but Im on my phone. piRSquared confirmed my fears when he said the info is lost. I guess ill have to do a loop everytime or add a column with numbers ( that will get scrambled if i sort them : / ).</p> <p>Thanks everyone.</p>
0
2016-08-02T13:25:14Z
[ "python", "pandas", "numbers", "row" ]
Object indexing in python
38,712,056
<p>I have created the following objects in python</p> <p>It creates an object of class arc and then creates another object network using the object arc</p> <pre><code>class Arc: # Creates an object of class arc def __init__(self, tailNode = 0, headNode = 0, lowerBound = 0, upperBound = 0, cost = 0): s...
0
2016-08-02T04:58:25Z
38,712,103
<p>In order to support indexing, your Network class should have a <code>__getitem__()</code> method (<a href="http://docs.python.org/reference/datamodel.html#object.__getitem__" rel="nofollow">http://docs.python.org/reference/datamodel.html#object.<strong>getitem</strong></a>).</p>
1
2016-08-02T05:03:27Z
[ "python", "indexing" ]
Object indexing in python
38,712,056
<p>I have created the following objects in python</p> <p>It creates an object of class arc and then creates another object network using the object arc</p> <pre><code>class Arc: # Creates an object of class arc def __init__(self, tailNode = 0, headNode = 0, lowerBound = 0, upperBound = 0, cost = 0): s...
0
2016-08-02T04:58:25Z
38,712,572
<p>Assuming net[index] returns the arcList variable you can simply override your [] operator as such</p> <pre><code>class Network: def __getitem__(self,index): return arcList[index] </code></pre> <p>Printing a class needs a method as well. This might help you <a href="http://stackoverflow.com/questions/1...
0
2016-08-02T05:45:14Z
[ "python", "indexing" ]
Appending a list
38,712,204
<p>I am trying to append the "result" variable into a new list called total_winnings but I get an error.</p> <p>I managed to do it successfully for the total_stake but I get an error when I try use the same method for <code>total_winnings</code>.</p> <p>I think it is because the "result" variable takes string input?<...
1
2016-08-02T05:14:52Z
38,712,321
<p>The error you get is </p> <p><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'</code></p> <p>The problem is that you are currently storing strings <code>"Win"</code> and <code>"Lose"</code> in <code>my_list[3]</code> whereas you mean to store <code>stake * odds</code>. When you do the function <c...
0
2016-08-02T05:25:15Z
[ "python", "list", "append" ]
Appending a list
38,712,204
<p>I am trying to append the "result" variable into a new list called total_winnings but I get an error.</p> <p>I managed to do it successfully for the total_stake but I get an error when I try use the same method for <code>total_winnings</code>.</p> <p>I think it is because the "result" variable takes string input?<...
1
2016-08-02T05:14:52Z
38,712,333
<pre><code>result = (raw_input('Result: ')) </code></pre> <p><code>result</code> is a <code>str</code> (a string).</p> <pre><code>my_list=[selection,stake,odds,result,book] ... for my_list in inputs: total_winnings.append(my_list[3]) </code></pre> <p><code>my_list[3]</code> is <code>result</code>, which is a <co...
0
2016-08-02T05:26:28Z
[ "python", "list", "append" ]
Appending a list
38,712,204
<p>I am trying to append the "result" variable into a new list called total_winnings but I get an error.</p> <p>I managed to do it successfully for the total_stake but I get an error when I try use the same method for <code>total_winnings</code>.</p> <p>I think it is because the "result" variable takes string input?<...
1
2016-08-02T05:14:52Z
38,712,347
<p>I can see several issues with your code.</p> <p>First, defining a function ("def looks_good(inputs)") within a loop is not a good idea. Unless you're trying to do something relatively tricky, function definitions should be at the top level of your code, before other stuff.</p> <p>Second, the variable named "input...
0
2016-08-02T05:28:08Z
[ "python", "list", "append" ]
Appending a list
38,712,204
<p>I am trying to append the "result" variable into a new list called total_winnings but I get an error.</p> <p>I managed to do it successfully for the total_stake but I get an error when I try use the same method for <code>total_winnings</code>.</p> <p>I think it is because the "result" variable takes string input?<...
1
2016-08-02T05:14:52Z
38,712,419
<p>my_list[3] contains either Win of Lose i.e a string value and summing over it won't work. You can do something like this</p> <pre><code>result = (raw_input('Result: ')) result_val = stake*odds if result == "Win": print result_val elif result == "Lose": print 0 </code></pre> <p>And while...
0
2016-08-02T05:33:08Z
[ "python", "list", "append" ]
How can I link my DetailView and my ListView together?
38,712,209
<p>I'm building a demo-website for a local jewellery store, and I'm trying to create a list of jewellery brands (ListView) and link each to its description (DetailView) in another page. I've spent a solid 15 hours trying to link my ListView and my DetailView together and I haven't fixed anything. These are the views I'...
0
2016-08-02T05:15:23Z
38,721,497
<p>Your problem is in your url patterns. You have missed out the dollar from the end of your regex. That means that <code>/products/my-slug/</code> is matched by the regex for <code>BrandView</code> instead or <code>TextView</code>. Change it to:</p> <pre><code>url(r'^products/$', BrandView.as_view(), name = 'products...
0
2016-08-02T13:15:43Z
[ "python", "django", "listview", "detailview" ]
request.function in web2py
38,712,360
<p>What is <code>request.function</code> used for in <code>web2py</code> . I am a beginner to <code>web2y</code> and came across these lines in a tutorial </p> <pre><code>if not request.function=='first' and not session.visitor_name: redirect(URL('first')) </code></pre> <p>What is <code>request.function</code> us...
0
2016-08-02T05:28:51Z
38,716,012
<p>Taken from the <a href="http://web2py.com/books/default/chapter/29/04/the-core#request" rel="nofollow">documentation.</a> </p> <p><code>request.function: the name of the requested function.</code></p> <p>So in your case. </p> <pre><code>if not request.function=='first' and not session.visitor_name: redirect(U...
1
2016-08-02T08:58:48Z
[ "python", "web2py" ]
python map function with min argument and two lists
38,712,468
<p>Im having trouble figuring out why this map function is producing the output it's producing. The code is as follows:</p> <pre><code> L1 = [1, 28, 36] L2 = [2, 57, 9] print map(min, L1, L2) </code></pre> <p>output is: [1, 28, 9]</p> <p>I understand it took the min values from the first list, but...
2
2016-08-02T05:36:29Z
38,712,496
<p>The result is made up from</p> <pre><code>[min(L1[0], L2[0]), min(L1[1], L2[1]), min(L1[2], L2[2])] </code></pre> <p>so <code>min</code> is being called on each pair of values to construct the new list</p>
4
2016-08-02T05:38:41Z
[ "python" ]
python map function with min argument and two lists
38,712,468
<p>Im having trouble figuring out why this map function is producing the output it's producing. The code is as follows:</p> <pre><code> L1 = [1, 28, 36] L2 = [2, 57, 9] print map(min, L1, L2) </code></pre> <p>output is: [1, 28, 9]</p> <p>I understand it took the min values from the first list, but...
2
2016-08-02T05:36:29Z
38,712,500
<p><code>map(min, L1, L2)</code> means roughly this:</p> <pre><code>[min(L1[0], L2[0]), min(L1[1], L2[1]), min(L1[2], L2[2])] </code></pre> <p>So the min of [1,2] (first element of each list) is 1, min of [28,57] is 28, and min of [36,9] is 9.</p> <p>You probably wanted <code>map(min, [L1, L2])</code> instead.</p>
2
2016-08-02T05:39:09Z
[ "python" ]
python map function with min argument and two lists
38,712,468
<p>Im having trouble figuring out why this map function is producing the output it's producing. The code is as follows:</p> <pre><code> L1 = [1, 28, 36] L2 = [2, 57, 9] print map(min, L1, L2) </code></pre> <p>output is: [1, 28, 9]</p> <p>I understand it took the min values from the first list, but...
2
2016-08-02T05:36:29Z
38,712,513
<p>The statement:</p> <pre><code>map(min, L1, L2) </code></pre> <p>compares each elements of the two lists with <strong>the same index</strong>. </p> <p>Thus,<br> It performs:</p> <pre><code>list = [] list.append(min(1,2)) #1 list.append(min(28,57)) #28 list.append(min(36,9)) #9 print list </code></pre> <p>leading...
1
2016-08-02T05:40:04Z
[ "python" ]
python map function with min argument and two lists
38,712,468
<p>Im having trouble figuring out why this map function is producing the output it's producing. The code is as follows:</p> <pre><code> L1 = [1, 28, 36] L2 = [2, 57, 9] print map(min, L1, L2) </code></pre> <p>output is: [1, 28, 9]</p> <p>I understand it took the min values from the first list, but...
2
2016-08-02T05:36:29Z
38,712,650
<p>Let's take a look at <a href="https://docs.python.org/3.5/library/functions.html?highlight=map#map" rel="nofollow">the document</a>:</p> <blockquote> <p><code>map(function, iterable, ...)</code></p> <p>Return an iterator that applies function to every item of iterable, yielding the results. If additional i...
1
2016-08-02T05:51:47Z
[ "python" ]
I am trying to figure out what these temporary variables mean
38,712,567
<pre><code>def genfibon(n): #fib sequence until n a=1 b=1 for i in range n: yield a t=a a=b b=t+b </code></pre> <p>Can someone explain the t variable? It seems like <code>t=a</code> so then <code>a=b</code> and then <code>b=t</code> because <code>a=b</code> and <code>a=t</...
-1
2016-08-02T05:44:43Z
38,712,604
<p>Let's say a = 2 and b = 3.</p> <pre><code>t = a # now t = 2 a = b # now a = 3, but t is unchanged b = t + b # now b = 5 </code></pre> <p>The key is that second part. <code>t = a</code> means <code>t</code> gets the same value as <code>a</code>. It does not mean that <code>t</code> and <code>a</code> are now both t...
4
2016-08-02T05:48:27Z
[ "python" ]
I am trying to figure out what these temporary variables mean
38,712,567
<pre><code>def genfibon(n): #fib sequence until n a=1 b=1 for i in range n: yield a t=a a=b b=t+b </code></pre> <p>Can someone explain the t variable? It seems like <code>t=a</code> so then <code>a=b</code> and then <code>b=t</code> because <code>a=b</code> and <code>a=t</...
-1
2016-08-02T05:44:43Z
38,712,633
<p>Let us go statement by statement.</p> <ol> <li><code>t=a</code> means value of <code>a</code> is stored in <code>t</code>.</li> <li><code>a=b</code> means value of <code>b</code> is stored in <code>a</code>. (Thus <code>a</code> now contains the next element in the series)</li> <li><code>b=t+b</code> means value of...
1
2016-08-02T05:50:01Z
[ "python" ]
I am trying to figure out what these temporary variables mean
38,712,567
<pre><code>def genfibon(n): #fib sequence until n a=1 b=1 for i in range n: yield a t=a a=b b=t+b </code></pre> <p>Can someone explain the t variable? It seems like <code>t=a</code> so then <code>a=b</code> and then <code>b=t</code> because <code>a=b</code> and <code>a=t</...
-1
2016-08-02T05:44:43Z
38,712,653
<p>It's called swapping of variables. how do you replace the values of variables? </p> <p>as @smarx said, when <code>a = 2</code> and <code>b = 3</code>, how do you make it <code>a = 3</code> and <code>b = 2</code>?</p> <p>when you do <code>a = 3</code>, the old value of a(2) is lost so you wont know what to set b wi...
2
2016-08-02T05:52:27Z
[ "python" ]
I am trying to figure out what these temporary variables mean
38,712,567
<pre><code>def genfibon(n): #fib sequence until n a=1 b=1 for i in range n: yield a t=a a=b b=t+b </code></pre> <p>Can someone explain the t variable? It seems like <code>t=a</code> so then <code>a=b</code> and then <code>b=t</code> because <code>a=b</code> and <code>a=t</...
-1
2016-08-02T05:44:43Z
38,712,993
<p>In your first run </p> <pre><code>yield a # will return 1 t = a # which is 1 a = b # which is 1 b = t + b # which is 2 as t = 1 and b = 1 </code></pre> <p>In your 2nd run</p> <pre><code>yield a # will return 1 t = a # which is 1 a = b # which is 2 b = t + b # which is 3 as t = 1 and b = 2 </code></pre> ...
2
2016-08-02T06:15:20Z
[ "python" ]
Capturing the order of occurrence of an ID in dataframe using Python
38,712,595
<p>I have a dataframe like this:</p> <pre><code>ID Product 10001 A 10001 B 10001 C 10002 D 10002 A 10001 F 10001 X 10002 N </code></pre> <p>What I want in output is order of occurrence of a distinct ID in co...
0
2016-08-02T05:47:47Z
38,718,140
<p>This builds groups of lines with the same ID, remembers the occurrences and add the group size at the end. </p> <pre><code>def occCount(db): occ = {} last = db[0][0] if db != [] else None group = [] res = [] for i, p in db: if i not in occ.keys(): occ[i] = 0 # Add ite...
1
2016-08-02T10:37:07Z
[ "python", "data-manipulation" ]
Writing list of tuples to a textfile and reading back into a list
38,712,635
<p>How do I write a list of tuples to a text file and read them back into the original list format?</p> <p>My code gives:</p> <pre><code>["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"] </code></pre> <p>My code:</p> <pre><code>file = open("x.txt", "w") default_scores = [(10, "EE...
2
2016-08-02T05:50:09Z
38,712,681
<p>If your purpose is to read the lines without the newline characters, you can change that after reading the lines with a simple for loop:</p> <pre><code>lines = file.readlines() lines = [line[:-1] for line in lines] </code></pre> <p>Or of course, you could read the file and split lines using <code>str.splitlines</c...
0
2016-08-02T05:54:41Z
[ "python", "tuples", "text-files" ]
Writing list of tuples to a textfile and reading back into a list
38,712,635
<p>How do I write a list of tuples to a text file and read them back into the original list format?</p> <p>My code gives:</p> <pre><code>["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"] </code></pre> <p>My code:</p> <pre><code>file = open("x.txt", "w") default_scores = [(10, "EE...
2
2016-08-02T05:50:09Z
38,712,829
<p>Just delete the '\n' character and append everything into a new list</p> <pre><code>x = [] for i in lines: i = i.replace("\n","") x.append(i) lines = x </code></pre>
0
2016-08-02T06:03:39Z
[ "python", "tuples", "text-files" ]
Writing list of tuples to a textfile and reading back into a list
38,712,635
<p>How do I write a list of tuples to a text file and read them back into the original list format?</p> <p>My code gives:</p> <pre><code>["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"] </code></pre> <p>My code:</p> <pre><code>file = open("x.txt", "w") default_scores = [(10, "EE...
2
2016-08-02T05:50:09Z
38,712,837
<p>You can use a list comprehension to convert the list returned by file.readlines() into list of tuples -</p> <p><strong>lines = [ast.literal_eval(line.strip()) for line in file.readlines()]</strong></p> <p>I have used ast.literal_eval to convert string into tuple. read more about ast.literal_eval <a href="https://d...
2
2016-08-02T06:04:23Z
[ "python", "tuples", "text-files" ]
Writing list of tuples to a textfile and reading back into a list
38,712,635
<p>How do I write a list of tuples to a text file and read them back into the original list format?</p> <p>My code gives:</p> <pre><code>["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"] </code></pre> <p>My code:</p> <pre><code>file = open("x.txt", "w") default_scores = [(10, "EE...
2
2016-08-02T05:50:09Z
38,712,844
<p>If you want to write a data-structure to a file and get it back (without mixing it with other contents) you can use (de)serialization with <a href="https://docs.python.org/3/library/pickle.html#examples" rel="nofollow">pickle</a>:</p> <pre><code>import pickle pickle.dump(default_scores, open('tuple.dump', 'wb')) re...
4
2016-08-02T06:04:50Z
[ "python", "tuples", "text-files" ]
Writing list of tuples to a textfile and reading back into a list
38,712,635
<p>How do I write a list of tuples to a text file and read them back into the original list format?</p> <p>My code gives:</p> <pre><code>["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"] </code></pre> <p>My code:</p> <pre><code>file = open("x.txt", "w") default_scores = [(10, "EE...
2
2016-08-02T05:50:09Z
38,712,853
<p>It seems that <a href="https://docs.python.org/3/library/json.html" rel="nofollow">json</a> is suitable for the task :</p> <pre><code>default_scores = [(10, "EEE"), (20, "DDD"), (30, "CCC"), (40, "BBB"), (50, "AAA")] import json with open('scores.txt','w') as ff: json.dump(default_scores ,ff ) with open('score...
1
2016-08-02T06:05:16Z
[ "python", "tuples", "text-files" ]
Writing list of tuples to a textfile and reading back into a list
38,712,635
<p>How do I write a list of tuples to a text file and read them back into the original list format?</p> <p>My code gives:</p> <pre><code>["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"] </code></pre> <p>My code:</p> <pre><code>file = open("x.txt", "w") default_scores = [(10, "EE...
2
2016-08-02T05:50:09Z
38,712,943
<p>If it's a file used only internally for your program to store an later retrieve the data you can use a simpler approach:</p> <pre><code># Save data to disk with open("mydata.dat", "w") as f: f.write(repr(data)) ... # Read back from disk with open("mydata.dat") as f: data = eval(f.read()) </code></pre> <p...
1
2016-08-02T06:11:45Z
[ "python", "tuples", "text-files" ]
Bind event to wx.button directy using wx.EVT_BUTTON?
38,712,807
<p>I read several wxPython books and am now quite familiar with binding a button with an event. Such as in a wx.Frame's __init__ method, I wrote:</p> <pre><code>self.btn = wx.Button(self, 2, "click me") self.btn.bind(wx.EVT_BUTTON, self.onclick) </code></pre> <p>where <code>onclick</code> is something need to do when...
0
2016-08-02T06:02:18Z
38,714,084
<p>Paul's comment is correct, but here is some more information:</p> <p>To answer #1, no it will not be garbage collected. The parent window owns the C++ part of the button object, which in turn has a reference to the Python part of the button object. So the Python object will continue to exist as long as the C++ obje...
1
2016-08-02T07:19:29Z
[ "python", "wxpython" ]
Incomplete Gamma function in scipy
38,713,199
<p>I would like to compute what wolfram alpha calls the incomplete gamma function <a href="http://www.wolframalpha.com/input/?i=Gamma%5B0,%200.1%5D" rel="nofollow">(see here)</a>:</p> <pre><code>`gamma[0, 0.1]` </code></pre> <p>The wolfram alpha output is <code>1.822</code>. The only thing <code>scipy</code> gives me...
1
2016-08-02T06:29:44Z
38,715,054
<p>According to <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.special.gammainc.html" rel="nofollow">http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.special.gammainc.html</a>, the first argument must be positive, whereas you have zero; that's why you're getting NaN.</p> <p>T...
2
2016-08-02T08:09:28Z
[ "python", "scipy" ]
How do I turn a dataframe into a series of lists?
38,713,200
<p>I have had to do this several times and I'm always frustrated. I have a dataframe:</p> <pre><code>df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'], ['A', 'B', 'C', 'D']) print df A B C D a 1 2 3 4 b 5 6 7 8 </code></pre> <p>I want to turn <code>df</code> into:</p> <pre><code>pd.Series([...
17
2016-08-02T06:29:48Z
38,713,212
<p>pandas tries really hard to make making dataframes convenient. As such, it interprets lists and arrays as things you'd want to split into columns. I'm not going to complain, this is almost always helpful.</p> <p>I've done this one of two ways.</p> <p><strong><em>Option 1</em></strong>:</p> <pre><code># Only wor...
7
2016-08-02T06:30:33Z
[ "python", "list", "pandas", "dataframe" ]
How do I turn a dataframe into a series of lists?
38,713,200
<p>I have had to do this several times and I'm always frustrated. I have a dataframe:</p> <pre><code>df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'], ['A', 'B', 'C', 'D']) print df A B C D a 1 2 3 4 b 5 6 7 8 </code></pre> <p>I want to turn <code>df</code> into:</p> <pre><code>pd.Series([...
17
2016-08-02T06:29:48Z
38,713,387
<p>You can first convert <code>DataFrame</code> to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html"><code>values</code></a>, then convert to list and last create new <code>Series</code> with index from <code>df</code> if need faster solution:</p> ...
11
2016-08-02T06:41:55Z
[ "python", "list", "pandas", "dataframe" ]
How do I turn a dataframe into a series of lists?
38,713,200
<p>I have had to do this several times and I'm always frustrated. I have a dataframe:</p> <pre><code>df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'], ['A', 'B', 'C', 'D']) print df A B C D a 1 2 3 4 b 5 6 7 8 </code></pre> <p>I want to turn <code>df</code> into:</p> <pre><code>pd.Series([...
17
2016-08-02T06:29:48Z
38,715,865
<p>Dataframe to list conversion</p> <pre><code>List_name =df_name.values.tolist() </code></pre>
0
2016-08-02T08:51:37Z
[ "python", "list", "pandas", "dataframe" ]
customised loss function in keras using theano function
38,713,407
<p>I'd like to use my own binary_crossentropy instead of using the one that comes with Keras library. Here is my custom function:</p> <pre><code> import theano from keras import backend as K def elementwise_multiply(a, b): # a and b are tensors c = a * b return theano.function([a, b], c) ...
0
2016-08-02T06:43:08Z
38,732,069
<p>I found the problem. I had to multiply the return value by "-1" as I'm using stochastic gradient decedent (sgd) as optimiser and not stochastic gradient ascent!</p> <p>Here is the code and it works like a charm:</p> <pre><code>import theano from keras import backend as K def custom_objective(y_true, y_pred): ...
0
2016-08-02T23:33:24Z
[ "python", "theano", "keras" ]
Python/Numpy: Conditional simulation from a multivatiate distribution
38,713,746
<p>Using numpy I can simulate unconditionally from a multivariate normal distribution by</p> <pre><code>mean = [0, 0] cov = [[1, 0], [0, 100]] # diagonal covariance x, y = np.random.multivariate_normal(mean, cov, 5000).T </code></pre> <p>How do I simulate y from the same distribution, given that I have 5000 realizat...
2
2016-08-02T07:02:48Z
38,718,317
<p>Looking up in Eaton, Morris L. (1983). Multivariate Statistics: a Vector Space Approach, I gathered following example solution for a 4 vaiable system, with 2 dependent variables (the first two) and 2 independent variables (the last two)</p> <pre><code>import numpy as np mean = np.array([1, 2, 3, 4]) cov = np.array...
1
2016-08-02T10:46:21Z
[ "python", "numpy", "simulation" ]
Eclipse Raspberry Pi 3 remote debugging ImportError: No module named 'bluetooth'
38,713,816
<p>I am trying to do a Bluetooth scan on my Raspberry pi 3. I am using eclipse remote debugging for coding. Python version is 3.4</p> <pre><code>import sys sys.path.append(r'C:\Users\SachithW\Downloads\eclipse-java-mars-2-win32-x86_64\eclipse\plugins\org.python.pydev_5.1.2.201606231256\pysrc') import pydevd pydevd.s...
-1
2016-08-02T07:06:10Z
38,715,831
<p>Did you do this:</p> <pre><code>sudo apt-get install python-bluez </code></pre> <p>I have also seen this in tutorials:</p> <pre><code>pip install pybluez </code></pre>
0
2016-08-02T08:49:46Z
[ "python", "eclipse", "bluetooth", "raspberry-pi", "remote-debugging" ]
Cython: invalid operand types
38,713,913
<p>I have a C++ class implementation which I want to expose to Python with Cython. The class interface is something like this (each operator's implementation involves some private attributes so they cannot be inline implementations):</p> <pre><code>class Quantity { private: // Some implementation -- public: ex...
1
2016-08-02T07:12:00Z
38,714,675
<p>Multiple <code>__cinit__</code> is not allowed as far as I remember</p> <pre><code>def __cinit__(PyQuantity self, ... ): self._thisptr = new Quantity(...) def __cinit__(PyQuantity self, Quantity ot): self._thisptr = new Quantity(ot) </code></pre> <p>Arguments to <code>__cinit__</code> should be python obj...
0
2016-08-02T07:49:46Z
[ "python", "c++", "cython" ]
Cython: invalid operand types
38,713,913
<p>I have a C++ class implementation which I want to expose to Python with Cython. The class interface is something like this (each operator's implementation involves some private attributes so they cannot be inline implementations):</p> <pre><code>class Quantity { private: // Some implementation -- public: ex...
1
2016-08-02T07:12:00Z
38,721,939
<p>A slightly modified version of the accepted answer actually works. The problem with that was += is not implemented (for a reason) so <code>nobj._thisptr[0] = self._thisptr[0] + other._thisptr[0]</code> was used, but this causes segmentation errors - obviously, since the resulting Quantity object is not heap alo...
0
2016-08-02T13:32:30Z
[ "python", "c++", "cython" ]
django time checker database
38,713,931
<p>I am trying to create a thread function that allow me to check a database field in order to see if the time.now() is bigger than the one recorded in the database(postgresql); the problem is that the view.py where I am calling this, is blocked by this thread, this is my actual code:</p> <p>PD: expire_pet is a text f...
0
2016-08-02T07:13:04Z
38,714,792
<p>It works, the problem was that I have been calling the run in the wrong place, thanks</p>
0
2016-08-02T07:56:22Z
[ "python", "django", "postgresql", "python-multithreading" ]
Python 3 - IndexError: list index out of range when trying to find determinant of a matrix
38,713,967
<p>I am trying to find determinant with a nested list representing a two-dimensional matrix. But it is infinitely calling the getMinor() function and continuously deleting from the same list, which should not happend because I am creating new list every time. Below is the code. Also all the functions are defined in a c...
0
2016-08-02T07:14:36Z
38,715,359
<p>You have two problems. One is alluded to by user2357112 who unfortunately didn't bother to explain. When you use the expression x[:] you get a shallow copy of the list x. Often there is no practical difference between deep and shallow copies; for example if x contains numbers or strings. But in your case the ele...
1
2016-08-02T08:26:01Z
[ "python", "python-3.x", "math", "matrix" ]
Groupby, pivot and concatenate in Pandas, breaking by date?
38,714,057
<p>I have a dataframe which looks like this:</p> <pre><code>df = pd.DataFrame([ [123, 'abc', '121'], [123, 'abc', '121'], [456, 'def', '121'], [123, 'abc', '122'], [123, 'abc', '122'], [456, 'def', '145'], [456, 'def', '145'], [456, 'def', '121'], ], ...
0
2016-08-02T07:18:24Z
38,714,277
<p>Try:</p> <pre><code>def tweak(df): return df.reset_index().name df.set_index('userid').groupby(level=0).apply(tweak) </code></pre> <hr> <h3>Demonstration</h3> <pre><code>df = pd.DataFrame([[1, 'a'], [1, 'c'], [1, 'c'], [1, 'd'], [1, 'e'], [1, 'a'], [1, 'c'], [1, 'c'], [1, 'd'], [1, 'e'], ...
0
2016-08-02T07:28:47Z
[ "python", "pandas" ]
Pyhon:Generate a variable inside a for loop
38,714,076
<p>I am trying to generate and save an image with a new name for each loop.Is this possible in python with a for loop?Or should I try a different approach?</p> <pre><code>For i in range(x,y) i=str(i) p= img(i).save(s+i+j,) i=int('i') i=i+1 </code></pre>
2
2016-08-02T07:19:12Z
38,714,149
<pre><code>from PIL import Image images = [...] # create some images for i, image in enumerate(images): image.save('image_%03d.png' % i) </code></pre>
0
2016-08-02T07:22:09Z
[ "python", "for-loop", "image-processing", "image-generation" ]
How to detect 01-Jan-01 dates in pandas from csv
38,714,207
<p>I have the following csv, saved as <code>test.txt</code>:</p> <pre><code>title, arbitrarydate, value hello, 01-Jan-01, 314159 </code></pre> <p>running the following code</p> <pre><code>dataframe = pd.read_csv('pandatestcsv.txt', parse_dates = True) print dataframe.dtypes </code></pre> <p>gives this output </p> ...
0
2016-08-02T07:24:53Z
38,714,234
<p>For me works:</p> <pre><code>import pandas as pd import io temp=u"""title,arbitrarydate,value hello,01-Jan-01,314159""" #after testing replace io.StringIO(temp) to filename df = pd.read_csv(io.StringIO(temp), parse_dates=['arbitrarydate']) print (df) title arbitrarydate value 0 hello 2001-01-01 314159 p...
0
2016-08-02T07:26:15Z
[ "python", "csv", "pandas" ]
Pandas DataFrame grouping to generate numerical multi-index
38,714,254
<p>I would like to apply a group by operation to a Pandas DataFrame without performing any aggregation. Instead, I just want the hierarchical structure to be reflected in the MultiIndex.</p> <pre><code>import pandas as pd def multi_index_group_by(df, columns): # TODO: How to write this? (Hard-coded to give the de...
3
2016-08-02T07:27:37Z
38,716,324
<p>This code does what you want:</p> <pre><code>index_columns = [] replace_values = {} index_columns += ["b"] replace_values.update({'b0':0, 'b1':1}) df[['idx_{}'.format(i) for i in index_columns]] = df[index_columns].replace(replace_values) print(df.set_index(['idx_{}'.format(i) for i in index_columns], drop=True))...
1
2016-08-02T09:13:28Z
[ "python", "pandas", "grouping" ]
Pandas DataFrame grouping to generate numerical multi-index
38,714,254
<p>I would like to apply a group by operation to a Pandas DataFrame without performing any aggregation. Instead, I just want the hierarchical structure to be reflected in the MultiIndex.</p> <pre><code>import pandas as pd def multi_index_group_by(df, columns): # TODO: How to write this? (Hard-coded to give the de...
3
2016-08-02T07:27:37Z
38,717,841
<p>if you are willing to use the <a href="http://scikit-learn.org/stable/" rel="nofollow">sklearn</a> package you could use the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow">LabelEncoder</a>:</p> <pre><code>from sklearn.preprocessing import LabelEncod...
2
2016-08-02T10:24:32Z
[ "python", "pandas", "grouping" ]
How do I trim a .fits image and keep world coordinates for plotting in astropy Python?
38,714,293
<p>This issue has been plaguing me for some time. I'm trying to handle some large amount of data that is in the form of a .fits file (on the order of 11000x9000 pixels). What I need to do is create a 'zoomed in' RA/Dec coordinate plot (ideally using astropy.wcs) for many objects on the sky with contours from one fits f...
2
2016-08-02T07:29:38Z
38,716,117
<p>The good news is: You can simply slice your <code>astropy.WCS</code> as well which makes your task relativly trivial:</p> <pre><code>... wmapcut = wmap[250:650, 250:650] # sliced here datacut = data[250:650, 250:650] ax2 = fig.add_subplot(122, projection=wmapcut) # use sliced wcs as projection ax2.imshow(datacut, ...
4
2016-08-02T09:03:07Z
[ "python", "python-2.7", "astronomy", "astropy" ]
How to Assign Values to Tensorflow SubTensor?
38,714,440
<p>I have a tensorfow constant</p> <pre><code>x = tf.zeros((N * (T - n + 1), n, D)) </code></pre> <p>I have a tensorflow placeholder:</p> <pre><code>X = tf.placeholder(tf.float32, shape=(None, None, n_in)) </code></pre> <p>And I want to assign some valued of X to x, in numpy I would do:</p> <pre><code>x[N * i:N * ...
0
2016-08-02T07:37:02Z
38,715,198
<p>I'd assign array chunks with <code>numpy</code> and then converting back to <code>tensorflow</code>:</p> <pre><code>with tf.Session() as sess: #some tf operations here # ... x_np = np.array(sess.run(x)) X_np = np.array(sess.run(X)) #assign with numpy: x_np[N * i:N * (i + 1), :, :...
1
2016-08-02T08:18:32Z
[ "python", "tensorflow", "subset", "variable-assignment" ]
Monitor new appended rows and create a ; separated file for each row
38,714,470
<p>I have a csv file on a linux server that has new rows appended in random times (can be every 1 sec and can be 2 hours with no new rows). The file looks as follows:</p> <pre><code>KEY PREDICTION FIRST NAME LAST NAME aaaaaa 0 john doe bbbbbb 1 jane doe cccccc 1 michael michael...
-4
2016-08-02T07:39:24Z
38,714,901
<p>I would recommend looking at <a href="http://www.dabeaz.com/generators/" rel="nofollow">David's generator tricks from python</a> . A sample program that would achieve your objective would be something like:</p> <pre><code>import time import csv def follow(thefile): thefile.seek(0,2) while True: line...
0
2016-08-02T08:01:24Z
[ "python", "python-2.7", "pandas" ]
tensorflow - memory leak?
38,714,557
<p>I'm running tensorflow 0.10.0rc0 on OSX 10.9.5 Mavericks.</p> <p>There are approximately 25k training examples, 250 features (x), 15 classes (y_) and the predict (y) is a single-hidden-layer NN perceptron.</p> <p>The following snippet of a simple training loop seems to have a massive memory leak (of order 10s of G...
1
2016-08-02T07:44:00Z
38,716,814
<ol> <li>Its unnecessary to run <code>sess.run(correct_prediction)</code> -- it's a tensorflow graph variable on which the <code>accuracy</code> variable is dependant. This implies that it will be evaluated during the call to <code>sess.run(accuracy)</code> in any case.</li> <li>You're probably modifying your graph by ...
1
2016-08-02T09:35:58Z
[ "python", "memory-leaks", "tensorflow" ]
How To Avoid Logic In Template?
38,714,607
<p>I'm trying to develop a forum application.</p> <p>I'm trying to display the latest topic that's been posted in each category on a listing page. However, I realised after adding more than one category that I need a separate query for each single category or it just shows the newest topic overall.</p> <p>I'm just no...
0
2016-08-02T07:46:25Z
38,717,708
<p>You can create a custom template tag that returns the latest post for each category.</p> <p>Something like this:</p> <pre><code># views.py def index(req): categories = ForumCategory.objects.all() return render(req, "forum/category_listing.html", {'categories': categories}) # templatetags/category_tags.py ...
0
2016-08-02T10:17:40Z
[ "python", "django" ]
Python string literals - including single quote as well as double quotes in string
38,714,701
<p>I want to join this series of strings:</p> <pre><code>my_str='"hello!"' + " it's" + ' there' </code></pre> <p>Want the result to be: </p> <pre><code>my_str Out[65]: '"hello!" it's there' </code></pre> <p>But I get:</p> <pre><code>my_str Out[65]: '"hello!" it\'s there' </code></pre> <p>I have tried a few iterat...
1
2016-08-02T07:50:56Z
38,714,774
<p>The result is correct. Single quotes have to be escaped in single quoted strings. The same for double quotes.</p> <p>If you try <code>print</code> the result, you'll see that it's as you expected.</p> <pre><code>&gt;&gt;&gt; print(my_str) "hello!" it's there </code></pre>
3
2016-08-02T07:54:48Z
[ "python" ]
Python string literals - including single quote as well as double quotes in string
38,714,701
<p>I want to join this series of strings:</p> <pre><code>my_str='"hello!"' + " it's" + ' there' </code></pre> <p>Want the result to be: </p> <pre><code>my_str Out[65]: '"hello!" it's there' </code></pre> <p>But I get:</p> <pre><code>my_str Out[65]: '"hello!" it\'s there' </code></pre> <p>I have tried a few iterat...
1
2016-08-02T07:50:56Z
38,715,024
<p>if you use <code>print</code> command you will see as you want...</p> <pre><code>&gt;&gt;&gt; my_str='"hello!"' + " it's" + ' there' &gt;&gt;&gt; my_str '"hello!" it\'s there' #Count printed characters. You will count 22 &gt;&gt;&gt; print my_str "hello!" it's there #Now count characters. 19 &gt;&gt;&gt; len(my_str...
2
2016-08-02T08:08:12Z
[ "python" ]
Python string literals - including single quote as well as double quotes in string
38,714,701
<p>I want to join this series of strings:</p> <pre><code>my_str='"hello!"' + " it's" + ' there' </code></pre> <p>Want the result to be: </p> <pre><code>my_str Out[65]: '"hello!" it's there' </code></pre> <p>But I get:</p> <pre><code>my_str Out[65]: '"hello!" it\'s there' </code></pre> <p>I have tried a few iterat...
1
2016-08-02T07:50:56Z
38,715,205
<p><code>print my_str</code> will print your string as</p> <p><code>'"hello!" it's there'</code></p> <p>You can also do that stuff in another way using <code>my_str.decode('ascii')</code></p> <pre><code>new_str = my_str.decode('ascii') print new_str </code></pre> <p>It will print the string as:</p> <p><code>"hello...
0
2016-08-02T08:18:57Z
[ "python" ]
OpenERP/Odoo - Quote inside a string is not working - cr.execute(SQL)
38,714,803
<p>In OpenERP 7 , I am using a cr.execute to execute a SQL Request</p> <pre><code>cr.execute('select distinct(value) from ir_translation where name = \'product.bat3,name\' and src = \''+ str(res_bat[j][0].encode('utf-8'))+'\' and res_id = '+ str(res_bat[j][1])+' and lang = \''+ str(line2.partner_id.lang)+'\'') </code>...
1
2016-08-02T07:56:44Z
38,718,459
<p>you must not perform the substitutions yourself in a SQL query as this makes your code vulnerable to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injections</a>. </p> <p>The correct version is:</p> <pre><code>cr.execute( 'select distinct(value) from ir_translation ' 'where name ...
1
2016-08-02T10:53:38Z
[ "python", "sql", "openerp" ]
Django database to postgresql
38,714,806
<p>There are around 5000 companies and each company has around 4500 prices, that makes a total of around 22,000,000 prices.</p> <p>Now a while ago, I wrote a code that stored this data in a format like this-</p> <pre><code>class Endday(models.Model): company = models.TextField(null=True) eop = models.CommaSeparat...
0
2016-08-02T07:56:56Z
38,716,608
<p>I think you can create a separate model for <code>Company</code>and <code>Price</code> something like this:</p> <pre><code>class Company(models.Model): name = models.CharField(max_length=20) class Price(models.Model): company = models.ForeignKey(Company, related_name='prices') price = models.FloatField...
0
2016-08-02T09:27:12Z
[ "python", "mysql", "django", "database", "postgresql" ]
Alternating Least Square error in pyspark
38,714,937
<p>I've been trying to train model based on ALS using pyspark.ALS.recommendation. Code : </p> <pre><code>from pyspark.ALS.recommendation import ALS model=ALS.train(trainingset,rank=8,seed=0,iterations=10,lambda_=0.1) </code></pre> <p>But I am getting this following error : </p> <pre><code>invalid literal for int() ...
1
2016-08-02T08:03:18Z
38,715,386
<p>Well, the error message means you are passing some 'userId' <strong>text where a number is expected</strong>. Without further information (like full error message or the stacktrace) is hard to say what exactly the problem is.</p> <p>EDIT: As mentioned in the comments, it turns out you have the 'header' row from CSV...
0
2016-08-02T08:27:15Z
[ "python", "pyspark" ]
Understanding Keras LSTMs
38,714,959
<p>I am trying to reconcile my understand of LSTMs and pointed out here: <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">http://colah.github.io/posts/2015-08-Understanding-LSTMs/</a> with the LSTM implemented in Keras. I am following the blog written <a href="http://machinelearningmastery.com/time-s...
15
2016-08-02T08:04:13Z
38,737,941
<p>First of all, you choose great tutorials(<a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">1</a>,<a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">2</a>) to start.</p> <p><strong>What Time-step means</strong>: <code>Time-steps==3</code> in X.shape (Describing data shape) means ther...
7
2016-08-03T08:09:59Z
[ "python", "deep-learning", "keras", "lstm" ]
how can i update an alfresco share site?
38,714,974
<p>I am trying to update a website (just change its name) I have created with the Share script in Alfresco, but I am getting a <code>401</code> response. I'm sure my login and password are correct.</p> <p>Code: </p> <pre><code>s = requests.Session() data = {'username':"admin", 'password':"admin"} url = "http://127.0....
0
2016-08-02T08:05:01Z
38,719,300
<p>This is because you are using different contexts to make your queries.</p> <p>The Alfresco stack is made of multiples parts :</p> <ul> <li>alfresco.war</li> <li>share.war</li> <li>solr.war</li> </ul> <p>If we forget the solr part and focus on your problem, you have :</p> <ul> <li>a <strong>content repository</st...
2
2016-08-02T11:33:49Z
[ "python", "alfresco", "alfresco-webscripts" ]
Run multiple unittest tes tfiles at once
38,715,036
<p>In my project I created a unittest test file for each Python file. For example, I have file <code>component.py</code> and its accompanying <code>test_component.py</code>. Similarly for <code>path.py</code> and <code>test_path.py</code>, etc.</p> <p>However, since these files depend on each other it is possible that...
0
2016-08-02T08:08:49Z
38,727,892
<p>I would recommend using <a href="http://docs.pytest.org/en/latest/" rel="nofollow">Pytest</a>. </p> <p>Another alternative is to have a separate file that calls tests or instantiates classes from each test file. Based on the returns it calls the next test. </p> <p>You also might have a need store information in a ...
1
2016-08-02T18:25:32Z
[ "python", "unit-testing", "testing", "pycharm" ]
Run multiple unittest tes tfiles at once
38,715,036
<p>In my project I created a unittest test file for each Python file. For example, I have file <code>component.py</code> and its accompanying <code>test_component.py</code>. Similarly for <code>path.py</code> and <code>test_path.py</code>, etc.</p> <p>However, since these files depend on each other it is possible that...
0
2016-08-02T08:08:49Z
38,768,038
<p>It's possible to run all tests located in some folder.</p> <p>Go to <code>Run - Edit Configurations</code>, select or create run configuration for tests and specify path to folder.</p> <p><a href="http://i.stack.imgur.com/2aQja.png" rel="nofollow"><img src="http://i.stack.imgur.com/2aQja.png" alt="enter image desc...
1
2016-08-04T12:58:26Z
[ "python", "unit-testing", "testing", "pycharm" ]
Converting Disassembled Python Bytecode back into Source Code
38,715,149
<p>This is not traditional bytecode but rather disassembled bytecode, no compiler is built to compile this code.</p> <p>I have been given an encoder to reverse engineer. This encoder however was disassembled and put into human-readable form. I have so-far rewritten the majority of the code back into source code but ha...
0
2016-08-02T08:15:39Z
38,715,958
<p>You really want to automate this rather than do this by hand; there are some tools like <code>decompyle</code> and <code>uncompyle</code> that can produce Python source code from bytecode.</p> <p>Your bytecode from the code objects are somewhat jumbled up, and we are missing the <code>co_argcount</code> and <code>c...
2
2016-08-02T08:55:34Z
[ "python", "reverse-engineering", "bytecode" ]
Scikit Learn - Extract word tokens from a string delimiter using CountVectorizer
38,715,212
<p>I have list of strings. If any string contains the <em>'#'</em> character then I want to extract the first part of the string and get the frequency count of word tokens from this part of string only. i.e if the string is <em>"first question # on stackoverflow"</em> expected tokens are <em>"first","question"</em></p>...
4
2016-08-02T08:19:13Z
38,716,512
<p>The problem lays with your tokenizer, you've split the string into the bits you want to keep and the bits you don't want to keep, but you've not split the string into words. Try using the tokenizer below</p> <pre><code>class MyTokenizer(object): def __call__(self,s): if(s.find('#')==-1): ret...
2
2016-08-02T09:21:50Z
[ "python", "machine-learning", "scikit-learn" ]
Scikit Learn - Extract word tokens from a string delimiter using CountVectorizer
38,715,212
<p>I have list of strings. If any string contains the <em>'#'</em> character then I want to extract the first part of the string and get the frequency count of word tokens from this part of string only. i.e if the string is <em>"first question # on stackoverflow"</em> expected tokens are <em>"first","question"</em></p>...
4
2016-08-02T08:19:13Z
38,716,682
<p>You could split on your separator(<code>#</code>) at most once and take the first part of the split.</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer def tokenize(text): return([text.split('#', 1)[0].strip()]) text = ["first ques # on stackoverflow", "please help"] vec = CountVector...
2
2016-08-02T09:30:16Z
[ "python", "machine-learning", "scikit-learn" ]
Scikit Learn - Extract word tokens from a string delimiter using CountVectorizer
38,715,212
<p>I have list of strings. If any string contains the <em>'#'</em> character then I want to extract the first part of the string and get the frequency count of word tokens from this part of string only. i.e if the string is <em>"first question # on stackoverflow"</em> expected tokens are <em>"first","question"</em></p>...
4
2016-08-02T08:19:13Z
38,717,160
<pre><code> s.split('#',1)[0] </code></pre> <p><code>#</code> is your result. you dont need check that "#" is exist or not.</p>
0
2016-08-02T09:51:46Z
[ "python", "machine-learning", "scikit-learn" ]
Multiply each column from 2D array with each column from another 2D array
38,715,287
<p>I have two Numpy arrays <code>x</code> with shape <code>(m, i)</code> and <code>y</code> with shape <code>(m, j)</code> (so the number of rows is the same). I would like to multiply each column of <code>x</code> with each column of <code>y</code> element-wise so that the result is of shape <code>(m, i*j)</code>.</p>...
4
2016-08-02T08:22:49Z
38,715,383
<p>Use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p> <pre><code>(y[:,None]*x[...,None]).reshape(x.shape[0],-1) </code></pre> <p><strong>Explanation</strong></p> <p>As inputs, we have -</p> <pre><code>y : 10 x 2 x : 10 x 3 </code></pr...
6
2016-08-02T08:26:57Z
[ "python", "numpy", "vectorization" ]
Matrix of Key-Value Pairs / Dict
38,715,321
<p>I have several objects from <code>type dict</code> with different keys. I want to create a table <code>with all keys</code> and foreach object one row. If one key isn't available, it should be empty.</p> <p>For Example:</p> <pre><code>x1=dict( {"a":2, "b":3}) x2=dict( {"a":2, "b":3, "c":2}) </code></pre> <p>and i...
0
2016-08-02T08:24:26Z
38,715,541
<p>If you use pandas, you can do this:</p> <pre><code>import pandas as pd df = pd.DataFrame({k: [v] for k, v in x1.iteritems()}) df2 = pd.DataFrame({k: [v] for k, v in x2.iteritems()}) df = pd.concat((df, df2), ignore_index=True) # a b c # 0 2 3 NaN # 1 2 3 2 </code></pre> <p>Note: <code>iteritems()</co...
1
2016-08-02T08:35:52Z
[ "python" ]
Matrix of Key-Value Pairs / Dict
38,715,321
<p>I have several objects from <code>type dict</code> with different keys. I want to create a table <code>with all keys</code> and foreach object one row. If one key isn't available, it should be empty.</p> <p>For Example:</p> <pre><code>x1=dict( {"a":2, "b":3}) x2=dict( {"a":2, "b":3, "c":2}) </code></pre> <p>and i...
0
2016-08-02T08:24:26Z
38,715,663
<p>As a general approach (I am assuming you have a list of dicts, here, and you are fine with having the columns in "asciibetical" order):</p> <pre><code>def EmitDictsAsCSV(list_of_dicts): # First, accumulate the full set of dict keys key_set = set() for d in list_of_dicts: key_set.update(d.iterkeys()) #...
0
2016-08-02T08:42:39Z
[ "python" ]
Matrix of Key-Value Pairs / Dict
38,715,321
<p>I have several objects from <code>type dict</code> with different keys. I want to create a table <code>with all keys</code> and foreach object one row. If one key isn't available, it should be empty.</p> <p>For Example:</p> <pre><code>x1=dict( {"a":2, "b":3}) x2=dict( {"a":2, "b":3, "c":2}) </code></pre> <p>and i...
0
2016-08-02T08:24:26Z
38,715,806
<p>Here is another simple solution that does not use <code>pandas</code>:</p> <pre><code>all_dics = [x1, x2] keys = set(key for d in all_dics for key in d) # {'a', 'b', 'c'} dic = {key: [None]*len(all_dics) for key in keys} # {'a': [None, None], 'b': [None, None], 'c': [None, None]} for j, d in enumerate(all_dics): ...
0
2016-08-02T08:49:01Z
[ "python" ]
Matrix of Key-Value Pairs / Dict
38,715,321
<p>I have several objects from <code>type dict</code> with different keys. I want to create a table <code>with all keys</code> and foreach object one row. If one key isn't available, it should be empty.</p> <p>For Example:</p> <pre><code>x1=dict( {"a":2, "b":3}) x2=dict( {"a":2, "b":3, "c":2}) </code></pre> <p>and i...
0
2016-08-02T08:24:26Z
38,716,213
<p>Here is a very crude and possibly inefficient solution</p> <pre><code>x1=dict( {"a":2, "b":3,"d":4,"e":5}) x2=dict( {"a":2, "b":3, "c":2}) z = dict(x1.items() + x2.items()) print(z.keys()) x1_vals = [] x2_vals = [] for keys in z.keys(): if keys in x1.keys(): x1_vals.append( x1[keys]) else: ...
0
2016-08-02T09:08:06Z
[ "python" ]
What does a call on queue.join() in main thread do to non-main threads?
38,715,595
<p>My code is as below, </p> <pre><code>import time, queue, threading def washer(dishes, dish_queue): for dish in dishes: print ("Washing", dish) time.sleep(1) dish_queue.put(dish) def dryer(dish_queue): while True: dish = dish_queue.get() print("Drying", dish) ...
2
2016-08-02T08:38:49Z
38,720,740
<p>The short answer to your main question is nothing. </p> <p>For a longer answer, here are two concurrency graphs, one without wait: <a href="http://i.stack.imgur.com/z67vI.png" rel="nofollow"><img src="http://i.stack.imgur.com/z67vI.png" alt="enter image description here"></a></p> <p>And one with: <a href="http://i...
1
2016-08-02T12:43:07Z
[ "python", "multithreading", "queue" ]
How to close cmd after opening a file using Python in Windows?
38,715,630
<p>I have a written a program using Python to open a particular file (txt) which it creates during execution. I have made a batch file to access the script using command line. The batch script is as follows:</p> <pre><code>@echo off python F:\program\script.py %* </code></pre> <p>I have tried these two options for op...
0
2016-08-02T08:40:51Z
38,715,932
<p>To execute a child program in a new process use <code>Popen</code></p> <pre><code>from subprocess import Popen Popen( [ "notepad.exe", "arg1", "arg2", "arg3" ] ) </code></pre>
1
2016-08-02T08:54:16Z
[ "python", "windows", "batch-file", "cmd" ]
Hide Bootstrap Modal after Python Flask template has rendered
38,715,650
<p>I am new to Python and Flask so I am not sure if I am going about this the right way. I have 2 Bootstrap modals. One displays a generic "please wait while loading" spinner that should be displayed whilst my python GETs a JSON string from the server, processes the string as JSON and stores it. The second modal displ...
1
2016-08-02T08:41:57Z
38,718,555
<p>For the loading modal just remove <em>{% if not ready %}</em> and <em>{% endif %}</em>. Then adapt the code slightly to show the message until the site is loaded:</p> <pre><code>$("#pleaseWaitModal").modal("show"); $(document).ready(function(){ $("#pleaseWaitModal").modal("hide"); }); </code>...
0
2016-08-02T10:58:30Z
[ "jquery", "python", "twitter-bootstrap", "flask" ]
Python3 - AttributeError: 'NoneType' object has no attribute 'contents'
38,715,834
<p>I am trying to create a very simple Python currency converter based off the xc.com currency converter website, however at the end of my program I get the following error:</p> <p>line 16, in print(result.contents[0]) AttributeError: 'NoneType' object has no attribute 'contents'</p> <p>After researching similar...
0
2016-08-02T08:50:00Z
38,715,921
<p>This error is pretty straightforward, <code>result</code> is <code>None</code>.</p> <pre><code>result = soup.find('td', {'class', "rightCol"}) </code></pre> <p>You're passing <code>find</code> the set <code>{'class', "rightCol"}</code> instead of the <br/> dictionary <code>{'class': "rightCol"}</code></p>
3
2016-08-02T08:53:54Z
[ "python", "python-3.x", "module", "attributeerror", "nonetype" ]
Python3 - AttributeError: 'NoneType' object has no attribute 'contents'
38,715,834
<p>I am trying to create a very simple Python currency converter based off the xc.com currency converter website, however at the end of my program I get the following error:</p> <p>line 16, in print(result.contents[0]) AttributeError: 'NoneType' object has no attribute 'contents'</p> <p>After researching similar...
0
2016-08-02T08:50:00Z
38,715,940
<p>The exception is thrown because your <code>result</code> name is bind to a <code>None</code> object, which is likely an indication of <code>BeautifulSoup.find</code> failing for some reasons, possibly because there is <code>,</code> where I would expect a <code>:</code> here:</p> <pre><code>result = soup.find('td',...
1
2016-08-02T08:54:42Z
[ "python", "python-3.x", "module", "attributeerror", "nonetype" ]
Python datetime switching between US and UK date formats
38,715,918
<p>I'm using matplotlib to plot some data imported from CSV files. These files have the following format:</p> <pre><code>Date,Time,A,B 25/07/2016,13:04:31,5,25550 25/07/2016,13:05:01,0,25568 .... 01/08/2016,19:06:43,0,68425 </code></pre> <p>The dates are formatted as they would be in the UK, i.e. <code>%d/%m/%Y</code...
0
2016-08-02T08:53:49Z
38,716,169
<p>You're using strings in <code>%d/%m/%Y</code> format but you've given the format specifier as <code>%Y-%m-%d</code>. </p>
0
2016-08-02T09:05:27Z
[ "python", "python-datetime" ]
Python datetime switching between US and UK date formats
38,715,918
<p>I'm using matplotlib to plot some data imported from CSV files. These files have the following format:</p> <pre><code>Date,Time,A,B 25/07/2016,13:04:31,5,25550 25/07/2016,13:05:01,0,25568 .... 01/08/2016,19:06:43,0,68425 </code></pre> <p>The dates are formatted as they would be in the UK, i.e. <code>%d/%m/%Y</code...
0
2016-08-02T08:53:49Z
38,719,000
<p>Matplotlib's <a href="http://matplotlib.org/api/mlab_api.html#matplotlib.mlab.csv2rec" rel="nofollow">csv2rec</a> function parses your dates already and tries to be intelligent when it comes to parsing dates. The function has two options to influence the parsing, <code>dayfirst</code> should help here:</p> <blockqu...
1
2016-08-02T11:19:36Z
[ "python", "python-datetime" ]
PyCharm 2016.2 Automatic breakpoints
38,715,969
<p>I'm getting some 'odd' behaviour out of the debugger in PyCharm 2016.2. Whenever I make a change and the server restarts, I have a few automated breakpoints that always trigger. Specifically, it seems that I always get a break point at <strong>line 1226 in python2.7/dist-packages/pyinotify.py</strong> and <strong>li...
2
2016-08-02T08:56:43Z
39,054,805
<p>This is a bug in PyCharm, Yet to be resolved. Refer this link. <a href="https://youtrack.jetbrains.com/issue/PY-20442" rel="nofollow">https://youtrack.jetbrains.com/issue/PY-20442</a></p>
1
2016-08-20T13:43:06Z
[ "python", "django", "pycharm", "jetbrains" ]
select elements in a list by the occurrence of zeros in python
38,716,055
<p>Given a 2D list:</p> <pre><code>X = [ [a,2], [b,12], [c,6], [d,0], [e,2], [f,0], [g,0], [h,12], [i,18] ] </code></pre> <p>I need to get a 2D list that groups all the sublists, separated by zeros in the <code>X[1]</code> column. I mean, I need to select:</p> <pre><code>Y = [ [[a,2],[b,12],[c,6]], [[e,2]], [[h,12],...
3
2016-08-02T09:00:32Z
38,716,399
<p>I believe this will do the work: </p> <pre><code>[map(lambda a:a[0],list(v)) for k, v in itertools.groupby(X, lambda x: x[1] == 0) if not k] </code></pre> <p><strong>More explanation:</strong> </p> <p>you want to groupby X according to the second value of each item in the list so you need to do:<br> <code>ite...
2
2016-08-02T09:16:38Z
[ "python", "list", "selection", "itertools", "zero" ]
select elements in a list by the occurrence of zeros in python
38,716,055
<p>Given a 2D list:</p> <pre><code>X = [ [a,2], [b,12], [c,6], [d,0], [e,2], [f,0], [g,0], [h,12], [i,18] ] </code></pre> <p>I need to get a 2D list that groups all the sublists, separated by zeros in the <code>X[1]</code> column. I mean, I need to select:</p> <pre><code>Y = [ [[a,2],[b,12],[c,6]], [[e,2]], [[h,12],...
3
2016-08-02T09:00:32Z
38,716,618
<p>I will do it like this:</p> <pre><code>X = [ ['a',2], ['b',12], ['c',6], ['d',0], ['e',2], ['f',0], ['g',0], ['h',12], ['i',18] ] ind = [-1] + [i for i in range(n) if X[i][1]==0] + [len(X)] # found the indices of the "zero" lists Y = [X[ind[i]+1:ind[i+1]] for i in range(len(ind)-1)] # choose the items between those...
0
2016-08-02T09:27:42Z
[ "python", "list", "selection", "itertools", "zero" ]
select elements in a list by the occurrence of zeros in python
38,716,055
<p>Given a 2D list:</p> <pre><code>X = [ [a,2], [b,12], [c,6], [d,0], [e,2], [f,0], [g,0], [h,12], [i,18] ] </code></pre> <p>I need to get a 2D list that groups all the sublists, separated by zeros in the <code>X[1]</code> column. I mean, I need to select:</p> <pre><code>Y = [ [[a,2],[b,12],[c,6]], [[e,2]], [[h,12],...
3
2016-08-02T09:00:32Z
38,717,019
<p>You can define your own splitter using an iterator:</p> <pre><code>def splitter(L): group = [] res = [] for i in iter(L): if i[1]: group.append(i[0]) if not i[1] and len(group): res.append(group) group = [] if len(group): res.append(group) ...
1
2016-08-02T09:45:37Z
[ "python", "list", "selection", "itertools", "zero" ]
Usage of setdefault instead of defaultdict
38,716,079
<p>I need to create a structure like this :</p> <pre><code>D = {i:{j:{k:0,l:1,m:2}},a:{b:{c:0,d:4}}} </code></pre> <p>So this can be done using defaultdict:</p> <pre><code> D = defaultdict(defaultdict(Counter)) </code></pre> <p>How do i use setdefault here?</p> <p>EDIT :</p> <p>Is it possible to combine setdefau...
-1
2016-08-02T09:01:33Z
38,716,203
<p>To build a multi-level dictionary with <code>setdefault()</code> you'd need to repeatedly access the keys like this:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; d = {} &gt;&gt;&gt; d.setdefault("i", {}).setdefault("j", Counter()) Counter() &gt;&gt;&gt; d {'i': {'j': Counter()}} </code><...
0
2016-08-02T09:07:28Z
[ "python" ]
error with strptime() to extract date from timestamp with python
38,716,165
<p>I try to extract hour from the timestamp : I have a dataframe called df_no_missing : </p> <pre><code>df_no_missing.info() </code></pre> <blockquote> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 34673 entries, 1 to 43228 Data columns (total 8 columns): TIMESTAMP 34673 non-null object P_...
0
2016-08-02T09:05:16Z
38,716,216
<p>you would probably want to use <code>datetime.strptime</code> on a single entry rather than on the dataframe object itself? Try something like:</p> <pre><code>for data in df_no_missing["TIMESTAMP"]: mytime = datetime.strptime(data,"%d/%m/%Y %H:%M") print (mytime.day) print (mytime.hour) </code></pre>
0
2016-08-02T09:08:15Z
[ "python", "datetime", "pandas" ]