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
How to use Opsworks (amazon) to deploy python app using 'Custom' layer?
37,654,423
<p>Anyone knows how to deploy python app (just backend, not web) using Opsworks with 'Custom' layer</p>
1
2016-06-06T09:54:49Z
37,669,230
<p>You can create your own custom layer, as you've seen. There's AWS Documentation on <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-custom.html" rel="nofollow">custom layers</a>, which is a good thing to have around if you're trying this at home.</p> <p>Because you're writing a custom lay...
0
2016-06-07T01:39:50Z
[ "python", "amazon", "aws-opsworks" ]
print element from list json
37,654,611
<p>I have a list a load from a txt file which is formatted with JSON, the program prints out the element i want (by index, requested from user) although it prints the list in an unwanted format </p> <pre><code>elif choice == 'v': # View a joke. # See Point 6 of the "Requirements of admin.py" section of the ass...
0
2016-06-06T10:03:26Z
37,654,735
<p>Rather than </p> <pre><code>print(data[index]) </code></pre> <p>You should put something like this:</p> <pre><code>print('Q: {setup}? A: {punchline}'.format(**data[index]) </code></pre> <p>The reason is because it is a dictionary, which you can access by keys.<br> The way I put <code>**data[index]</code> is call...
4
2016-06-06T10:09:27Z
[ "python", "json", "list", "printing" ]
print element from list json
37,654,611
<p>I have a list a load from a txt file which is formatted with JSON, the program prints out the element i want (by index, requested from user) although it prints the list in an unwanted format </p> <pre><code>elif choice == 'v': # View a joke. # See Point 6 of the "Requirements of admin.py" section of the ass...
0
2016-06-06T10:03:26Z
37,654,753
<p>You need to format the output more</p> <pre><code>elif choice == 'v': jokeIndex = input('Joke number to view: ') index = int(jokeIndex) file = open('data.txt', 'r') data = json.load(file) print('Q: ' + data[index]['setup']) print('A: ' + data[index]['punchline']) file.close(); pass </code></pre>
2
2016-06-06T10:10:11Z
[ "python", "json", "list", "printing" ]
print element from list json
37,654,611
<p>I have a list a load from a txt file which is formatted with JSON, the program prints out the element i want (by index, requested from user) although it prints the list in an unwanted format </p> <pre><code>elif choice == 'v': # View a joke. # See Point 6 of the "Requirements of admin.py" section of the ass...
0
2016-06-06T10:03:26Z
37,654,867
<pre><code>f = "Q:{}? A: {}" row = data[index] f1 = f.format(row.get('setup'), row['punchline']) print f1 </code></pre>
0
2016-06-06T10:16:56Z
[ "python", "json", "list", "printing" ]
How to make Braintree's python client reuse connections?
37,654,878
<p>Braintree provides a <a href="https://developers.braintreepayments.com/start/hello-server/python" rel="nofollow">Python library</a> for interacting with their API.</p> <p>However, with logging enabled, it can be seen that every API call negotiates a new SSL connection.</p> <pre class="lang-python prettyprint-overr...
1
2016-06-06T10:17:27Z
37,661,870
<p>It's not officially supported as it overrides a private method, but you can provide an alternate HTTP implementation. This one will send all API requests through a session.</p> <pre class="lang-python prettyprint-override"><code>class SessionHttp(braintree.util.http.Http): session = requests.Session() def ...
2
2016-06-06T15:56:58Z
[ "python", "python-requests", "braintree" ]
Return only certain filename without extension
37,654,894
<p>So from a previous post which I asked I found the following code to work:</p> <pre><code>b = os.walk('C:\\Users\\USER\\Desktop\\FOLDER') f = [] for(dirpath, dirnames, filenames) in b: f.extend(os.path.splitext(name)[0] for name in filenames) break </code></pre> <p>However, now I would like this list to re...
-1
2016-06-06T10:18:11Z
37,655,090
<p>If I understand you correctly, you want to check each file name and return only a specific file type without the extension? Since you're working on <em>Windows</em>, I guess you could do:</p> <pre><code>for filename in files: try: ext = filename.split('.') if ext[1].lower() == 'gif' or ext[1].lo...
0
2016-06-06T10:28:01Z
[ "python", "os.walk" ]
Return only certain filename without extension
37,654,894
<p>So from a previous post which I asked I found the following code to work:</p> <pre><code>b = os.walk('C:\\Users\\USER\\Desktop\\FOLDER') f = [] for(dirpath, dirnames, filenames) in b: f.extend(os.path.splitext(name)[0] for name in filenames) break </code></pre> <p>However, now I would like this list to re...
-1
2016-06-06T10:18:11Z
37,655,157
<p>You can use <em>str.endswith</em> passing a tuple of extensions:</p> <pre><code>f.extend((os.path.splitext(name)[0] for name in filenames if name.lower().endswith((".jpeg", ".gif"))) </code></pre> <p>I am not sure why you have a <em>break</em> in your for loop as that will mean you loop over one directory which yo...
1
2016-06-06T10:31:20Z
[ "python", "os.walk" ]
Return only certain filename without extension
37,654,894
<p>So from a previous post which I asked I found the following code to work:</p> <pre><code>b = os.walk('C:\\Users\\USER\\Desktop\\FOLDER') f = [] for(dirpath, dirnames, filenames) in b: f.extend(os.path.splitext(name)[0] for name in filenames) break </code></pre> <p>However, now I would like this list to re...
-1
2016-06-06T10:18:11Z
37,655,367
<pre><code>def find_files_by_filter(folder_path, filter): """ :rtype : list """ if not isdir(folder_path): log('Folder path: '+ str(folder_path) + ' not found') return [] re_filter = re.compile(filter) all_files = listdir(folder_path) result = [file for file in all_files if...
1
2016-06-06T10:43:35Z
[ "python", "os.walk" ]
Dictionaries - Check key for multiple values
37,655,060
<p>in my program (that searches for specific keys) i want to implement that it terminates if the key has more than one value. How can i check a key for multiple values?</p> <p>edit: thanks for clearing up my mistake. It seems my values are lists. In that case how can i check for multiple items in the list that is my v...
1
2016-06-06T10:26:33Z
37,655,170
<p>It is not possible for a dictionary key to have more than one value: either the key is not present in the dictionary, so it has no value, or it is present, and it has one value.</p> <p>That value may be a tuple, list, dictionary, etc., which contains multiple values, but it is <em>still one value</em> itself. The v...
1
2016-06-06T10:31:57Z
[ "python", "dictionary" ]
Dictionaries - Check key for multiple values
37,655,060
<p>in my program (that searches for specific keys) i want to implement that it terminates if the key has more than one value. How can i check a key for multiple values?</p> <p>edit: thanks for clearing up my mistake. It seems my values are lists. In that case how can i check for multiple items in the list that is my v...
1
2016-06-06T10:26:33Z
37,655,594
<p>Using the <a href="https://docs.python.org/3/library/functions.html#len" rel="nofollow"><code>len</code></a> builtin in python, you can check the length of a list. If the length of the value is more then 1 then there are more then one value in the list.</p> <pre><code>for key in dictionary: # loop through all the k...
1
2016-06-06T10:55:27Z
[ "python", "dictionary" ]
Dependent properties that are CPU intensive
37,655,098
<p>I am very often confronted to this case and did not manage to discover a stable way to deal with it.</p> <p>Suppose I have a class defined like that:</p> <pre><code>class MyClass(object): def __init__(self, a, b): self.a = a self.b = b @property def c(self): """This method perfo...
2
2016-06-06T10:28:26Z
37,655,932
<blockquote> <p>But what if I have a lot of XX dependent properties that rely on a and b values. Do I have to write an update_XX method for each of them and add this method to init and to each a.setter and b.setter ? That seems to me quite verbose...</p> </blockquote> <p>You can have the <code>c</code> value (and an...
1
2016-06-06T11:11:53Z
[ "python", "class", "properties" ]
Dependent properties that are CPU intensive
37,655,098
<p>I am very often confronted to this case and did not manage to discover a stable way to deal with it.</p> <p>Suppose I have a class defined like that:</p> <pre><code>class MyClass(object): def __init__(self, a, b): self.a = a self.b = b @property def c(self): """This method perfo...
2
2016-06-06T10:28:26Z
37,656,935
<p>I'd simply store the actual value of <code>c</code> in a private attribute and check if this is not <code>None</code>. Set this to <code>None</code> when either <code>a</code> or <code>b</code> changes.</p> <p>So the "proper" way of doing this using properties would be:</p> <pre><code>class MyClass(object): de...
0
2016-06-06T12:02:55Z
[ "python", "class", "properties" ]
Dependent properties that are CPU intensive
37,655,098
<p>I am very often confronted to this case and did not manage to discover a stable way to deal with it.</p> <p>Suppose I have a class defined like that:</p> <pre><code>class MyClass(object): def __init__(self, a, b): self.a = a self.b = b @property def c(self): """This method perfo...
2
2016-06-06T10:28:26Z
37,658,806
<p>So based on your answers, I managed to build a new answer using a dict for dependent properties.</p> <pre><code>class MyClass(object): def __init__(self, a, b): self._properties = dict() self._a = a self._b = b def _update_dependent_properties(self): # Do computations for c1...
0
2016-06-06T13:30:01Z
[ "python", "class", "properties" ]
Dependent properties that are CPU intensive
37,655,098
<p>I am very often confronted to this case and did not manage to discover a stable way to deal with it.</p> <p>Suppose I have a class defined like that:</p> <pre><code>class MyClass(object): def __init__(self, a, b): self.a = a self.b = b @property def c(self): """This method perfo...
2
2016-06-06T10:28:26Z
37,659,141
<p>There is a small pypi package that fits well: <a href="https://pypi.python.org/pypi/cached-property/1.2.0" rel="nofollow">cached-property</a></p> <pre><code>from cached_property import cached_property class MyClass(object): def __init__(self): pass @cached_property def c(self): # Heavy...
0
2016-06-06T13:45:46Z
[ "python", "class", "properties" ]
cv2.BackgroundSubtractorMOG2 outputs videos with initial frame superimposed
37,655,118
<p>How can I output the the video with initial frame superimposed using <code>cv2.BackgroundSubtractorMOG2</code>?</p> <p>Here is my code:</p> <pre><code>import cv2 import numpy as np cap = cv2.VideoCapture(0) fgbg = cv2.BackgroundSubtractorMOG2() fourcc = cv2.cv.CV_FOURCC(*'XVID') out = cv2.VideoWriter('output....
0
2016-06-06T10:29:23Z
37,655,630
<p>You can use the <a href="http://docs.opencv.org/master/d0/d86/tutorial_py_image_arithmetics.html#gsc.tab=0" rel="nofollow">cv2.addWeighted</a> function to achieve the superimpose effect</p> <p>however, note that the MOG background subtractor continuously updates it's "idea" of background as new frames are added via...
0
2016-06-06T10:57:27Z
[ "python", "opencv" ]
ImportError: No module named analysis.clustering.algorithms
37,655,169
<p>I am trying to understand python code on text summarization (<a href="https://github.com/giorgosera/pythia/blob/dev/analysis/summarization/summarization.py" rel="nofollow">https://github.com/giorgosera/pythia/blob/dev/analysis/summarization/summarization.py</a>) but when I am running this code, it is showing error:<...
0
2016-06-06T10:31:45Z
37,655,286
<p>Its trying to import this module:</p> <p><a href="https://github.com/giorgosera/pythia/blob/dev/analysis/clustering/algorithms.py" rel="nofollow">https://github.com/giorgosera/pythia/blob/dev/analysis/clustering/algorithms.py</a></p> <p>Have you cloned the <strong>pythia</strong> repository?</p> <p><strong>git cl...
0
2016-06-06T10:39:30Z
[ "python", "nltk" ]
python: Split string by last occurrence seems to delete it rather then split it
37,655,340
<p>I am using the following code to first check if there to the '(' in the string. If so i want to split the string into two like the below example</p> <pre><code>['(Class 6)', '(0-60, 4yo+)', '1m4f Standard'] ['(Class 6)', '(0-60, 4yo+) (1m4f50y)', '1m4f Standard','(1m4f50y)'] </code></pre> <p>but for some reason if...
1
2016-06-06T10:41:55Z
37,655,406
<p><code>rsplit()</code> returns a list, which you put into <code>details</code>. If you take the first element <code>[0]</code> of that list and put it into the element you were taking data from <code>details[1]</code> you should get what you expect.</p> <pre><code>if details[1].count('(') == 2: splitdata = detai...
2
2016-06-06T10:45:45Z
[ "python", "string" ]
python: Split string by last occurrence seems to delete it rather then split it
37,655,340
<p>I am using the following code to first check if there to the '(' in the string. If so i want to split the string into two like the below example</p> <pre><code>['(Class 6)', '(0-60, 4yo+)', '1m4f Standard'] ['(Class 6)', '(0-60, 4yo+) (1m4f50y)', '1m4f Standard','(1m4f50y)'] </code></pre> <p>but for some reason if...
1
2016-06-06T10:41:55Z
37,657,763
<p>Is this kinda what you're trying to do?</p> <pre><code>deets = [ ['(Class 6)', '(0-60, 4yo+) (1m4f50y)', '1m4f Standard', '(1m4f50y)'] ] def separate_tuples(details: list) -&gt; list: # Loop over each string in the list, but also get it's index for index, string in enumerate(details): # If th...
0
2016-06-06T12:41:32Z
[ "python", "string" ]
How do I do a math filter in Django database request?
37,655,408
<p>I've got a model which has the following columns in database: "corrects" and "incorrects".</p> <p>I want to do a filter that takes only the > 80%.</p> <p>F.e: (corrects * 100 / (corrects + incorrects)) > 80</p> <p>How do I do this?</p>
0
2016-06-06T10:45:54Z
37,656,162
<p>Use <code>F</code> (<a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/#f-expressions" rel="nofollow">documentation</a>) expressions to <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#annotate" rel="nofollow">annotate</a>, then filter on the annotation:</p> <pre><code>from dj...
1
2016-06-06T11:24:21Z
[ "python", "django", "database", "filter", "models" ]
What is the opposite of Flask's `init_app`? (Flask app teardown)
37,655,421
<p>I'm building a Flask extension that needs to create a temporary folder when its <code>init_app</code>-method is called. I'm planning to use Python's built-in <code>tempfile.mkdtemp()</code> – however, I need to remove the temporary directory when the Flask app is stopped/torn down.</p> <p>What is the correct way ...
0
2016-06-06T10:46:33Z
37,656,344
<p>There is no teardown; generally Flask servers are expected to run 'forever'.</p> <p>Leave it to the OS to delete the temporary directory or register an <a href="https://docs.python.org/2/library/atexit.html" rel="nofollow"><code>atexit</code> handler</a> to clean up any such directories.</p> <p>Note that it depend...
0
2016-06-06T11:33:17Z
[ "python", "flask" ]
'This field is required.' is shown next to inputs, with GET request
37,655,477
<p>I can't get the 'This field is required.' <strong>not</strong> show on the page when my form is instantiated. Also, I'm using Django + Bootstrap.</p> <p>forms.py</p> <pre><code>class RatingForm(forms.Form): name = forms.CharField( label='', widget=forms.TextInput(attrs={'class': 'form-control'}), ) ra...
0
2016-06-06T10:49:23Z
37,656,300
<p>You should only pass <code>request.POST</code> to the form for POST requests.</p> <pre><code>if request.method == 'POST': rating_form = RatingForm(request.POST) ... else: rating_form = RatingForm() </code></pre> <p>If you use <code>RatingForm(request.POST)</code> for a GET request, then <code>request.P...
2
2016-06-06T11:30:44Z
[ "python", "django", "twitter-bootstrap", "django-forms" ]
plot components of a vector separately in matplotlib
37,655,518
<p>I have a python list of 3-dimensional numpy vectors, which can be created as follows:</p> <pre><code>import numpy as np x = list() for i in range(10): x.append(np.random.rand(3)) </code></pre> <p>Now, I want to plot the x, y and z values of this vector collection in a matplotlib plot on the same plot with diff...
-4
2016-06-06T10:51:17Z
37,656,242
<p>It's trivial:</p> <pre><code>from matplotlib import pyplot as plt plt.plot(x) plt.legend(['x', 'y', 'z']) </code></pre>
1
2016-06-06T11:28:16Z
[ "python", "matplotlib" ]
Keeping part of array constant
37,655,551
<p>I have an array of float values which I then pass to an equation to produce a corresponding array. However, I would like to keep the first n values of this array constant, and then all values after that to be passed to the equation. </p> <p>What is this best way to do this in Python?</p>
0
2016-06-06T10:53:08Z
37,655,717
<p>Just slice the array to pass the values after the <em>nth</em> to your "equation" (which I assume is a function?).</p> <pre><code>def equation(l): return sum(l) # for example a = [1, 2, 3, 4, 5, 6, 7, 8] n = 4 &gt;&gt;&gt; equation(a[n:]) 26 &gt;&gt;&gt; equation(a[3:6]) 15 </code></pre> <p>This passes on...
4
2016-06-06T11:00:38Z
[ "python", "arrays", "numpy" ]
How to create a numpy array from two lists of tuples, but only when the tuples are the same
37,655,805
<p>For image analysis i loaded up a float image with scipy imread.</p> <p>Next, i had scipys argrelmax search for local maxima in axis 0 and 1 and stored the results as arrays of tuples.</p> <pre><code>data = msc.imread(prediction1, 'F') datarelmax_0 = almax(data, axis = 0) datarelmax_1 = almax(data, axis = 1) </code...
0
2016-06-06T11:05:16Z
37,656,129
<p>How about this "naive" way?</p> <pre><code>import numpy as np result = np.array([x for x in datarelmax_0 if x in datarelmax_1]) </code></pre> <p>Pretty simple. Maybe there's a better/faster/fancier way by using some numpy methods but this should work for now.</p> <p>EDIT: To answer your edited question, you can...
1
2016-06-06T11:22:43Z
[ "python", "arrays", "numpy" ]
Looking for a simple way to display a code block in Django admin
37,655,902
<p>I'm looking for a way to display a block of code (i.e. show a snippet of markup) in Django admin. I've been digging around for a while, and my current (non-working) approach is:</p> <pre><code>from django.template import Context, loader class EventAdmin(admin.ModelAdmin): list_display = ('name', 'date') or...
1
2016-06-06T11:10:35Z
37,656,195
<p>Try escaping the output of your <code>create_markup</code> method.</p> <pre><code>from django.utils.html import escape def create_markup(event): output = ... return escape(output) </code></pre>
3
2016-06-06T11:26:19Z
[ "python", "django", "django-templates", "django-admin" ]
Error: Command '['dot', '-V']' returned non-zero exit status -5 When using Iris
37,655,977
<p>After I installed the package <code>Iris</code> with <code>conda install -c scitools iris</code>,</p> <p>Whether using Ipython console or Jupyter notebook, the <code>iris</code> was always failed to import. The error subroutine shows like:</p> <pre><code> -----------------------------------------------------------...
0
2016-06-06T11:14:22Z
37,656,259
<p>I raised a similar issue on the iris GitHub tracker (<a href="https://github.com/SciTools/iris/issues/1899" rel="nofollow">https://github.com/SciTools/iris/issues/1899</a>). Essentially, as much as I believe it was intended to be optional, the way it has been implemented I think Iris actually requires a <code>dot</c...
2
2016-06-06T11:28:57Z
[ "python", "python-2.7", "netcdf", "grib", "python-iris" ]
Define time dependent variable in a netcdf file using python
37,656,059
<p>I'll explain a bit my situation: I am trying to edit some variables of a netcdf file and write out a new netcdf file that shows me the new edited variables. My problem is that variables are time-dependent and I don't know how to include this in my code:</p> <pre><code>import netCDF4 import numpy as np ncfile = ne...
1
2016-06-06T11:19:04Z
37,656,677
<p>You have to create another dimension for time:</p> <pre><code>ncfile_out.createDimension('time', nt) # to make time dimension unlimited put None instead of nt v_out = ncfile_out.createVariable('v_center', 'f4', ('time', 'longitude', 'latitude', 'level')) </code></pre> <p>Then add additional array to store time val...
2
2016-06-06T11:48:53Z
[ "python", "netcdf" ]
querying on json data | Mongodb | django | python
37,656,094
<p>I want to get all the news that are published on dates after Mon, 06 Jun 2016 13:54:32. I tried this:</p> <pre><code>db.collection.find({'date':{$gt:'Mon, 06 Jun 2016 13:54:32'}}) </code></pre> <p>but I got an invalid syntax error.</p>
0
2016-06-06T11:20:54Z
37,656,305
<p><strong>Seems to be a syntax error. Check below code :</strong></p> <pre><code>db.collection.find({"date":{$gt:"Mon, 06 Jun 2016 13:54:32"}}) </code></pre> <p>If you are <strong>connecting from python/django code</strong> , above query might not work again. Use below then:</p> <pre><code>db.collection.find({"date...
0
2016-06-06T11:31:04Z
[ "python", "json", "mongodb" ]
querying on json data | Mongodb | django | python
37,656,094
<p>I want to get all the news that are published on dates after Mon, 06 Jun 2016 13:54:32. I tried this:</p> <pre><code>db.collection.find({'date':{$gt:'Mon, 06 Jun 2016 13:54:32'}}) </code></pre> <p>but I got an invalid syntax error.</p>
0
2016-06-06T11:20:54Z
37,656,309
<p>Do something like this</p> <p><code>db.collection.find({"date" : { $gt : "Mon, 06 Jun 2016 13:54:32" }});</code></p> <p>Cheers!</p>
0
2016-06-06T11:31:22Z
[ "python", "json", "mongodb" ]
querying on json data | Mongodb | django | python
37,656,094
<p>I want to get all the news that are published on dates after Mon, 06 Jun 2016 13:54:32. I tried this:</p> <pre><code>db.collection.find({'date':{$gt:'Mon, 06 Jun 2016 13:54:32'}}) </code></pre> <p>but I got an invalid syntax error.</p>
0
2016-06-06T11:20:54Z
37,656,393
<p>I think you have to do something like $gt: new Date("Mon, 06 Jun 2016 13:54:32Z"), or ISODate(...) to allow mongodb to compare it to the BSON representation it has stored.</p>
0
2016-06-06T11:35:43Z
[ "python", "json", "mongodb" ]
querying on json data | Mongodb | django | python
37,656,094
<p>I want to get all the news that are published on dates after Mon, 06 Jun 2016 13:54:32. I tried this:</p> <pre><code>db.collection.find({'date':{$gt:'Mon, 06 Jun 2016 13:54:32'}}) </code></pre> <p>but I got an invalid syntax error.</p>
0
2016-06-06T11:20:54Z
37,657,140
<p>its a syntax error.</p> <p>You write like this db.collectionName.find({"AttributeName":{$gt:"You Date Format"}}); In Your Case it should like this db.collection.find({"date":{$gt:"Mon, 06 Jun 2016 13:54:32"}})</p>
0
2016-06-06T12:12:39Z
[ "python", "json", "mongodb" ]
Ren-py: Why doesn't this work?
37,656,227
<p>I want the images to be loaded depending on a variable "ImgVal"</p> <pre><code>$ ImgVal = [] $ image bob = "b_neutral_%s.png" % ImgVal $ image bob_sad = "b_sad_%s.png" % ImgVal $ image bob_happy = "b_happy_%s.png" % ImgVal </code></pre>
-1
2016-06-06T11:27:37Z
37,656,444
<p>The value passed by the <code>%</code> operator has to be of type string (or a dictionary, if you use <code>%(val_name)s</code> instead of <code>%s</code>).</p> <p>For example:</p> <pre><code>ImgVal = 1 # some calculation to evaluate Imgval print "b_neutral_%s.png" % str(ImgVal) # cast ImgVal from int to str </cod...
0
2016-06-06T11:38:00Z
[ "python", "renpy" ]
Populate form using jinga2 / flask html with button dynamic
37,656,271
<p>I'm trying to populate a form, by clicking in data from table, but I'm trying do it so dynamically that only get the last value, in this case it's stopping in column 3. I can't find a way to do it directly with html / a href, so I'm trying with jquery. Any help would be fantastic :)</p> <p>the list:</p> <pre><code...
0
2016-06-06T11:29:19Z
37,678,226
<p>I realize later that I already give the right solution for this case, while I was building this "test case", by renaming with the column name (field...).</p> <p>Just missing to do the same for all the remaining ones, and create their respective function to activate them.</p> <p>Not looks so dynamically/ magic by r...
0
2016-06-07T11:32:48Z
[ "jquery", "python", "html", "flask" ]
Why is my output from scrabing empty brackets?
37,656,473
<p>I am trying to scrabe distance in km and time from google maps. However, when I run my code. the result is 2 emty brackets. like these: [] []</p> <p>What am I doing wrong? You can see my code below. bwt, I am using the 3.5.1 version of python. I hope you can help me. Thanks Anna. </p> <pre><code>import urllib.req...
2
2016-06-06T11:39:36Z
37,669,668
<p>In Python Regexp, the <code>"&lt;&gt;."</code> characters are of special use, also called <code>regexp meta chacter</code>. So when using those character as the original character, make it escaped with a <code>\</code> ahead first. </p> <p>So, the following expression <code>regex</code> and <code>regex2</code>:</p>...
0
2016-06-07T02:42:41Z
[ "python", "ssl" ]
Openshift outdated python packages
37,656,479
<p>I use free gear on openshift.com, I need to install SQLAlchemy 1.0+, but openshift use local easy_install mirror for downloading packages and latest version of SQLAlchemy is 0.7.9. i try to using pip, but it also use local mirror. Then i find this solution, but compiling process crash. <code>--index-url https://pypi...
0
2016-06-06T11:39:55Z
37,661,237
<p>Try</p> <p>1) SSH into your app</p> <p>2) activate your venv </p> <pre><code>source python/virtenv/venv/bin/activate </code></pre> <p>3) Manually install package </p> <pre><code>easy_install sqlalchemy==1.0 </code></pre>
1
2016-06-06T15:27:13Z
[ "python", "python-3.x", "pip", "openshift", "pypi" ]
why does pip not comply with minimal dependencies?
37,656,690
<p>For my Python package, I have a setup.py file where I specify requirements:</p> <pre><code>install_requires=['numpy&gt;=1.7', 'matplotlib&gt;=1.3'], </code></pre> <p>When I use pip install, it nicely recognizes that I have specified these requirements, and then proceeds to update numpy while my numpy version was h...
1
2016-06-06T11:49:55Z
37,656,915
<p>pip is installing a version of <code>numpy</code> that is greater than 1.7. Which is what you specified. If you're looking for an exact match of the version you want, you can try something like:</p> <pre><code>install_requires=['numpy==1.7', ... ] </code></pre> <p>Or if you want to specify a particular range you c...
2
2016-06-06T12:01:36Z
[ "python", "pip" ]
Optical flow by Lucas-Kanade method?
37,656,713
<p>The method given in OpenCV tutorials-python has some delay in processing,it is like playing the video at 0.5 speed, Can you suggest any other method where in the optical flow feature(displacement vector fields) can be obtained with a negligible delay?</p> <pre><code>import cv2 import numpy as np cap = cv2.VideoCapt...
1
2016-06-06T11:51:04Z
37,662,131
<p>First, the method you are using in your code is <strong>not</strong> Lucas-Kanade. You are using <code>calcOpticalFlowFarneback</code> function which is the <a href="http://www.diva-portal.org/smash/get/diva2:273847/FULLTEXT01.pdf" rel="nofollow">Farneback</a> method for motion estimation. </p> <p>In general, opt...
1
2016-06-06T16:10:22Z
[ "python", "opencv", "opticalflow" ]
Cloud9 djangobower install permissions issue
37,656,761
<p>I'm trying to add the <code>djangobower</code> app to my django project in Cloud9. </p> <p>I changed my <code>settings.py</code> as per the instructions from the <a href="https://django-bower.readthedocs.io/en/latest/" rel="nofollow">documentation</a>. But when I try to run <code>./manage bower install</code> I get...
0
2016-06-06T11:53:34Z
37,662,348
<p>This is a <a href="https://github.com/bower/bower/issues/2262" rel="nofollow">permissions with Bower</a>, as suggested from the error (not a Cloud9 specific issue).</p> <p>Use the following to fix it:</p> <p><code>sudo chown -R $USER:$GROUP ~/.npm</code></p> <p><code>sudo chown -R $USER:$GROUP ~/.config</code></p...
1
2016-06-06T16:21:36Z
[ "python", "django", "bower", "cloud9-ide" ]
RGB to HSV using colorsys
37,656,768
<p>i am trying to make a tracking program that takes an image and displays where the the object with the specified color is: </p> <p>example: <a href="https://imgur.com/a/8LR40" rel="nofollow">https://imgur.com/a/8LR40</a></p> <p>to do this i am using RGB right now but it is realy hard to work with it so i want to co...
0
2016-06-06T11:53:54Z
37,656,972
<blockquote> <p>Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all other spaces, the coordinates are all between 0 and 1.</p> </blockquote> <p><a href="https://docs.python.org/3/lib...
1
2016-06-06T12:04:52Z
[ "python", "rgb", "hsv" ]
scipy.integrate Pseudo-Voigt function, integral becomes 0
37,656,971
<p>I am writing a script for fitting peak shapes to spectroscopic data in Python, using Scipy, Numpy and Matplotlib. It can fit multiple peaks at once. The peak profile (for now) is Pseudo-Voigt, which is a linear combination of a Gaussian (aka Normal) and Lorentzian (aka Cauchy) distribution. </p> <p>I have an option...
1
2016-06-06T12:04:51Z
37,658,878
<p>As I'm sure you are aware, the interval (-inf, inf) is pretty big. :) A Gaussian decays very fast, so except for an interval near the peak, a Gaussian is numerically indistinguishable from 0. I suspect <code>quad</code> is simply not seeing your peak.</p> <p>A simple work-around is to split the integral into two ...
0
2016-06-06T13:32:51Z
[ "python", "numpy", "scipy", "data-fitting", "integrate" ]
NamedTuple, is the class being treated as a value
37,657,222
<p>In the code below:</p> <pre><code>point=namedtuple('point','x y') </code></pre> <p>I am confused that a class is being treated as a value. As in when I do:</p> <pre><code>class point: ... </code></pre> <p>It creates a class object named point in the namespace, but not in the named tuple case.</p> <p>And if...
1
2016-06-06T12:16:05Z
37,657,258
<p>Classes are <em>just objects</em> in Python. <code>namedtuple()</code> returns a new class each time (the name is only used to set the <code>__name__</code> attribute). Calling <code>namedtuple()</code> multiple times with the same name will still create multiple unique class objects:</p> <pre><code>&gt;&gt;&gt; fr...
4
2016-06-06T12:17:31Z
[ "python", "class", "namedtuple" ]
how to implement custom metric in keras?
37,657,260
<p>I get this error : </p> <blockquote> <p>sum() got an unexpected keyword argument 'out'</p> </blockquote> <p>when I run this code:</p> <pre><code>import pandas as pd, numpy as np import keras from keras.layers.core import Dense, Activation from keras.models import Sequential def AUC(y_true,y_pred): not_y_pr...
4
2016-06-06T12:17:34Z
37,663,327
<p>This code doesn't work because <code>y_pred</code> and <code>y_true</code> are not numpy arrays but either Theano or Tensor Flow tensors. That's why you got this error.</p> <p>You can define your custom metrics but you have to remember that its arguments are those Tensors - not numpy arrays.</p>
2
2016-06-06T17:18:20Z
[ "python", "neural-network", "metrics", "keras" ]
Multiple threads inside docker container
37,657,280
<p>I need to spawn N threads inside a docker container. I am going to receive a list of elements, then divide it in chunks and each thread will process each chunk.</p> <p>So I am using a docker container with one process and N threads. Is it good practice in docker? I think so, because we have, e.g, apacha webserver ...
1
2016-06-06T12:18:27Z
37,692,379
<p>A container as such has nothing to do with the computation you need to perform. The question you are posting is <strong>whether I should have multiple processes doing my processing or multiple threads spawned by the same process doing the processing ?</strong> </p> <p>A container is <strong>just a platform for runn...
0
2016-06-08T02:41:33Z
[ "python", "multithreading", "docker" ]
Error when importing CSV to postgres with python and psycopg2
37,657,333
<p>I try to COPY a CSV file from a folder to a postgres table using python and psycopg2 and I get the following error:</p> <pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; psycopg2.ProgrammingError: must be superuser to COPY to or from a file HINT: Anyone can COPY to st...
0
2016-06-06T12:20:38Z
37,657,544
<p>Try using <a href="http://initd.org/psycopg/docs/cursor.html#cursor.copy_expert" rel="nofollow"><code>cursor.copy_expert()</code></a>:</p> <pre><code>constr = "dbname='db_name' user='user' host='localhost' password='pass'" conn = psycopg2.connect(constr) cur = conn.cursor() sqlstr = "COPY test_2 FROM STDIN DELIMITE...
2
2016-06-06T12:30:03Z
[ "python", "postgresql", "csv", "psycopg2" ]
Force iPython %cd magic command to not print path
37,657,450
<h1><a href="https://ipython.org" rel="nofollow">iPython</a> <a href="https://ipython.org/ipython-doc/3/interactive/magics.html#magic-cd" rel="nofollow"><code>%cd</code> magic command</a></h1> <p>Can the <a href="https://ipython.org/ipython-doc/3/interactive/magics.html#magic-cd" rel="nofollow"><code>%cd</code> magic ...
1
2016-06-06T12:25:51Z
37,657,451
<h1><em>Quiet</em> iPython <code>%cd</code> magic command</h1> <p>The <a href="https://ipython.org/ipython-doc/3/interactive/magics.html#magic-cd" rel="nofollow">iPython magic command provides a quiet option</a>. Use the <code>-q</code> option to not display the output.</p> <pre><code>In [1]: %cd -q ~/GitHub/somepla...
1
2016-06-06T12:25:51Z
[ "python", "ipython", "cd", "ipython-magic" ]
Python server "Aborted (Core dumped)"
37,657,461
<p>I use web.py to create a Python web server. This server is called to solve linear programming problems, and it uses the library CBC to do that.</p> <p>Every once in a while, the server crashes with a log that looks like that:</p> <pre><code>78.243.184.3:56271 - - [03/Jun/2016 04:35:54] "HTTP/1.1 GET /optimization"...
4
2016-06-06T12:26:27Z
37,713,234
<p>A core dump is caused by a fault in the native code in your web server. Python is pretty darn solid these days, so such faults are almost always caused by bugs in C extensions in my experience.</p> <p>You therefore have 3 problems.</p> <ol> <li><p>You need to find the core dump file. This is usually in the curre...
3
2016-06-08T21:27:39Z
[ "python", "c", "web.py", "linear-programming", "coredump" ]
Python server "Aborted (Core dumped)"
37,657,461
<p>I use web.py to create a Python web server. This server is called to solve linear programming problems, and it uses the library CBC to do that.</p> <p>Every once in a while, the server crashes with a log that looks like that:</p> <pre><code>78.243.184.3:56271 - - [03/Jun/2016 04:35:54] "HTTP/1.1 GET /optimization"...
4
2016-06-06T12:26:27Z
37,749,908
<p>Most common reason for a Core dump is to access a memory address outside of your reach (memory that do not belong to your program). The operatingsystem interrupts the program with a interruption called SegFault or BusError depeding on how the program tried to access the invalid memory address. The program will then ...
0
2016-06-10T13:46:32Z
[ "python", "c", "web.py", "linear-programming", "coredump" ]
interactive: How to select the defined Frame in?
37,657,485
<p>I have a problem using n </p> <p>Here is the plan:<br> I am just a beginner. But I just think the easist way to do it might be, </p> <p>Hope you understand my poor English and my beginners question. Here is the code. Thank you all.</p> <pre><code>import matplotlib matplotlib.use('TkAgg') root.mainloop() ...
1
2016-06-06T12:27:41Z
37,662,423
<p>If you wont to show it in <code>frame_0</code>, i don't know why you are setting the <code>master=root</code>. Simply change:</p> <pre><code>dataPlot = FigureCanvasTkAgg(f, master=root) </code></pre> <p>to:</p> <pre><code>dataPlot = FigureCanvasTkAgg(f, master=Frame_0) </code></pre> <p>Also you don't need that <...
2
2016-06-06T16:25:55Z
[ "python", "matplotlib", "tkinter" ]
How to unpack multdimensional array into variables in Julia
37,657,664
<p>In Python I can do:</p> <pre><code>a = array([[1,2],[3,4]]) row1, row2 = a </code></pre> <p>Is there an equivalent one-liner in Julia? This doesn't seem to work:</p> <pre><code>a = [[1 2]; [3 4]] row1, row2 = a </code></pre> <p>Instead it sets row1=1 and row2=3. Thanks! </p>
1
2016-06-06T12:36:10Z
37,659,340
<p>Arrays in Julia are a bit more general (they can be more than 2-d matrices). So the meaning of "rows" is less clear and there might be more options of slicing the array which the programmer intends. Therefore more info needs to be put into the expression.</p> <p>The version I came up with is:</p> <pre><code>row1, ...
2
2016-06-06T13:54:35Z
[ "python", "multidimensional-array", "julia-lang", "iterable-unpacking" ]
How to unpack multdimensional array into variables in Julia
37,657,664
<p>In Python I can do:</p> <pre><code>a = array([[1,2],[3,4]]) row1, row2 = a </code></pre> <p>Is there an equivalent one-liner in Julia? This doesn't seem to work:</p> <pre><code>a = [[1 2]; [3 4]] row1, row2 = a </code></pre> <p>Instead it sets row1=1 and row2=3. Thanks! </p>
1
2016-06-06T12:36:10Z
37,659,865
<p>The shortest one-liner I can think of in Julia is</p> <pre><code>r1, r2 = [sub(a, i, :) for i=1:2] </code></pre> <p>it's not as efficient as writing out</p> <pre><code>r1 = sub(a, 1, :) r2 = sub(a, 2, :) </code></pre> <p>because the first version creates a temporary array and then unpacks it into the tuple on th...
3
2016-06-06T14:20:14Z
[ "python", "multidimensional-array", "julia-lang", "iterable-unpacking" ]
How to unpack multdimensional array into variables in Julia
37,657,664
<p>In Python I can do:</p> <pre><code>a = array([[1,2],[3,4]]) row1, row2 = a </code></pre> <p>Is there an equivalent one-liner in Julia? This doesn't seem to work:</p> <pre><code>a = [[1 2]; [3 4]] row1, row2 = a </code></pre> <p>Instead it sets row1=1 and row2=3. Thanks! </p>
1
2016-06-06T12:36:10Z
37,660,075
<p>Depending on what you are doing you could use a <code>Vector{Vector{T}}</code>, like python list of lists instead of a <code>Matrix</code> (<code>Array{T,2}</code>).</p> <p>In <code>v0.5+</code> it just works, with <code>[ , ]</code>:</p> <pre class="lang-rb prettyprint-override"><code>julia&gt; VERSION v"0.5.0-...
2
2016-06-06T14:29:51Z
[ "python", "multidimensional-array", "julia-lang", "iterable-unpacking" ]
How to sequentially search for files and save them?
37,657,781
<p>I have the code below which tries to find PDF files first. If it does not succeed in finding even a single PDF file, then it continues to search for e.g. .TIF files in the same folder. </p> <p>However, I have two problems. First, when it finds a PDF file in the folder, it also prints all the .TIF files in a .txt fi...
1
2016-06-06T12:42:11Z
37,658,234
<p>Try this:</p> <pre><code>import os def gather_files(folder, ending): contents = os.walk(folder) files = [] for (dirpath, dirnames, filenames) in contents: files += ([file.splitext()[0] for file in filenames if file.lower().endswith(ending)]) return files def main(): f = gather_files("...
2
2016-06-06T13:02:45Z
[ "python", "file", "operating-system" ]
Asking User to play again
37,657,931
<p>I don't know how to include a play again "loop" with the current code I have. I put a boolAgain = "" so it null's it out but I don't know where to go from there and how I'm going to get there or if I'm doing this correctly.</p> <pre><code>#This imports the random generator import random #Sets up variables strName ...
2
2016-06-06T12:48:49Z
37,658,262
<p>You'll want a big outer <code>while</code> loop for playing the game again, in which you have another <code>while</code> loop to check for <code>yes</code> or <code>no</code>, and the actual game. So:</p> <pre><code>boolAgain = True while boolAgain: #here is where the actual game goes #yay game #end of game ...
3
2016-06-06T13:04:02Z
[ "python" ]
Stackexchange API encoding
37,657,992
<p>I am writing following decorator for Stackexchange API: </p> <pre><code> class StackOverflowHandler(tornado.web.RequestHandler): def get(self, look_up_pattern): url = "https://api.stackexchange.com/2.2/search?order=desc&amp;sort=votes&amp;intitle=%s&amp;site=stackoverflow" ...
1
2016-06-06T12:51:24Z
37,707,767
<p>The relevant portion of the answer linked to by Daniel Roseman is this:</p> <pre><code>if response.info().get('Content-Encoding') == 'gzip': buf = StringIO( response.read()) f = gzip.GzipFile(fileobj=buf) data = f.read() </code></pre> <p>In other words, the encoding should be available as <code>respons...
2
2016-06-08T16:15:20Z
[ "python", "encoding", "stackexchange-api" ]
I am trying to write a sample user define function that will plot, but having issues
37,658,127
<pre><code>import numpy as np import matplotlib.pyplot as plt x=np.array([1,2,3,4,5,6]) def linear(a,b): return a*x+b plt.plot(x,linear(a,b)) plt.show() linear(2,4) </code></pre> <p>It just gives me the output <code>[6,8,10,12,14,16]</code> but not a plot. I cannot see what's wrong.</p>
0
2016-06-06T12:57:33Z
37,658,607
<p>You are using <code>return</code> before plot.Change your code to something like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x=np.array([1,2,3,4,5,6]) def linear(a,b): return a*x+b plt.plot(x,linear(2,4)) plt.show() </code></pre>
1
2016-06-06T13:20:25Z
[ "python", "function", "plot", "user-defined" ]
Get command line arguments as string
37,658,154
<p>I want to print all command line arguments as a single string. Example of how I call my script and what I expect to be printed:</p> <pre><code>./RunT.py mytst.tst -c qwerty.c mytst.tst -c qwerty.c </code></pre> <p>The code that does that:</p> <pre><code>args = str(sys.argv[1:]) args = args.replace("[","") args =...
0
2016-06-06T12:58:54Z
37,658,207
<p>An option:</p> <pre><code>import sys ' '.join(sys.argv[1:]) </code></pre> <p>The <code>join()</code> function joins its arguments by whatever string you call it on. So <code>' '.join(...)</code> joins the arguments with single spaces (<code>' '</code>) between them.</p>
6
2016-06-06T13:01:38Z
[ "python", "command-line-arguments" ]
Get command line arguments as string
37,658,154
<p>I want to print all command line arguments as a single string. Example of how I call my script and what I expect to be printed:</p> <pre><code>./RunT.py mytst.tst -c qwerty.c mytst.tst -c qwerty.c </code></pre> <p>The code that does that:</p> <pre><code>args = str(sys.argv[1:]) args = args.replace("[","") args =...
0
2016-06-06T12:58:54Z
37,659,622
<p>You're getting a list object with all of your arguments when you use the syntax <code>[1:]</code> which goes from the second argument to the last. You could run a for each loop to join them into one string:</p> <pre><code>args = sys.argv[1:] result = '' for arg in args: result += " " + arg </code></pre>
1
2016-06-06T14:07:56Z
[ "python", "command-line-arguments" ]
Python - Readline and compare
37,658,158
<p>Im trying to create a function which reads each line in a file and compares the words with their reverse (palindrome) version <code>i.e &gt; (heheh = heheh) &amp; (law = wal)</code>. So when i tried to do that the condition has failed and the function returned an empty list.</p> <p><strong>CODE</strong></p> <pre><...
1
2016-06-06T12:59:02Z
37,658,217
<p>When iterating over the lines in a file, you're getting the line-terminator along with the rest of the line. Id est, you're not comparing <code>"eye" == "eye"</code>, but <code>"eye\n" == "\neye"</code>, which is of course false for all words.</p> <p>Try adding <code>line = line.strip()</code> before the comparison...
6
2016-06-06T13:01:59Z
[ "python" ]
Gurobi Interactive Shell execute automatic commands through a file
37,658,254
<p>I want to execute automatic commands through a file in the Gurobi interactive Shell.</p> <p>I tried the following: </p> <p><code>solve.bat</code> (should do all the work - start gurobi and execute the commands in <code>.cmd</code>)</p> <pre><code>@ECHO OFF cd D:\gurobi651\ run.bat -f PowerLPData.cmd EXIT </code><...
0
2016-06-06T13:03:40Z
37,670,472
<p>gurobi.bat is a Python interpreter that includes the gurobipy library. To run your Python script using gurobi.bat, rename it to PowerLPData.py, then run <code>gurobi.bat PowerLPData.py</code> from a Windows shell.</p>
0
2016-06-07T04:26:03Z
[ "python", "batch-file", "gurobi" ]
Pandas Data Frame find index according to column value
37,658,474
<p>I have a data frame lets say "df". Now one of the columns of the data frame is named "itemID". I would like to get some how very fast the row index according to a value on the column "itemID".</p> <p>When I do:</p> <pre><code>df[df['itemID']==X] </code></pre> <p>The performance is quite slow.</p> <p>Is there a w...
0
2016-06-06T13:14:23Z
37,658,801
<p>I believe you can use <a href="http://dask.pydata.org/en/latest/index.html" rel="nofollow">dask</a>.</p> <p><a href="http://dask.pydata.org/en/latest/dataframe-overview.html#scope" rel="nofollow">Docs</a> say:</p> <p><strong>The following class of computations works well:</strong></p> <blockquote> <p>Trivially ...
0
2016-06-06T13:29:41Z
[ "python", "performance", "pandas", "indexing", "dataframe" ]
How to get followers and following list in Instagram via http requests
37,658,723
<p>I'm looking for a possibility to get a followers and following list in JSON format via web request (in the same way as on the Instagram web site). For example, I can login via requests, and get user info:</p> <pre><code>def get_user_info(self, user_name): url = "https://www.instagram.com/" + user_name + "/?__a=...
1
2016-06-06T13:26:31Z
37,660,535
<p>Easy(just replace _a with __a)</p> <pre><code>'https://www.instagram.com/'+user_name+'/followers/?_a=1' 'https://www.instagram.com/'+user_name+'/following/?_a=1' </code></pre>
-1
2016-06-06T14:52:57Z
[ "python", "instagram" ]
Tornado: asynchronous endpoints
37,658,761
<p>I have following code:</p> <pre><code>class StackOverflowHandler(tornado.web.RequestHandler): def get(self, look_up_pattern): url = "https://api.stackexchange.com/2.2/search?order=desc&amp;sort=votes&amp;intitle=%s&amp;site=stackoverflow" response = self.async_get(url) print(response) ...
2
2016-06-06T13:28:07Z
37,661,892
<p>Since <code>async_get</code> is coroutine it returns <code>Future</code> object. To get "real" results, Future must be resolved - it need to be yielded. More over the <code>get</code> handler must be decorated as asynchronous as well</p> <pre><code>class StackOverflowHandler(tornado.web.RequestHandler): @gen.c...
2
2016-06-06T15:58:15Z
[ "python", "asynchronous", "tornado" ]
Can the header field of requests.post be a unicode object?
37,658,779
<p>I'm using python requests 2.2.1, and trying to post a request with a custom header.</p> <p>I'm creating my own header, <code>myheader</code>, like this:</p> <pre><code>myheader = {'name' : myvalue } </code></pre> <p>The thing is <code>myvalue</code> is a unicode object. I'm not encoding it to a byte string, just ...
0
2016-06-06T13:28:38Z
37,658,890
<p>Headers are <strong>not</strong> unicode data, no. They are not part of the POST body (which is encoded for you as needed, and can otherwise contain <em>any</em> binary data).</p> <p>The vast majority of HTTP headers encode information that only require the ASCII characterset <em>anyway</em>. For example, an <code>...
0
2016-06-06T13:33:30Z
[ "python", "unicode", "python-requests" ]
How can i make MongoDB safe from other users?
37,658,925
<p>I've heard that MongoDB is very good Database, especially for placing large data inside, However i'm not sure how safe can it really be.</p> <p>I'm not experienced at MongoDB, but before i choose, i want to know how safe it can be for important data.</p> <p>So for example, if i specified uri, i would type this:</p...
1
2016-06-06T13:35:15Z
37,659,039
<p>You have no easy way of hiding the credentials. Instead, create a user with the minimal required permissions in the database, and use these credentials in your distributed code.</p> <p>If you are worried about the users being able to see plain-text IP addresses, you should hash and salt them before inserting them t...
1
2016-06-06T13:40:55Z
[ "python", "mongodb" ]
Using Scrapy Itemloader in a loop
37,658,950
<p>I want to use Scrapy on the Dmoz website they use in their tutorials, but instead of just reading the books in the books URL (<a href="http://www.dmoz.org/Computers/Programming/Languages/Python/Books/" rel="nofollow">http://www.dmoz.org/Computers/Programming/Languages/Python/Books/</a>) by using the Item/Field pairs...
3
2016-06-06T13:36:32Z
37,658,984
<p>You need to let your <code>ItemLoader</code> work inside a specific <em>selector</em>, not <code>response</code>:</p> <pre><code>l = MainItemLoader(selector=sel) l.add_xpath('title', './a/div[@class="site-title"]/text()') l.add_xpath('link', './a/@href') l.add_xpath('desc', './div[@class="site-descr "]/text()') yie...
3
2016-06-06T13:38:04Z
[ "python", "web-scraping", "scrapy" ]
python multithreading writing to file no result
37,658,968
<p>I have the following code, which is a stripped-down version of a simulation program I'm writing:</p> <pre><code>import sched, time import _thread as thread, threading lock = threading.Lock() f0=open("f0.out",'w',1) f1=open("f1.out",'w',1) f2=open("f2.out",'w',1) # f3=open("f3.out",'w',1) # f4=open("f4.out",'w',1)...
0
2016-06-06T13:37:14Z
37,659,277
<p>Working code:</p> <pre><code>import sched, time import threading lock = threading.Lock() f0=open("f0.out",'w',1) f1=open("f1.out",'w',1) f2=open("f2.out",'w',1) # f3=open("f3.out",'w',1) # f4=open("f4.out",'w',1) # files = [f1,f2,f3,f4] files = [f1,f2,] def demoWrite(destFile): destFile.write("Hello\n") de...
3
2016-06-06T13:52:04Z
[ "python", "python-3.x", "python-multithreading", "python-3.5" ]
How to click language/region link using Selenium Webdriver and Python?
37,659,066
<p>I'm trying to just click 'North America' and 'US', at the following URL: <a href="http://www.nike.com/language_tunnel" rel="nofollow">http://www.nike.com/language_tunnel</a></p> <p>Here are the steps I have were working for a few weeks, but now seem to not work.</p> <pre><code># choose country/region driver.find_e...
0
2016-06-06T13:42:19Z
37,659,314
<p>As you can see, locating the element by index in this case is not quite reliable. Things like the order of elements tend to change frequently. Instead, use the <code>data-region</code> attribute, for instance:</p> <pre><code>driver.find_element_by_css_selector("button[data-region=n-america]").click() </code></pre>
2
2016-06-06T13:53:22Z
[ "python", "selenium" ]
How to click language/region link using Selenium Webdriver and Python?
37,659,066
<p>I'm trying to just click 'North America' and 'US', at the following URL: <a href="http://www.nike.com/language_tunnel" rel="nofollow">http://www.nike.com/language_tunnel</a></p> <p>Here are the steps I have were working for a few weeks, but now seem to not work.</p> <pre><code># choose country/region driver.find_e...
0
2016-06-06T13:42:19Z
37,659,351
<p>Try to use following code:</p> <pre><code>driver.find_element_by_xpath('//button[@data-region="n-america"]').click() wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li a[data-country="US"]"))).click() </code></pre>
0
2016-06-06T13:55:05Z
[ "python", "selenium" ]
How to click language/region link using Selenium Webdriver and Python?
37,659,066
<p>I'm trying to just click 'North America' and 'US', at the following URL: <a href="http://www.nike.com/language_tunnel" rel="nofollow">http://www.nike.com/language_tunnel</a></p> <p>Here are the steps I have were working for a few weeks, but now seem to not work.</p> <pre><code># choose country/region driver.find_e...
0
2016-06-06T13:42:19Z
37,659,551
<p>If you might want to change the country name tomorrow, you can use the following snippet : </p> <pre><code>countryToSearch = "North America" // you can change this accordingly, rest should work fine for countries in driver.find_elements_by_xpath("(//button[@type='button'])"): countryName = countries.text i...
0
2016-06-06T14:04:32Z
[ "python", "selenium" ]
cannot import VisualRecognitionV3
37,659,124
<p>Here is the python code</p> <pre><code>import os, json, requests from flask import Flask, jsonify from watson_developer_cloud import VisualRecognitionV3 as VisualRecognition def Welcome(): v = json.loads(os.getenv('VCAP_SERVICES')) svcName = 'watson_vision_combined' svc = v[svcName][0]['credentials']...
0
2016-06-06T13:44:49Z
37,668,791
<p>It doesn't look like VisualRecognitionV3 has been merged in at this point in time:</p> <p><a href="https://github.com/watson-developer-cloud/python-sdk/pull/62/files" rel="nofollow">https://github.com/watson-developer-cloud/python-sdk/pull/62/files</a></p> <p>However, you can install the development branch:</p> <...
0
2016-06-07T00:32:27Z
[ "python", "importerror" ]
How to work with context in Django
37,659,317
<p>I'm trying to create a confirmation page. <code>User</code> can create orders on one page, then the <code>create_order</code> view validates the <code>forms</code> and send a request with context to another <code>view</code> which is called <code>confirm_order</code>. I think that I would work correct but there is o...
0
2016-06-06T13:53:35Z
37,660,690
<p>You are returning a template render on your first view. So, the request doesn't end on your confirm_order view. </p> <p>If you want, you can redirect to reverse('confirm_order') and add the data on session. </p> <p>In your confirm_order view you will pop the data from session and continue with your flow.</p>
0
2016-06-06T15:00:37Z
[ "python", "django", "django-forms", "django-views" ]
Errors in the data received through serial using Python
37,659,385
<p>I want to send data to a peripheral using PySerial. However, errors <em>sometime</em> appear in the data received.</p> <pre><code>import serial dongle = serial.Serial("/dev/ttyUSB0", 9600) dongle.write("Some data\n") </code></pre> <p>And then, <code>Some data\n</code> is transmitted to the peripheral.</p> <p>So...
0
2016-06-06T13:56:23Z
37,660,663
<p>I suspect you need to add an inter-char delay to your serial write. Unfortunately, such a thing is not available in PySerial. There is an <code>inter_byte_timeout</code>, but that's for reads.</p> <p>Something like:</p> <pre><code>import serial import time def write_with_delay(command): while len(command)&gt;...
0
2016-06-06T14:58:59Z
[ "python", "pyserial" ]
Energy for 1-D wavelet in Python
37,659,422
<p><br><br> I was wondering if there is an implementation for the Energy for 1-D wavelet in Python, the same as the Matlab '[Ea,Ed] = wenergy(C,L) '. I have tried to write one on my own but i am not sure of it: The formula is:</p> <p><a href="http://i.stack.imgur.com/Yki3c.gif" rel="nofollow"><img src="http://i.stack....
0
2016-06-06T13:58:02Z
37,659,802
<p>You can simplify your code a little bit:</p> <pre><code>coeffs[len(coeffs) - k - 1] </code></pre> <p>can be rewritten as</p> <pre><code>coeffs[-k] </code></pre> <p>and you can do the squaring and summation as one NumPy operation (since you're using NumPy already)</p> <pre><code>def Energy(coeffs, k): return...
1
2016-06-06T14:17:02Z
[ "python", "matlab", "wavelet", "energy" ]
Custom padding for convolutions in TensorFlow
37,659,538
<p>In tensorflow function <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#conv2d" rel="nofollow">tf.nn.conv2d</a>, the padding option just has 'SAME' and 'VALID'. </p> <p>But in the conv layer of Caffe, there is <a href="http://caffe.berkeleyvision.org/tutorial/layers.html" rel="nofollow">pad...
1
2016-06-06T14:04:04Z
37,660,000
<p>You can use <code>tf.pad()</code> (see the <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#pad" rel="nofollow">doc</a>) to pad the Tensor before applying <code>tf.nn.conv2d(..., padding="VALID")</code> (valid padding means no padding).</p> <hr> <p>For instance, if you want to pad t...
4
2016-06-06T14:26:49Z
[ "python", "tensorflow", "caffe" ]
DRY Django querysets
37,659,545
<p>I have a query which users order_by on a number of aggregated fields in a database, like so:</p> <pre><code>list = MyList.objects.filter(key_item=None).extra( select={"diff":"abs(field1+field2+field3+field4+field5+field6+field7+field8+field9+field10)"}).order_by('-diff') </code></pre> <p>I'm using this is ...
1
2016-06-06T14:04:16Z
37,659,662
<p>You can add a manager to your model class to include that as a base filter. For example:</p> <pre><code>class MyListManager(models.Manager): def select_diff(self): return self.get_queryset().extra(...) class MyList(models.Model): objects = MyListManager() </code></pre> <p>With this you can simply...
4
2016-06-06T14:09:58Z
[ "python", "django" ]
python crashes on build script: event log indicates CRYPT32.dll error
37,659,590
<p>platform: windows 2008 server R2<br> this is the error the event log is producing:</p> <pre><code>Faulting application name: python.exe, version: 0.0.0.0, time stamp: 0x52c9534c Faulting module name: CRYPT32.dll, version: 6.1.7601.18741, time stamp: 0x54d03c46 Exception code: 0xc0000005 Fault offset: 0x0005d412 Fau...
0
2016-06-06T14:06:22Z
38,185,951
<p>Update: seems like I've solved it. running the scripts through python does not produce error codes, so I ran it via installshield UI, and got some more information. After an extensive research, I found this: <a href="https://flexeracommunity.force.com/customer/articles/en_US/ERRDOC/Q107380" rel="nofollow">http...
0
2016-07-04T13:27:50Z
[ "python", "windows", "dll" ]
How to add model object to many to many field in django.1.9 and not get TypeError
37,659,644
<p>I got:</p> <pre><code>Author(models.Model): name=models.CharField("name", max_length=100) Entry(models.Model): (...) authors = models.ManyToMany(Author, blank=true) def findAuthors(input): (...) authors = [] for name in names: authors.append(Author.objects.get_or_create(name=name)) ...
0
2016-06-06T14:08:49Z
37,659,806
<p>The <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create" rel="nofollow"><code>get_or_create</code></a> method returns a tuple, not just the object. You could fix it by changing your code to:</p> <pre><code>authors = [] for name in names: author, created = Author.objects.get_or_cre...
1
2016-06-06T14:17:15Z
[ "python", "django", "many-to-many" ]
How to make xml parser ignore invalid characters?
37,659,666
<p>I am using python module lxml to parse xml files. However, some of the xml files contain invalid characters such as ® . Due to this, I am getting following error.</p> <blockquote> <p>lxml.etree.XMLSyntaxError: Input is not proper UTF-8, indicate encoding !</p> <p>Bytes: 0xAE 0x0A 0x53 0x6F, line 45, column ...
1
2016-06-06T14:10:14Z
37,667,016
<p>As mentioned by @jwodder, the xml file was not encoded with utf-8 encoding even though it had utf-8 as encoding attribute. . I changed my encoding params to ISO-8859-1 in lxml parser. </p> <pre><code>parsed_doc = etree.parse(u, etree.XMLParser(encoding='ISO-8859-1', ns_clean=True, recover=True)) </code></pre> <p>...
1
2016-06-06T21:16:36Z
[ "python", "python-2.7", "xml-parsing", "lxml" ]
Copy a list of files fast with access time in windows
37,659,671
<p>This question has been asked in different ways allready, but I am not happy with the answers so far, that's why I'm asking this question with specific needs. </p> <p>I want to copy files on windows using python 2.7 in the style</p> <pre><code>file a --&gt; destination a file b --&gt; destination b etc. </code></pr...
0
2016-06-06T14:10:23Z
37,659,942
<p>1) Use Python to create a 'batch file' that zips the files from the source, then unzips them at the destination.<br> 2) Execute the batch file.</p> <p>This will ensure the timestamps are the same at source and destination, and also means only one process is created to do the work.</p>
-1
2016-06-06T14:24:05Z
[ "python", "windows", "copy" ]
Where am I in a chain of indexing?
37,659,715
<p>If I have some code like this:</p> <pre><code>x.y.z = 12 </code></pre> <p>I can infer that the <code>z</code> member is being indexed from the call to <code>__setattr__</code>. However if I have something like this:</p> <pre><code>foo = x.y.z # situation 1 bar = x.y.z.bar # situation 2 </code></pre> <p>How can I...
3
2016-06-06T14:12:51Z
37,659,898
<p>I'm not sure how you define 'being last at chain of indexing'. You can still call more attributes on an object at any time. </p> <p>But you can know when your object is being accessed as an attribute. As mentioned before, you can overload <code>__getattr__</code> and <code>__getattribute__</code>, but a more robust...
1
2016-06-06T14:22:16Z
[ "python" ]
Where am I in a chain of indexing?
37,659,715
<p>If I have some code like this:</p> <pre><code>x.y.z = 12 </code></pre> <p>I can infer that the <code>z</code> member is being indexed from the call to <code>__setattr__</code>. However if I have something like this:</p> <pre><code>foo = x.y.z # situation 1 bar = x.y.z.bar # situation 2 </code></pre> <p>How can I...
3
2016-06-06T14:12:51Z
37,752,660
<p>There is no way to do this with python overrides. The only way is to have a known member that means "the end." For example, if you wanted to know which member was being set in a long chain of indexes you'd need some kind of setter:</p> <pre><code>x.y.z.set(some_value) </code></pre>
0
2016-06-10T16:05:04Z
[ "python" ]
How to compare two GraphView in graph-tool?
37,659,730
<p>I need to process a lot of sub-graphs of given graph G. Using for that purpose graph-tool seems to be nice approach with utilizing its functionality of GraphViews and edge/vertex filtering functionality. To save time I would like to cache information about already processed sub-graphs. I thought that the fastest way...
0
2016-06-06T14:13:25Z
37,664,421
<p>If the vertices of the subgraphs are aligned, you may use the <a href="https://graph-tool.skewed.de/static/doc/topology.html#graph_tool.topology.similarity" rel="nofollow"><code>similarity()</code></a> function. Otherwise, you have to resort to <a href="https://graph-tool.skewed.de/static/doc/topology.html#graph_too...
1
2016-06-06T18:27:48Z
[ "python", "graph", "graph-tool" ]
Creating Dictionary and Integer Key for List of Strings in Python
37,659,782
<p>I have a list of unicode string lists. </p> <p>Each string list represents a different document with the strings representing the authors' names. Some documents have only one author while other documents can have multiple co-authors.</p> <p>For example, a sample of authorship of three documents looks like this:</p...
1
2016-06-06T14:16:07Z
37,659,818
<p>You need to invert your <code>author_name</code> dictionary; after that the conversion of your list is trivial, using a nested list comprehension:</p> <pre><code>author_to_id = {name: id for id, name in author_name.items()} doc_author = [[author_to_id[name] for name in doc] for doc in authors] </code></pre> <p>De...
2
2016-06-06T14:18:05Z
[ "python", "list", "dictionary", "token" ]
Apache spark taking average by key with python
37,659,882
<p>My solution is like below code but it's with scala.</p> <p>Is there any person to convert it to python for taking average by key ? </p> <pre><code>val avgValue = data.mapValues((_, 1) .reduceByKey((x, y) =&gt; (x._1 + y._1, x._2 + y._2)) .mapValues{ case (sum, count) =&gt; (1.0 * sum) / count } ...
1
2016-06-06T14:21:08Z
37,660,568
<p>With the few information you have given and the quality of the question, the following might be a solution :</p> <pre><code>rdd = sc.parallelize(((7, 6, "dev14", 2016, 22.0),(7, 6, "dev11", 2016, 21.0),(2, 6, "dev12", 2016, 62.0),(2, 6, "dev18", 2016, 28.0),(1, 6, "dev15", 2016, 22.0))) df = sqlContext.createDataFr...
2
2016-06-06T14:54:43Z
[ "python", "scala", "apache-spark", "pyspark" ]
Why doesn't command redirection operator work in PyCharm?
37,659,916
<p>I want to run a python script in PyCharm and redirect the stdin out put to a file. Therefore, I opened Run/Debug configurations and typed:</p> <pre><code>&gt;&gt; output.txt </code></pre> <p>in script parameters field. When I run the script, I get the error: </p> <blockquote> <p>error: unrecognized arguments: >...
0
2016-06-06T14:23:02Z
37,660,058
<p><a href="http://i.stack.imgur.com/9CDHS.png" rel="nofollow"><img src="http://i.stack.imgur.com/9CDHS.png" alt="enter image description here"></a></p> <p>It is available in Run -->EditConfigurations.</p> <p>On the right side you will have Logs tab which says Save console output to file.</p> <p>You may use that opt...
2
2016-06-06T14:29:05Z
[ "python", "pycharm", "io-redirection" ]
Multiply sub items of only lists
37,659,960
<p>I have a data structure like this</p> <pre><code>[[1,2,3,4,5], {9,2,5,8,7}, (7, 4, 8, 6)] </code></pre> <p>One big list containing lists, sets, and tuples.</p> <p>I want to multiply everything inside a list by 3, but not the things inside tuple or set. Output should be:</p> <pre><code>[[3,6,9,12,15], {9,2,5,8,7}...
0
2016-06-06T14:25:00Z
37,660,076
<p>You can use this comprehension pattern: <code>[x if a else b for x in lst]</code>:</p> <pre><code>new_list = [[3*y for y in x] if isinstance(x, list) else x for x in l] </code></pre> <p>Look <a href="http://stackoverflow.com/questions/2951701/is-it-possible-to-use-else-in-a-python-list-comprehension">here</a> for ...
1
2016-06-06T14:30:03Z
[ "python", "list", "list-comprehension" ]
Multiply sub items of only lists
37,659,960
<p>I have a data structure like this</p> <pre><code>[[1,2,3,4,5], {9,2,5,8,7}, (7, 4, 8, 6)] </code></pre> <p>One big list containing lists, sets, and tuples.</p> <p>I want to multiply everything inside a list by 3, but not the things inside tuple or set. Output should be:</p> <pre><code>[[3,6,9,12,15], {9,2,5,8,7}...
0
2016-06-06T14:25:00Z
37,660,095
<p>The code you provided was so close, all you need to do is add a check for if the subList is a list, then if so multiply else leave alone.</p> <pre><code>l = [[2,6,9,13,15], {9,2,5,8,7}, (7, 4, 8, 6)] newList = [[subitem*3 for subitem in subList ] if type(subList) is list else subList for subList in l] print(newList...
1
2016-06-06T14:30:36Z
[ "python", "list", "list-comprehension" ]
Multiply sub items of only lists
37,659,960
<p>I have a data structure like this</p> <pre><code>[[1,2,3,4,5], {9,2,5,8,7}, (7, 4, 8, 6)] </code></pre> <p>One big list containing lists, sets, and tuples.</p> <p>I want to multiply everything inside a list by 3, but not the things inside tuple or set. Output should be:</p> <pre><code>[[3,6,9,12,15], {9,2,5,8,7}...
0
2016-06-06T14:25:00Z
37,660,130
<pre><code>newList = [[subitem*3 for subitem in subList ] if isinstance(subList, list) else subList for subList in l] </code></pre> <p>This can be an option!</p>
1
2016-06-06T14:32:01Z
[ "python", "list", "list-comprehension" ]
How to send JSON response from python server to the javascript using ajax call
37,660,035
<pre><code>elif self.path == "/recQuery": r = requests.get('http://example.com') # This returns some json from a request to another server. print r.json() self.wfile.write(r.json()) </code></pre> <p>.</p> <pre><code>var http = new XMLHttpRequest(); var url = SERVER + "/recQuery"; var params = JSON.stringify({ ...
0
2016-06-06T14:28:14Z
37,660,290
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var http = new XMLHttpRequest(); var url = SERVER + "/recQuery"; var params = JSON.stringify({ query: search_query }); http.onreadystatechange...
0
2016-06-06T14:40:59Z
[ "javascript", "python", "json", "ajax" ]
How to give a relative path to redirection operator?
37,660,154
<p>As you probably know, when running a python script and typing:</p> <pre><code>&gt;&gt; &lt;file-name&gt; </code></pre> <p>a file named &lt; file-name> will be created inside the script directory, and all stdin output of this script will be directed to this file. </p> <p>I want to add a feature in the script that ...
0
2016-06-06T14:33:16Z
37,660,255
<p>Just give the full name of the directory that you'd like to redirect your output to.</p> <pre><code>echo hello world &gt;&gt; &lt;full path of directory&gt;/&lt;name of output file&gt; </code></pre>
0
2016-06-06T14:39:12Z
[ "python", "command-line-arguments", "io-redirection" ]
How to give a relative path to redirection operator?
37,660,154
<p>As you probably know, when running a python script and typing:</p> <pre><code>&gt;&gt; &lt;file-name&gt; </code></pre> <p>a file named &lt; file-name> will be created inside the script directory, and all stdin output of this script will be directed to this file. </p> <p>I want to add a feature in the script that ...
0
2016-06-06T14:33:16Z
37,660,482
<p>Files are created relative to the current directory. You can use <a href="https://docs.python.org/2/library/os.html#os.chdir" rel="nofollow"><code>os.chdir</code></a> to change the current directory.</p>
0
2016-06-06T14:50:24Z
[ "python", "command-line-arguments", "io-redirection" ]
How to give a relative path to redirection operator?
37,660,154
<p>As you probably know, when running a python script and typing:</p> <pre><code>&gt;&gt; &lt;file-name&gt; </code></pre> <p>a file named &lt; file-name> will be created inside the script directory, and all stdin output of this script will be directed to this file. </p> <p>I want to add a feature in the script that ...
0
2016-06-06T14:33:16Z
37,696,169
<p>When you run any command from a sheel and use the <code>&gt;&gt;</code> redirection operator, or in fact any of the standard <code>|</code>, <code>&gt;</code> and similar ones, the one who is doing the redirection is the <strong>shell</strong>, not Python.</p> <p>This means that the Python interpreter will not have...
0
2016-06-08T07:39:20Z
[ "python", "command-line-arguments", "io-redirection" ]
Cleaner way to use re.sub
37,660,200
<p>I know there must be a better way to accomplish the following. Here is my function:</p> <pre><code>def authenticated_url(url): return re.sub(r"(^https://)", "https://" + access_token() + "@", url) </code></pre> <p><code>access_token()</code> returns a token as a String, for example <code>"1248jkdfhjksabcd382"<...
1
2016-06-06T14:35:51Z
37,660,286
<p>If your pattern is fixed, you can do the following:</p> <pre><code>url[:8] + access_token() + '@' + url[8:] </code></pre> <p>If you're not sure about the protocol, you can use <code>replace</code>:</p> <pre><code>url.replace('github', access_token() + '@github') </code></pre>
2
2016-06-06T14:40:41Z
[ "python", "regex" ]
Cleaner way to use re.sub
37,660,200
<p>I know there must be a better way to accomplish the following. Here is my function:</p> <pre><code>def authenticated_url(url): return re.sub(r"(^https://)", "https://" + access_token() + "@", url) </code></pre> <p><code>access_token()</code> returns a token as a String, for example <code>"1248jkdfhjksabcd382"<...
1
2016-06-06T14:35:51Z
37,660,628
<p>What about:</p> <pre><code>&gt;&gt;&gt; url = "https://{access_token}@github.com/jfach/autostager" &gt;&gt;&gt; url.format(access_token=access_token()) 'https://1248jkdfhjksabcd382@github.com/jfach/autostager' </code></pre>
0
2016-06-06T14:57:28Z
[ "python", "regex" ]
Efficient way to subset a huge delimited file
37,660,278
<p>I have previously posted a question before to be solved using <code>R</code>: <a href="http://stackoverflow.com/questions/37310404/subset-recursively-a-data-frame">subset recursively a data.frame</a>, however the file is so huge that I need a lot of time and RAM memory to read it. I wonder if I could use <code>panda...
1
2016-06-06T14:40:22Z
37,662,856
<p>First of all i would strongly recommend to switch from CSV files to PyTables (HDF storage) and store your DF sorted by <code>['SNP','BP']</code> if it's possible, as it's orders of magnitude faster, allows conditional selects (see <code>where</code> parameter) and usually takes less space - see <a href="http://stack...
2
2016-06-06T16:49:12Z
[ "python", "pandas" ]
How to combine every two adjoining lines in Chinese txt file into one line with Python
37,660,288
<p>I have a Chinese txt file with thousands of sentence lines as following, </p> <ol> <li>line 1 </li> <li>line 2</li> <li>line 3</li> <li>line 4</li> </ol> <p>…………</p> <p>I want to combine every two adjoining lines into one line,it should be transformed as:</p> <ol> <li>line 1 + space + line 2</li> <li>lin...
0
2016-06-06T14:40:54Z
37,660,480
<ol> <li>You would read the file and obtain a list of lines (i.e. list of strings)</li> <li><p>then you could use a list comprehension, like this one:</p> <p><code>[ l1 + ' ' + l2 for l1,l2 in zip(lines[::2], lines[1::2]) ]</code></p></li> </ol> <p>Note, this means you'll have to have an equal number of lines. so if ...
0
2016-06-06T14:50:17Z
[ "python" ]
How to combine every two adjoining lines in Chinese txt file into one line with Python
37,660,288
<p>I have a Chinese txt file with thousands of sentence lines as following, </p> <ol> <li>line 1 </li> <li>line 2</li> <li>line 3</li> <li>line 4</li> </ol> <p>…………</p> <p>I want to combine every two adjoining lines into one line,it should be transformed as:</p> <ol> <li>line 1 + space + line 2</li> <li>lin...
0
2016-06-06T14:40:54Z
37,660,502
<p>You should iterate on your file like follows:</p> <pre><code>with open('./chinese.txt') as my_file: for line in my_file: try: print '{} {}'.format(line.strip(), my_file.next()) except StopIteration: # Manage case: number of lines is an odd number print line </code></pre>...
0
2016-06-06T14:51:35Z
[ "python" ]
How to combine every two adjoining lines in Chinese txt file into one line with Python
37,660,288
<p>I have a Chinese txt file with thousands of sentence lines as following, </p> <ol> <li>line 1 </li> <li>line 2</li> <li>line 3</li> <li>line 4</li> </ol> <p>…………</p> <p>I want to combine every two adjoining lines into one line,it should be transformed as:</p> <ol> <li>line 1 + space + line 2</li> <li>lin...
0
2016-06-06T14:40:54Z
37,660,553
<p>You don't need Python for that, <code>sed</code> is enough:</p> <pre><code>$ seq 15 &gt; lines $ cat lines 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $ sed 'N;s/\n/ /g' lines 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 </code></pre> <p>According to man sed:</p> <blockquote> <p>n N Read/append the next line of input into th...
1
2016-06-06T14:54:03Z
[ "python" ]
How to combine every two adjoining lines in Chinese txt file into one line with Python
37,660,288
<p>I have a Chinese txt file with thousands of sentence lines as following, </p> <ol> <li>line 1 </li> <li>line 2</li> <li>line 3</li> <li>line 4</li> </ol> <p>…………</p> <p>I want to combine every two adjoining lines into one line,it should be transformed as:</p> <ol> <li>line 1 + space + line 2</li> <li>lin...
0
2016-06-06T14:40:54Z
37,661,065
<p>A file is an iterator over lines in Python. You could <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow">use the itertools' grouper() recipe, to group the lines into pairs</a>: </p> <pre><code>#!/usr/bin/env python2 from itertools import izip_longest with open('Chinese.txt') as file:...
0
2016-06-06T15:19:16Z
[ "python" ]
Python locate words in nltk.tree
37,660,328
<p>I am trying to build a nltk to get the context of words. I have two sentences </p> <pre><code>sentences=pd.DataFrame({"sentence": ["The weather was good so I went swimming", "Because of the good food we took desert"]}) </code></pre> <p>I would like to find out, what the word "good" refers to. My idea is to chunk t...
0
2016-06-06T14:42:39Z
37,667,654
<p>It's easiest to find your word in a list of leaves. You can then translate the leaf index into a tree index, which is a path down the tree. To see what is grouped with <code>good</code>, go up one level and examine the subtree that this picks out.</p> <p>First, find out the position of <code>good</code> in your fla...
1
2016-06-06T22:12:13Z
[ "python", "nltk", "chunking" ]