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
Separation of a String into Individual Words (Python)
39,775,070
<p>So I have this code here:</p> <pre><code>#assign a string to variable x = "example text" #create set to store separated words xset = [] #create base word xword = "" for letter in x: if letter == " ": #add word xset.append(xword) #add space xset.append(letter) #reset base ...
0
2016-09-29T16:02:17Z
39,775,213
<p>Because when your code reaches the space in <code>x</code> it appends <code>xword</code>. But this only happens when it reaches a space. As there are no spaces after text, the final result is not appended to <code>xset</code> Also, you were not resetting <code>xword</code>:</p> <pre><code>#assign a string to variab...
1
2016-09-29T16:11:01Z
[ "python", "string", "python-2.7" ]
Separation of a String into Individual Words (Python)
39,775,070
<p>So I have this code here:</p> <pre><code>#assign a string to variable x = "example text" #create set to store separated words xset = [] #create base word xword = "" for letter in x: if letter == " ": #add word xset.append(xword) #add space xset.append(letter) #reset base ...
0
2016-09-29T16:02:17Z
39,775,446
<p>Just use string.split(). This command will return list of word in your string. Here is documentation on it: <a href="https://docs.python.org/2/library/string.html" rel="nofollow">https://docs.python.org/2/library/string.html</a></p> <p>If your values are space separated do something like this:</p> <pre><code>r.spl...
0
2016-09-29T16:23:02Z
[ "python", "string", "python-2.7" ]
Confused with elements sizing in Kivy
39,775,117
<p>I've just started to learn Kivy and confused with elements sizing. Let's say I want to create video player time bar with progress bar in middle and time labels on sides.</p> <p>What I got so far:</p> <pre><code>&lt;TimeLabel@Label&gt;: width: 100 padding: 10, 0 font_size: '14sp' &lt;Player&gt;: B...
0
2016-09-29T16:05:32Z
39,776,199
<p>Never ever use default pixel sizing for your widgets, like you did in several places. Use either size hint, or dp unit. This way, your UI will look the same everywhere. More info <a href="https://kivy.org/docs/api-kivy.metrics.html" rel="nofollow">here</a>.</p>
4
2016-09-29T17:07:50Z
[ "python", "kivy", "kivy-language" ]
Web Scraping : Get graph Coordinates from Webpage
39,775,220
<p>I wanted some help with web scraping. I want to retrieve players ranking which are plotted on the graph in this <a href="http://www.icc-cricket.com/player-rankings/profile/sachin-tendulkar" rel="nofollow">link</a></p> <p>Visit the link. Click on Rating, and then hover over the points in the plot. Its <code>y-coordi...
-1
2016-09-29T16:11:39Z
39,775,753
<p>Each <code>circle</code> element has a <code>cy</code> attribute that we can find with the following:</p> <pre><code>var circ = document.querySelector('circle') console.log(circ.getAttribute('cy') // cy= 123.586.... </code></pre> <p>This will give you the y coordinate for the first <code>circle</code> element. You...
0
2016-09-29T16:40:38Z
[ "javascript", "python", "html", "web-scraping" ]
Removing elements from the list when looping over it
39,775,231
<p>This part of my code does not scale if <strong>dimension</strong> gets bigger. </p> <p>I loop over my data and accumulate them every <strong>dt</strong> time window. To do this I compare lower and upper time value. When I reach upper bound, I break the <strong>for loop</strong> for efficiency. The next time I run <...
0
2016-09-29T16:12:00Z
39,777,695
<p>In a simpler form, I think you are trying to do:</p> <pre><code>In [158]: times=[0, 4, 6, 10] In [159]: data=np.arange(12) In [160]: cnt=[0 for _ in times] In [161]: for i in range(len(times)-1): ...: for d in data: ...: if d&gt;=times[i] and d&lt;times[i+1]: ...: cnt[i]+=1 ...
0
2016-09-29T18:39:26Z
[ "python", "list", "numpy", "iteration", "pop" ]
Python input never equals an integer
39,775,273
<p>I want to insert a number and if I put any number other than 4 it will tell me it's wrong, but if it's false it will tell me "gg you win, noob.". However when I insert 4, it tells me it's incorrect.</p> <pre><code>x = input("Insert a numer: ") while x != 4: print("incorrect") x =input("Insert another number...
1
2016-09-29T16:14:19Z
39,775,336
<p>In Python 3+, <code>input</code> returns a string, and <code>4</code> does not equal <code>'4'</code>. You will have to amend to:</p> <pre><code>while x != '4': </code></pre> <p>or alternatively use <code>int</code>, being careful to check for a <code>ValueError</code> if the input is not an int.</p>
3
2016-09-29T16:17:06Z
[ "python" ]
Python input never equals an integer
39,775,273
<p>I want to insert a number and if I put any number other than 4 it will tell me it's wrong, but if it's false it will tell me "gg you win, noob.". However when I insert 4, it tells me it's incorrect.</p> <pre><code>x = input("Insert a numer: ") while x != 4: print("incorrect") x =input("Insert another number...
1
2016-09-29T16:14:19Z
39,775,339
<p>The result from <code>input()</code> will be a string, which you'll need to convert to an integer before comparing it:</p> <pre><code>x = int(input("Insert another number: ") </code></pre> <p>This will raise a <code>ValueError</code> if your input is not a number.</p>
1
2016-09-29T16:17:14Z
[ "python" ]
Python input never equals an integer
39,775,273
<p>I want to insert a number and if I put any number other than 4 it will tell me it's wrong, but if it's false it will tell me "gg you win, noob.". However when I insert 4, it tells me it's incorrect.</p> <pre><code>x = input("Insert a numer: ") while x != 4: print("incorrect") x =input("Insert another number...
1
2016-09-29T16:14:19Z
39,775,471
<p>Here, <code>if x == 4</code> is not necessary. Because until <code>x</code> is equal to <code>4</code> the <code>while</code> loop won't be passed. You can try like this:</p> <pre><code>x = int(input("Insert a numer: ")) while x != 4: print("incorrect") x = int(input("Insert another number: ")) print("gg y...
0
2016-09-29T16:24:43Z
[ "python" ]
Python input never equals an integer
39,775,273
<p>I want to insert a number and if I put any number other than 4 it will tell me it's wrong, but if it's false it will tell me "gg you win, noob.". However when I insert 4, it tells me it's incorrect.</p> <pre><code>x = input("Insert a numer: ") while x != 4: print("incorrect") x =input("Insert another number...
1
2016-09-29T16:14:19Z
39,776,181
<p>Python 2 and 3 differ in the function <code>input()</code>.</p> <ul> <li>In Python 2, <code>input()</code> is equivalent to <code>eval(raw_input())</code>.</li> <li>In Python 3, there is no <code>raw_input()</code>, but <code>input()</code> works like Python 2's<code>raw_input()</code>.</li> </ul> <p>In your case:...
0
2016-09-29T17:07:23Z
[ "python" ]
Python input never equals an integer
39,775,273
<p>I want to insert a number and if I put any number other than 4 it will tell me it's wrong, but if it's false it will tell me "gg you win, noob.". However when I insert 4, it tells me it's incorrect.</p> <pre><code>x = input("Insert a numer: ") while x != 4: print("incorrect") x =input("Insert another number...
1
2016-09-29T16:14:19Z
39,780,497
<p>Try this:</p> <pre><code> z = 0 while z != "gg you win, noob": try: x = int(input("Insert a numer: ")) while x != 4: print("incorrect") x =int(input("Insert another number: ")) if x == 4: z = "gg you win, noob" print(z) except: ...
0
2016-09-29T21:43:03Z
[ "python" ]
Pandas: remove duplicate record while keeping its old value in dataframe for reference
39,775,337
<p>I am rewriting a piece of the old code using pandas. My data frame looks like this:</p> <pre><code>index stop_id stop_name stop_lat stop_lon stop_id2 0 A12 Some St 40.889248 -73.898583 None 1 A14 Some St 40.889758 -73.908573 None 2 B09 Some St 40.788924 ...
1
2016-09-29T16:17:07Z
39,775,530
<pre><code>new_df = df[df.duplicated(subset = ['stop_lat', 'stop_lon'], keep='first')] duplicates_df = df[df.duplicated(subset = ['stop_lat', 'stop_lon'], keep = 'last')][['stop_lat', 'stop_lon', 'stop_id']] new_df.merge(duplicates_df, how='left', on=['stop_lat, 'stop_lon']) </code></pre>
1
2016-09-29T16:28:00Z
[ "python", "pandas" ]
Pandas: remove duplicate record while keeping its old value in dataframe for reference
39,775,337
<p>I am rewriting a piece of the old code using pandas. My data frame looks like this:</p> <pre><code>index stop_id stop_name stop_lat stop_lon stop_id2 0 A12 Some St 40.889248 -73.898583 None 1 A14 Some St 40.889758 -73.908573 None 2 B09 Some St 40.788924 ...
1
2016-09-29T16:17:07Z
39,776,026
<p><strong><em>get duplicate mask</em></strong></p> <pre><code>cols = ['stop_lat', 'stop_lon'] dups = df.duplicated(subset=cols) </code></pre> <p><strong><em>subset df with mask</em></strong></p> <pre><code>nodups = df[~dups].set_index(cols) </code></pre> <p><strong><em>dups may be duplicated themselves</em></stron...
2
2016-09-29T16:57:38Z
[ "python", "pandas" ]
Python fromtimestamp() method inconsistent
39,775,408
<p>I am getting data from a WSO2 DAS, which contains a Unix time stamp. I have been developing this website using PyCharm. I primarily develop on a Windows 10 machine, occasionally on a MAC, and deploy on a Linux box. </p> <p>I have a fairly simple use case, where I want to take the date from WSO2, convert it to a hum...
2
2016-09-29T16:21:16Z
39,776,385
<p>Python probably uses the TZ from OS/shell environment.</p> <p>PyCharm seems to use TIME_ZONE found in settings.py file. <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones" rel="nofollow">Here</a> is the complete list of timezones. Try it and see.</p>
2
2016-09-29T17:18:50Z
[ "python", "osx", "datetime", "pycharm" ]
gitpython returns 'git push --porcelain origin' returned with exit code 128
39,775,489
<p>I'm trying to push a new git repo upstream using gitpython module. Below are the steps that I'm doing and get an error 128.</p> <pre><code># Initialize a local git repo init_repo = Repo.init(gitlocalrepodir+"%s" %(gitinitrepo)) # Add a file to this new local git repo init_repo.index.add([filename]) # Initial comm...
1
2016-09-29T16:25:43Z
39,792,455
<p>You need to capture the output from the git command.</p> <p>Given this Progress class:</p> <pre><code>class Progress(git.RemoteProgress): def __init__( self, progress_call_back ): self.progress_call_back = progress_call_back super().__init__() self.__all_dropped_lines = [] def upd...
-1
2016-09-30T13:15:29Z
[ "python", "gitpython" ]
Pandas - applying groupings and counts to multiple columns in order to generate/change a dataframe
39,775,506
<p>I'm sure what I'm trying to do is fairly simple for those with better knowledge of PD, but I'm simply stuck at transforming:</p> <pre><code>+---------+------------+-------+ | Trigger | Date | Value | +---------+------------+-------+ | 1 | 01/01/2016 | a | +---------+------------+-------+ | 2 |...
1
2016-09-29T16:26:39Z
39,775,612
<pre><code>df.groupby(['Date','Value']).count().unstack(level=-1) </code></pre>
2
2016-09-29T16:32:51Z
[ "python", "pandas", "dataframe" ]
Pandas - applying groupings and counts to multiple columns in order to generate/change a dataframe
39,775,506
<p>I'm sure what I'm trying to do is fairly simple for those with better knowledge of PD, but I'm simply stuck at transforming:</p> <pre><code>+---------+------------+-------+ | Trigger | Date | Value | +---------+------------+-------+ | 1 | 01/01/2016 | a | +---------+------------+-------+ | 2 |...
1
2016-09-29T16:26:39Z
39,776,108
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>GroupBy.size</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a>, also parameter <co...
1
2016-09-29T17:03:07Z
[ "python", "pandas", "dataframe" ]
Python switch case
39,775,536
<p>I am trying to use dictionary as switch case on python, however, the parameter does not seem to be pass to the called function, please help:</p> <pre><code>def switchcase(num,cc): def fa(num): out= num*1.1; def fb(num): out= num*2.2; def fc(num): out= num*3.3; def fd(num): ...
0
2016-09-29T16:28:22Z
39,775,560
<p>The problem is:</p> <pre><code>out=0 options[cc]; return out </code></pre> <p>Basically -- no matter what <code>options[cc]</code> gives you, you're going to return <code>0</code> because that's the value of <code>out</code>. Note that setting <code>out</code> in the various <code>fa</code>, <code>fb</code>, ... ...
6
2016-09-29T16:30:02Z
[ "python", "switch-statement" ]
Python - Check if part of element is in set
39,775,614
<p>I have a set with this output:</p> <pre><code> set( [Rule(chain='OUTPUT', num='3', pkts='0', bytes='0', target='ACCEPT', prot='tcp', opt='--', inp='*', out='*', source='0.0.0.0/0', destination='10.10.7.84', extra='tcp spt:7390'), Rule(chain='INPUT', num='1', pkts='0', bytes='0', target='ACCEPT', prot='tcp', opt='...
1
2016-09-29T16:32:55Z
39,775,733
<p>Untested code, but this is one way of going about it. If this rule should extend to any kind of equality check, I advise modifying the magic <code>__eq__(self, other)</code> method of the <code>Rule</code> class with the <code>rules_match</code> logic.</p> <pre><code>def rules_match(rule1, rule2): attributes_to...
0
2016-09-29T16:39:43Z
[ "python" ]
Get checkbox value in django
39,775,676
<p>I have passed a python list (list_exp) in my html template and now i would like to get the result of my multiple checkbox in view.py with a dictionary. {list_exp[0] : True/False, list_exp[1] : True/False.....} </p> <pre><code>&lt;form action="" method="post"&gt; {% for name in list_exp%} &lt;input type="checkbox" ...
0
2016-09-29T16:36:41Z
39,777,259
<p>From what I know, if you give every input checkbox the same name, you can refer to the them as a list in your views.py. </p> <p>So in the template:</p> <pre><code>{% for name in list_exp %} &lt;input type="checkbox" name="list_exp"&gt;&lt;label&gt; Experiment : {{name}}&lt;/label&gt; &lt;br&gt; {% endfor %} ...
0
2016-09-29T18:13:21Z
[ "python", "django", "input", "submit" ]
how to change r,g,b color to 2 coordinates in python?
39,775,699
<pre><code>from PIL import Image picture = Image.open("C:/Lab/photos/frog2.png") r,g,b = picture.getpixel( (0,0) ) print("Red: {0}, Green: {1}, Blue: {2}".format(r,g,b)) </code></pre> <p>the result is Red: 57, Green: 66, Blue: 19 but i want to change this r,g,b to 2 coorinates like(x,y)</p> <p>what should i type?</p...
0
2016-09-29T16:37:45Z
39,776,411
<p><a href="https://github.com/gtaylor/python-colormath" rel="nofollow"><code>colormath</code></a> can be used to convert a RGB color to a xyY color, and from there you can simply ignore the Y coordinate in order to get a xy chromacity.</p>
1
2016-09-29T17:20:10Z
[ "python", "python-2.7", "coordinates", "rgb", "dimensions" ]
How to enforce both xlim and ylim while using ax.axis('equal')?
39,775,709
<p>I want to use <code>ax.axis('equal')</code> to force even spacing on X &amp; Y, but I also want to prescribe specific ranges for the X and Y axes. If the margins are also fixed, the problem is over constrained and the result is shown on the left side of the Figure <a href="http://i.stack.imgur.com/Lv0mX.png" rel="no...
1
2016-09-29T16:38:08Z
39,795,483
<pre><code>ax.set_aspect('equal',adjustable='box') </code></pre> <p><a href="http://i.stack.imgur.com/hjGkL.png" rel="nofollow"><img src="http://i.stack.imgur.com/hjGkL.png" alt="enter image description here"></a></p>
2
2016-09-30T15:53:54Z
[ "python", "python-2.7", "matplotlib", "plot" ]
Decoding Actionscript ByteArray using python
39,775,727
<p>I am using actionscript to send an array to the server with this code(I am only writing that part of the code here):-</p> <pre><code>var a:ByteArray=new ByteArray; a.writeObject({'a':'b','c':'d'}); socket.writeBytes(a); socket.flush(); </code></pre> <p>here I already opened a socket to a port on my server and I ha...
1
2016-09-29T16:39:26Z
39,776,338
<p>ActionScript uses <a href="https://en.wikipedia.org/wiki/Action_Message_Format" rel="nofollow">AMF</a> format. There is an AMF library for Python which you can use: <a href="https://pypi.python.org/pypi/PyAMF" rel="nofollow">PyAMF</a>.</p> <p>I got this when I tested it (with <em>Python 2.7</em>):</p> <pre><code>&...
2
2016-09-29T17:15:37Z
[ "python", "arrays", "actionscript-3", "flex", "decode" ]
xlabels do not show up with seaborn and tight despined layout in python
39,775,747
<p>I would like to plot the following dataframe with xtick labels rotated while also having a tight, despined layout (using <code>tight_layout()</code> from matplotlib and <code>despine</code> from seaborn). the following does not work because the labels do not show up:</p> <pre><code>import matplotlib.pylab as plt im...
0
2016-09-29T16:40:13Z
39,777,362
<p>on my machine the following works</p> <pre><code>import matplotlib.pylab as plt import seaborn as sns import pandas df = pandas.DataFrame({"x": ["XYZ1", "XYZ2", "XYZ3", "XYZ4"], "y": [0, 1, 0, 1]}) plt.figure(figsize=(5,5)) sns.set_style("ticks") g = sns.pointplot(x="x", y="y", data=df) sns.d...
2
2016-09-29T18:19:07Z
[ "python", "matplotlib", "seaborn" ]
Extract series objects from Pandas DataFrame
39,775,828
<p>I have a dataframe with the columns</p> <pre><code>['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory'] </code></pre> <p>For each 'Part Number', 'Calendar Year/Month' will be unique on each Part Number.</p> <p>I want to convert each part number to a univariate Series with 'Calendar Year/Month' as ...
0
2016-09-29T16:44:51Z
39,776,167
<p>you can use the groupby method such has:</p> <pre><code>grouped_df = df.groupby('Part Number') </code></pre> <p>and then you can access the df of a certain part number and set the index easily such has:</p> <pre><code>new_df = grouped_df.get_group('THEPARTNUMBERYOUWANT').set_index('Calendar Year/Month') </code></...
1
2016-09-29T17:06:34Z
[ "python", "pandas", "dataframe", "time-series" ]
Extract series objects from Pandas DataFrame
39,775,828
<p>I have a dataframe with the columns</p> <pre><code>['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory'] </code></pre> <p>For each 'Part Number', 'Calendar Year/Month' will be unique on each Part Number.</p> <p>I want to convert each part number to a univariate Series with 'Calendar Year/Month' as ...
0
2016-09-29T16:44:51Z
39,776,221
<p>In pandas this is called a MultiIndex. Try:</p> <pre><code>import pandas as pd df = pd.DataFrame(file, index=['Part Number', 'Calendar Year/Month'], columns = ['Sales', 'Inventory']) </code></pre>
1
2016-09-29T17:08:47Z
[ "python", "pandas", "dataframe", "time-series" ]
Extract series objects from Pandas DataFrame
39,775,828
<p>I have a dataframe with the columns</p> <pre><code>['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory'] </code></pre> <p>For each 'Part Number', 'Calendar Year/Month' will be unique on each Part Number.</p> <p>I want to convert each part number to a univariate Series with 'Calendar Year/Month' as ...
0
2016-09-29T16:44:51Z
39,776,947
<p>From the answers and comments here, along with a little more research, I ended with the following solution.</p> <pre><code>temp_series = df[df[ "Part Number" == sku ] ].pivot(columns = ["Calendar Year/Month"], values = "Sales").iloc[0] </code></pre> <p>Where sku is a specific part number from df["Part Number"].uni...
0
2016-09-29T17:53:24Z
[ "python", "pandas", "dataframe", "time-series" ]
Include two different sized data frames together in a pandas panel
39,776,122
<p>I'm crafting a panel of multiple data frames. Each is rather long. </p> <p>I create the dfs, combine in a dictionary, then combine into a panel;</p> <pre><code>for name in names: # large list of paths # Do some code to get data info (dI), dataframe (df) and nameID # Create a dictionary out of dfs by nameID...
0
2016-09-29T17:03:37Z
39,966,207
<p>I was able to solve this. The key to it was converting the dataframe to a tuple and using the tuple as the dictionary key such that the panel key was immutable:</p> <pre><code>for name in names: # List of names nm = base(name)[:-4] # Uses each name to extract, trim, cure, and make meaningful dfInfo,df ...
0
2016-10-10T20:26:58Z
[ "python", "pandas", "panel", "pickle" ]
How do i include the csrf_token to dropzone Post request (Django)
39,776,136
<p>Allright this is resolved. Just editing in case anyone runs into the same problem.</p> <p>Add the Code posted in Comment marked as answer in the same javascript file. When defining</p> <pre><code>var myDropzone = new Dropzone(... ...//More stuff here headers:{ 'X-CSRFToken' : csrftoken } </code></pre> ...
1
2016-09-29T17:04:43Z
39,776,233
<p>The <a href="https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax" rel="nofollow">docs</a> recommend getting the CSRF token from the cookie, not the DOM. Try that.</p>
0
2016-09-29T17:09:20Z
[ "javascript", "jquery", "python", "django", "dropzone.js" ]
How do i include the csrf_token to dropzone Post request (Django)
39,776,136
<p>Allright this is resolved. Just editing in case anyone runs into the same problem.</p> <p>Add the Code posted in Comment marked as answer in the same javascript file. When defining</p> <pre><code>var myDropzone = new Dropzone(... ...//More stuff here headers:{ 'X-CSRFToken' : csrftoken } </code></pre> ...
1
2016-09-29T17:04:43Z
39,776,325
<p>Django’s docs have a <a href="https://docs.djangoproject.com/en/stable/ref/csrf/#ajax" rel="nofollow">reference for this</a>:</p> <blockquote> <p>While [a special parameter] can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POS...
0
2016-09-29T17:14:52Z
[ "javascript", "jquery", "python", "django", "dropzone.js" ]
How do i include the csrf_token to dropzone Post request (Django)
39,776,136
<p>Allright this is resolved. Just editing in case anyone runs into the same problem.</p> <p>Add the Code posted in Comment marked as answer in the same javascript file. When defining</p> <pre><code>var myDropzone = new Dropzone(... ...//More stuff here headers:{ 'X-CSRFToken' : csrftoken } </code></pre> ...
1
2016-09-29T17:04:43Z
39,776,634
<p>just place <code>{% csrf_token %}</code> anywhere in your Html file . it's automatically add </p> <pre><code> &lt;input type="hidden" name="csrfmiddlewaretoken" value="**************" /&gt; </code></pre> <p>Before sending data to the server just add extra field <code>csrf_token</code> which value is <code>$("inpu...
0
2016-09-29T17:34:04Z
[ "javascript", "jquery", "python", "django", "dropzone.js" ]
Python print on same line after delay
39,776,182
<p>This is my code:</p> <pre><code>def get(url): print 'GET: ' + url, r = requests.get(url) print 'DONE' return r get('https://www.###.com/getfoo') </code></pre> <p>The output:</p> <blockquote> <p>GET: <a href="https://www.###.com/getfoo">https://www.###.com/getfoo</a> DONE</p> </blockquote> <p><...
0
2016-09-29T17:07:24Z
39,776,252
<p>Because the console is line-buffering the output. Call <code>sys.stdout.flush()</code> in order to flush it.</p>
2
2016-09-29T17:10:36Z
[ "python" ]
Python print on same line after delay
39,776,182
<p>This is my code:</p> <pre><code>def get(url): print 'GET: ' + url, r = requests.get(url) print 'DONE' return r get('https://www.###.com/getfoo') </code></pre> <p>The output:</p> <blockquote> <p>GET: <a href="https://www.###.com/getfoo">https://www.###.com/getfoo</a> DONE</p> </blockquote> <p><...
0
2016-09-29T17:07:24Z
39,776,326
<p>Its bcs print() doen not flush to stdout;</p> <p>You can do it like this </p> <pre><code>import requests from sys import stdout def get(url): stdout.write( 'GET: ' + url+"\n"); stdout.flush(); # this func() will flush all to stdout r = requests.get(url); print("DONE"); return r; get("http://...
1
2016-09-29T17:14:53Z
[ "python" ]
Google Sheets API - Formatting inserted values
39,776,188
<p>Through this code I've update a bunch of rows in Google Spreadsheet. The request goes well and returns me the <code>updatedRange</code> below.</p> <pre><code>result = service.spreadsheets().values().append( spreadsheetId=spreadsheetId, range=rangeName, valueInputOption="RAW", insertDataOption="INSER...
0
2016-09-29T17:07:29Z
39,838,566
<p>Waiting for a native or better answer, I'll post a function I've created to translate a <code>namedRange</code> into a <code>gridRange</code>. The function is far from perfect and does not translate the sheet name to a sheet id (I left that task to another specific function), but accept named ranges in the form:</p>...
0
2016-10-03T18:57:49Z
[ "python", "google-spreadsheet-api" ]
Using .replace() method on a string read from HTML file containing Unicode
39,776,201
<p>I want to read a .html file as raw text and replace instances of a substring that contains unicode characters with another substring. Assume that the file <code>mm03.html</code> contains only one line of text:</p> <pre><code>&lt;span style='font-size:14.0pt'&gt;«test»&lt;/span&gt; </code></pre> <p>I would like t...
0
2016-09-29T17:07:51Z
39,777,256
<p>You need to decode the string that you want to replace before passing it to <code>str.replace()</code>. This works for me:</p> <pre><code># -*- coding: utf-8 -*- import codecs htmlBase = codecs.open("mm03.html",'r') htmlFill = htmlBase.read() htmlFill = codecs.decode(htmlFill,'utf-8') substr = codecs.decode("«test...
0
2016-09-29T18:13:07Z
[ "python", "html", "string", "unicode", "io" ]
Setting rules with scrapy crawlspider
39,776,236
<p>I'm trying out the scrapy CrawlSpider subclass for the first time. I've created the following spider strongly based on the docs example at <a href="https://doc.scrapy.org/en/latest/topics/spiders.html#crawlspider-example" rel="nofollow">https://doc.scrapy.org/en/latest/topics/spiders.html#crawlspider-example</a>:</p...
0
2016-09-29T17:09:28Z
39,810,686
<p>First of all, the purpose of using rules is to not only extract links, but, above all, follow them. If you just want to extract links (and, say, save them for later), you don't have to specify spider rules. If you, on the other hand, want to download the images, use a <a href="https://doc.scrapy.org/en/latest/topics...
1
2016-10-01T19:31:33Z
[ "python", "scrapy" ]
How to determine function parameter type in python?
39,776,321
<p>For example I have a poorly documented library. I have an object from it and I want to know what are the types of the arguments certain method accepts.</p> <p>In IPython I can run</p> <pre><code>In [28]: tdb.getData? Signature: tdb.getData(time, point_coords, sinterp=0, tinterp=0, data_set='isotropic1024coarse', g...
0
2016-09-29T17:14:47Z
39,776,651
<p>Usually, functions in Python accept arguments of any type, so you cannot define what type it expects.</p> <p>Still, the function probably does make some implicit assumptions about the received object.</p> <p>Take this function for example:</p> <pre><code>def is_long(x): return len(x) &gt; 1000 </code></pre> ...
1
2016-09-29T17:35:11Z
[ "python", "types" ]
Can't get Scrapy to parse and follow 301, 302 redirects
39,776,377
<p>I'm trying to write a very simple website crawler to list URLs along with referrer and status codes for 200, 301, 302 and 404 http status codes.</p> <p>Turns out that Scrapy works great and my script uses it correctly to crawl the website and can list urls with 200 and 404 status codes without problems.</p> <p><st...
0
2016-09-29T17:18:03Z
39,788,550
<p>If you want to parse 301 and 302 responses, and follow them at the same time, ask for 301 and 302 to be processed by your callback and mimick the behavior of RedirectMiddleware.</p> <h2>Test 1 (not working)</h2> <p>Let's illustrate with a simple spider to start with (not working as you intend yet):</p> <pre><code...
0
2016-09-30T09:48:40Z
[ "python", "scrapy" ]
SPARQL Parser for INSERT and DELETE queries
39,776,519
<p>I need to test if a certain <code>SPARQL</code> queries are indeed an <code>INSERT</code> or <code>DELETE</code> statements. Therefore, I have been using different parsers (mainly, <code>fyzz</code> and <code>SPARQLWrapper</code>) as follow: </p> <pre><code>try: sparql = parse(Query_String) except Exception as ...
0
2016-09-29T17:27:08Z
39,908,261
<p>SPARQLWrapper is not actually intended as a SPARQL parser. All it does is act as a client for a SPARQL endpoint service - AFAICT the actual parsing of the query string is done by the endpoint itself.</p> <p>In your specific example, you're pointing SPARQLWrapper to a local file, which simply won't work, because a l...
0
2016-10-07T02:06:09Z
[ "python", "parsing", "sparql", "rdf" ]
Python WMI Network Adapter Configuration parameter issue [Windows 8.1] [Python 2.7] [WMI 1.4.9]
39,776,521
<p>When I try to do this</p> <pre><code>SetDynamicDNSRegistration(True) </code></pre> <p>It returns '68' which I have looked up on the <a href="https://msdn.microsoft.com/en-us/library/aa393298(v=vs.85).aspx" rel="nofollow">MSDN WMI page</a> and it means "Invalid Input Parameter".</p> <p><strong>Full Script</strong>...
1
2016-09-29T17:27:11Z
39,797,654
<p>Rather than a Python boolean, use its corresponding boolean integer. So instead of</p> <pre><code>nic.SetDynamicDNSRegistration(True) </code></pre> <p>use</p> <pre><code>nic.SetDynamicDNSRegistration(FullDNSRegistrationEnabled=1) </code></pre>
0
2016-09-30T18:15:52Z
[ "python", "wmi" ]
How to go one or more levels using os.chdir with '..''s as arguments
39,776,616
<p>How do I change path in Python using '..' to go down one or more levels as argument to os.chdir(). So that if I am on /home/usr/one and I want to go to 'home' directory a '../..' argument to chdir will do it. Do I wrap the argument in some other function? </p>
0
2016-09-29T17:33:08Z
39,776,734
<p>As you say in your question, if you are in the directory <code>/home/usr/one</code> <code>os.chdir('../../')</code> will bring you to <code>/home/</code>. </p> <p>You can confirm this by calling:</p> <pre><code>os.getcwd() </code></pre> <p>Before and after changing directories. This function will show you the cur...
0
2016-09-29T17:39:40Z
[ "python", "python-2.7", "python-3.x" ]
How can I write my inventory program so that it reads and writes to a text file?
39,776,705
<p>Basically, I'm trying to write a fairly simple, user-friendly program for the repair shop I'm working at. We've been trying to figure out a good way to organize and track LCD usage, so I've been working on this thing as a possible option.</p> <p>I need it to do a few other things, but my main concern right now is g...
-1
2016-09-29T17:37:59Z
39,777,226
<p>To put you on the right track, here is a minimal example that reads a JSON text file in the same directory, modifies it, and then writes it back.</p> <p>First, here is the JSON file:</p> <p>data.txt</p> <pre><code>{"milk": 5, "orange juice": 3, "cookies": 1} </code></pre> <p>Here is a program that reads this jso...
0
2016-09-29T18:10:51Z
[ "python", "dictionary", "inventory" ]
Python remove dictionaries from list
39,776,786
<p>Python listed dictionaries:</p> <pre><code>_list_ = [{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value3', 'key2': 'value4'}] example_search_str1 = 'e1' # for value1 of key1 example_search_str2 = 'e3' # for value3 of key1 </code></pre> <p>I want to delete listed dictionaries containing multiple example search...
0
2016-09-29T17:42:50Z
39,776,822
<p>Your question is a little unclear, but as I understand it, you want to remove dictionaries from a list if their 'key1' value is one of some number of strings.</p> <pre><code>bad_strings = ['e1', 'e3'] new_list = [d for d in old_list if d['key1'] not in bad_strings] </code></pre> <p>EDIT:</p> <p>Oh, I get it. I ...
0
2016-09-29T17:45:15Z
[ "python", "list", "dictionary" ]
Python remove dictionaries from list
39,776,786
<p>Python listed dictionaries:</p> <pre><code>_list_ = [{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value3', 'key2': 'value4'}] example_search_str1 = 'e1' # for value1 of key1 example_search_str2 = 'e3' # for value3 of key1 </code></pre> <p>I want to delete listed dictionaries containing multiple example search...
0
2016-09-29T17:42:50Z
39,777,082
<p>Also for matching (key, unwanted_value) I would maybe try smthng like:</p> <pre><code>list_of_dicts = [{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value3', 'key2': 'value4'}] bad_keys_vals = [('key1', 'value1'), ('key2', 'value2')] def filter_dict_list(list_of_dicts, bad_keys_vals): return list(filter(la...
0
2016-09-29T18:01:06Z
[ "python", "list", "dictionary" ]
AttributeError: '__proxy__' object has no attribute 'regex'
39,776,854
<p>My urls.py looks like this; can anyone explain where the error (AttributeError: '<strong>proxy</strong>' object has not attribute 'regex') is coming from? Because the error message isn't giving me any place where the error is coming from, so I'm really confused. Thanks! </p> <pre><code>from django.conf import setti...
0
2016-09-29T17:47:34Z
39,777,086
<p>You have a stray <code>reverse_lazy()</code> in your urlpatterns:</p> <pre><code>urlpatterns = patterns('', url(r"^$", TemplateView.as_view(template_name = "homepage.html")), reverse_lazy("homepage.html"), </code></pre>
1
2016-09-29T18:01:10Z
[ "python", "regex", "django" ]
Make the Python Turtle screen self adjust to show what's been drawn?
39,776,865
<p>I've been trying to find an answer to this all over the internet, and just can't find anything that works. </p> <p>Essentially, I'm building my very first program which is a <code>digital spirograph</code>. One of the features of this is that you can have the turtle randomly draw a shape using fairly chaotic variab...
0
2016-09-29T17:48:23Z
39,777,581
<p>resize the window using the following code in python</p> <p>By the way your question is duplicated I think.</p> <p><a href="http://stackoverflow.com/questions/831894/python-imaging-resize-turtle-graphics-window">Python imaging, resize Turtle Graphics window</a></p> <pre><code>setup( width = 200, height = 200, sta...
0
2016-09-29T18:33:04Z
[ "python" ]
Skew a diagonal gradient to be vertical
39,776,890
<p>I have a not-quite linear gradient at some angle to the horizontal as an image. Here's some toy data:</p> <pre><code>g = np.ones((5,20)) for x in range(g.shape[0]): for y in range(g.shape[1]): g[x,y] += (x+y)*0.1+(y*0.01) </code></pre> <p><a href="http://i.stack.imgur.com/ytcp6.png" rel="nofollow"><img...
3
2016-09-29T17:49:27Z
39,806,897
<p>You can intepolate to determine the skewness and interpolate again to correct it. </p> <pre><code>import numpy as np from scipy.ndimage.interpolation import map_coordinates m, n = g.shape j_shift = np.interp(g[:,0], g[0,:], np.arange(n)) pad = int(np.max(j_shift)) i, j = np.indices((m, n + pad)) z = map_coordinate...
1
2016-10-01T12:59:39Z
[ "python", "arrays", "numpy", "transform" ]
How to compile cython module for multiple platforms on windows?
39,776,911
<p>Is there way to compile specified cython files for multiple platforms? If so, how to do it?</p> <p>I need compile module for linux and windows both by one tool (also would be nice if this also can be compiled to other popular platforms).</p> <p>This is distutils' settings?</p>
1
2016-09-29T17:51:04Z
39,798,610
<p>I'm not sure that it will completely answer your question but if you want to distribute a python package (containing c/cython code) to various platform you can use some continuous integration services to build <code>wheels</code> on specific platforms and then distribute them.</p> <p>For example you can use <a href...
0
2016-09-30T19:15:58Z
[ "python", "compilation", "cross-platform", "cross-compiling", "cython" ]
How to get files from Remote windows server to local Windows machine directory?
39,776,926
<p>I am using a tool which will create files in remote windows 2012 servers continuously. I need to get those files and place it in a local directory.</p> <pre><code>import os import time def copy_logs(): os.system(".\pscp.exe -pw test123 C:/Users/Administrator/Desktop/tr* Administrator@1.1.1.1:/") time.sleep...
0
2016-09-29T17:52:15Z
39,777,004
<p>The best solution I know, is to use <a href="http://www.fabfile.org/" rel="nofollow">Fabric</a>. See: <a href="http://stackoverflow.com/questions/5314711">How do I copy a directory to a remote machine using Fabric?</a>.</p>
0
2016-09-29T17:56:57Z
[ "python", "python-2.7" ]
Create or modify DataFrame using another DataFrame
39,777,018
<p>I currently have a Pandas DataFrame looking like this:</p> <pre><code> DATESTAMP price name pct_chg 0 2006-01-02 62.987301 a 0.000000 1 2006-01-03 61.990700 a -0.015822 2 2006-01-04 62.987301 a 0.016077 3 2006-01-05 62.987301 a ...
2
2016-09-29T17:57:49Z
39,777,083
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a>:</p> <pre><code>print (df.s...
2
2016-09-29T18:01:07Z
[ "python", "pandas", "dataframe", "pivot", "reshape" ]
subprocess.check_output(), zgrep, and match limit
39,777,039
<p>Context: I'm trying to find a github repository of a python package. To do that, I'm zgrep'ping package archive for github urls. And it works fine until I limit output by 1 result:</p> <pre><code># works, returns a lot of results subprocess.check_output(["zgrep", "-oha", "github", 'Django-1.10.1.tgz']) # works, a...
0
2016-09-29T17:58:51Z
39,778,977
<p>So, the reason is: zgrep is a shell script, which simply pipes the archive through gzip and egrep. If we limit number of results, egrep terminates the pipe, so gzip exits and complaints. In a console we never see it, but subprocess somehow catches this signal and raises an exception.</p> <p>Solution: write mini-ver...
0
2016-09-29T19:59:21Z
[ "python", "bash", "subprocess", "zgrep" ]
Writing to a mac csv not working using python file writter
39,777,207
<p>I have a python code where it compares two files and returns the common lines and writes them to a result file. I am using a MAC machine.</p> <p>script.py</p> <pre><code>with open('temp1.csv', 'r') as file1: with open('serialnumbers.txt', 'r') as file2: same = set(file1).intersection(file2) pri...
0
2016-09-29T18:09:53Z
39,777,453
<p>The end delimiters of the two files are different.</p> <ul> <li>The .csv file probably has Windows end of line: "\r\n",</li> <li>The .txt file probably has Posix end of line: "\n".</li> </ul> <p>So, in binary mode, lines always differ.</p> <p>You ought to read the two files in text mode, like this:</p> <pre><cod...
2
2016-09-29T18:25:02Z
[ "python", "csv", "file-writing", "macbook" ]
Python: Break down large file, filter based on criteria, and put all data into new csv file
39,777,240
<p>I have a super large csv.gzip file that has 59 mill rows. I want to filter that file for certain rows based on certain criteria and put all those rows in a new master csv file. As of now, I broke the gzip file into 118 smaller csv files and saved them on my computer. I did that with the following code:</p> <pre><co...
1
2016-09-29T18:12:10Z
39,778,035
<p>When you use file.write(df_f) you are effectively saving a string representation of the DataFrame, which is meant for humans to look at. By default that representation will truncate rows and columns so that large frames can be displayed on the screen in a sensible manner. As a result column "a" may get chopped.</p> ...
0
2016-09-29T18:58:44Z
[ "python", "csv", "pandas" ]
Python: Break down large file, filter based on criteria, and put all data into new csv file
39,777,240
<p>I have a super large csv.gzip file that has 59 mill rows. I want to filter that file for certain rows based on certain criteria and put all those rows in a new master csv file. As of now, I broke the gzip file into 118 smaller csv files and saved them on my computer. I did that with the following code:</p> <pre><co...
1
2016-09-29T18:12:10Z
39,807,939
<pre><code>import pandas import glob csvFiles = glob.glob(path + "/split files/*.csv") list_ = [] for files in csvFiles: df = pandas.read_csv(files, index_col=None) df_f = df[(df['a']==7) &amp; (df['b'] == 2016) &amp; (df['c'] =='D') &amp; df['d']=='US')] list_.append(df_f) frame = pandas.concat(list_, igno...
0
2016-10-01T14:46:24Z
[ "python", "csv", "pandas" ]
weird behavior of multiprocessing scipy optimization inside of a function
39,777,299
<p>Here is a simple code that runs well. Even if the function minimize wraps the scipy.optimize.minimize it does not complain about pickling </p> <pre><code>import numpy as np from scipy import optimize from multiprocessing import Pool def square(x): return np.sum(x**2+ 2*x) def minimize(args): f,x = args ...
1
2016-09-29T18:15:03Z
39,780,889
<p>The problem is that Python cannot pickle nested functions, and in your second example, you're trying to pass the nested <code>minimize</code> and <code>square</code> functions to your child process, which requires pickling. </p> <p>If there's no reason that you must nest those two functions, moving them to the top-...
0
2016-09-29T22:18:35Z
[ "python", "optimization", "parallel-processing", "scipy", "multiprocessing" ]
subprocess.Popen: 'OSError: [Errno 13] Permission denied' only on Linux
39,777,345
<blockquote> <p>Code and logs have changed a lot (due to a major rewrite) since the question was asked.</p> </blockquote> <p>When my code (given below) executes on Windows (both my laptop and AppVeyor CI), it does what it's supposed to do. But on Linux (VM on TravisCI), it throws me a permission denied error.</p> <...
0
2016-09-29T18:18:09Z
39,779,631
<p>This is pretty much off topic on SO, but here's your problem...</p> <p>This is the executable you are trying to run:</p> <pre><code>-rw-rw-r-- 1 travis travis 276306 Sep 29 20:14 espeak </code></pre> <p>Its permissions are <code>rw-</code> read+write for owner (travis), <code>rw-</code> read+write for group (trav...
1
2016-09-29T20:42:10Z
[ "python", "linux", "python-3.x", "cross-platform", "travis-ci" ]
Possible to change directory and have change persist when script finishes?
39,777,348
<p>In trying to answer <a href="http://stackoverflow.com/q/39776616/3642398">a question for another user</a>, I came across something that piqued my curiosity:</p> <pre><code>import os os.chdir('..') </code></pre> <p>Will change the working directory as far as Python is concerned, so if I am in <code>/home/username/<...
4
2016-09-29T18:18:20Z
39,777,583
<p>There is no way to do that because calling Python or bash will run everything within their own context (that ends when the script ends).</p> <p>You could achieve those results by using <code>source</code>, since that will actually execute your (shell) script in the current shell. i.e., call your example script with...
2
2016-09-29T18:33:24Z
[ "python" ]
convert code from boto to bot3
39,777,353
<p>I have a code which uploads base64 image to amazon s3 using boto version 2.38.0</p> <pre><code>conn = boto.connect_s3(AWS_ACCESS_KEYXXX, AWS_SECRET_KEYXXX) bucket = conn.get_bucket(AWS_BUCKET_NAMEXXX) k = Key(bucket) k.key = s3_file_name k.set_metadata('Content-Type', 'image/jpeg') k.set_contents_from_file(&lt...
0
2016-09-29T18:18:44Z
39,797,492
<p>In order to generate public URL you can use following code</p> <pre><code>k.set_acl('public-read') # make file public url = k.generate_url(expires_in=0, query_auth=False) </code></pre> <p>If you want to generate temporary link then you can change expires_in parameter </p> <p><strong>Hope it helps...
1
2016-09-30T18:04:05Z
[ "python", "boto", "boto3" ]
Selecting checboxes based on the parameters
39,777,403
<p>Let's say I have bunch of check boxes listed as below:</p> <ol> <li>All</li> <li>Test1</li> <li>Test3</li> <li>Test 4</li> </ol> <p>When the user goes to the application sometimes all are selected and sometimes only b and c are selected. I want to write a script which can do two things:</p> <ol> <li>Select All fi...
-2
2016-09-29T18:21:51Z
39,790,971
<p>This is what I understand from your problem description:</p> <p>If <code>All</code> is selected do not do anything. If <code>All</code> is not selected, there is a flag which determines what operation to do. (In this case I will use List of Elements is empty? flag)</p> <ol> <li>If false --> select <code>All</code...
0
2016-09-30T11:56:23Z
[ "python", "selenium" ]
In MongoDB, how do I find distinct values of a large, sharded collection?
39,777,491
<p>I have a large mongodb collection:</p> <ul> <li>with 3 shards, </li> <li>Totalling 300M records (at least)</li> <li>Shard key is (field1:1,field2:1)</li> <li>There are other non-indexed fields. </li> <li>Field1 is a ~200-characters string </li> <li>Field2 is an int. </li> <li>There are about 10M distinct v...
0
2016-09-29T18:27:14Z
39,784,773
<p>A collection distinct command (<a href="https://docs.mongodb.com/manual/reference/command/distinct/#dbcmd.distinct%20link" rel="nofollow">doc link</a>) returns a single variable, an array. This variable is sent as a BSON document, which has 16MB max size limit in MongoDB.</p> <p>Having the result set in an array is...
1
2016-09-30T06:08:50Z
[ "python", "mongodb-query" ]
How to speed up three dimensional sum for Madelung Constant?
39,777,534
<p>For my Computational Physics class we have to compute the <a href="https://en.wikipedia.org/wiki/Madelung_constant" rel="nofollow">Madelung Constant</a> for NaCl. My code to do this uses three nested for loops and therefore runs very slowly. I was wondering if there was a way to use arrays or some other method to in...
2
2016-09-29T18:30:02Z
39,779,327
<p>Since you've noted in a comment that you may use <code>numpy</code>, I suggest doing that. You can construct a 3d grid for your integers, and compute each term simultaneously, thereby vectorizing your calculation. You only need to watch out for the singular case where every integer is 0, for instance using <a href="...
1
2016-09-29T20:22:27Z
[ "python", "performance", "numpy", "vectorization" ]
How to speed up three dimensional sum for Madelung Constant?
39,777,534
<p>For my Computational Physics class we have to compute the <a href="https://en.wikipedia.org/wiki/Madelung_constant" rel="nofollow">Madelung Constant</a> for NaCl. My code to do this uses three nested for loops and therefore runs very slowly. I was wondering if there was a way to use arrays or some other method to in...
2
2016-09-29T18:30:02Z
39,786,927
<p>Here's an approach using open meshes with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ogrid.html" rel="nofollow"><code>np.ogrid</code></a> instead of creating actual meshes, which based on <a href="http://stackoverflow.com/a/39667342/3293881"><code>this other post</code></a> must be pretty eff...
2
2016-09-30T08:25:56Z
[ "python", "performance", "numpy", "vectorization" ]
Pressing Enter to skip print?
39,777,553
<p>I'm making a sort of text based game in python and I was wondering if there was a way to skip print's while playing by just pressing enter. </p> <p>Let's say I have this code.</p> <pre><code> print("BORING") time.sleep(5) print("ANNOYED") time.sleep(5) </code></pre> <p>and I just want to skip the w...
1
2016-09-29T18:31:00Z
39,777,687
<p>You'll need to handle this asynchronously, because you want to be handling two things at the same time. You want to both listen to some kind of input and print out something. </p> <p>Create an asynchronous task -> let it prent</p> <p>AND at the same time listen for input() (or another way of registering keypresses...
0
2016-09-29T18:39:01Z
[ "python" ]
Pressing Enter to skip print?
39,777,553
<p>I'm making a sort of text based game in python and I was wondering if there was a way to skip print's while playing by just pressing enter. </p> <p>Let's say I have this code.</p> <pre><code> print("BORING") time.sleep(5) print("ANNOYED") time.sleep(5) </code></pre> <p>and I just want to skip the w...
1
2016-09-29T18:31:00Z
39,778,557
<p>For speeding up your text, you could map the text to a function that prints it all (or iterates through it and prints one letter/word at a time... depending on what it is you're trying to accomplish). This function could be called on keypress using the tkinter library:</p> <pre><code>import tkinter def speed_up(ev...
0
2016-09-29T19:31:51Z
[ "python" ]
Is there any way to load a template dynamically inside of a static navbar template based on the current url?
39,777,664
<p>Hi I'm new to django and I'm trying to make a site with it. My project structure is currently like so: </p> <pre><code>project/ manage.py project/ __init__.py settings.py urls.py myapps/ __init__.py main/ __init__,models,views,urls,etc...
0
2016-09-29T18:37:14Z
39,777,911
<p>You're thinking about this the wrong way round: you should use template inheritance. Your view should render the specific template for that URL, but each template should in turn extend index.html which provides the sidebar and the rest of the structure.</p>
1
2016-09-29T18:50:53Z
[ "python", "django", "redirect", "django-templates" ]
How to update nltk package so that it does not break email into 3 different tokens?
39,777,806
<p>When I type following code: <code>tokens = word_tokenize("a@b.com")</code></p> <p>It gets broken into these 3 tokens: 'a' , '@' , 'b.com'</p> <p>What I want to do, is to keep it as a single token 'a@b.com'.</p>
1
2016-09-29T18:44:33Z
39,780,323
<p><em>DISCLAIMER: There are a lot of email regexps out there. I am not trying to match all email formats in this question, just showing an example</em>.</p> <p>A regex approach with <code>RegexpTokenizer</code> (<a href="http://stackoverflow.com/questions/39777806/how-to-update-nltk-package-so-that-it-does-not-break-...
1
2016-09-29T21:28:35Z
[ "python", "regex", "nlp", "nltk" ]
django-auth-ldap not finding groups
39,777,854
<p>I am using a fork of django-auth-ldap (django-auth-ldap-ng==1.7.6) with pyldap==2.4.25.1 to connect to ldap. I am able to successfully log in but I am running into errors. I am getting a DN_SYNTAX error even though I am able to still log in with ldap credentials and map attributes. Here is the main error code:</p> ...
0
2016-09-29T18:47:27Z
39,861,232
<p>I was able to solve this with the solution provided here:</p> <p><a href="https://bitbucket.org/psagers/django-auth-ldap/issues/21/cant-bind-and-search-on-activedirectory" rel="nofollow">https://bitbucket.org/psagers/django-auth-ldap/issues/21/cant-bind-and-search-on-activedirectory</a></p> <p>It is a work around ...
0
2016-10-04T20:31:06Z
[ "python", "django", "ldap", "django-auth-ldap" ]
How can I sort a nested list accordign to each element in nested lists
39,777,961
<p>I have a model Page which stores an optional parent page (instance of itself). In my views I made a function which will return a nested list of all pages and their parents.</p> <p>For example, my page architecture is</p> <pre><code>CCC AAA DDD KKK EEE ZZZ BBB </code></pre> <p>So DDD has the pare...
0
2016-09-29T18:54:14Z
39,778,336
<p>Using a tree of Pages:</p> <p>I define this simple tree structure:</p> <pre><code>class Page(object): def __init__(self, name, children=None): self.name = name self.children = children or [] def display(self, indent=""): child_repr = [child.display(indent=indent + " ") for child i...
0
2016-09-29T19:18:27Z
[ "python", "django", "sorting", "order", "nested-lists" ]
How can I sort a nested list accordign to each element in nested lists
39,777,961
<p>I have a model Page which stores an optional parent page (instance of itself). In my views I made a function which will return a nested list of all pages and their parents.</p> <p>For example, my page architecture is</p> <pre><code>CCC AAA DDD KKK EEE ZZZ BBB </code></pre> <p>So DDD has the pare...
0
2016-09-29T18:54:14Z
39,778,668
<p>Take advantage of helper functions in itertools and do your sorting with a simple and highly efficient one-line comparison function.</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; from itertools import dropwhile, izip_longest &gt;&gt;&gt; pages = [['CCC', 'AAA'], ... ['ZZZ', 'BBB'], ... ['...
0
2016-09-29T19:39:25Z
[ "python", "django", "sorting", "order", "nested-lists" ]
Django 1.9 doesnt filter query results
39,777,995
<p>I have a form where the options of one of my select input are related to another table.</p> <p>Everything works perfectly, but know i want to exclude some options so i have the following kode in <em>forms.py</em>:</p> <pre><code>class employeesForm(forms.ModelForm): def __init__(self, *args, **kwargs): ...
0
2016-09-29T18:55:52Z
39,780,494
<p>Related objects in ModelForms are <code>ModelChoiceField</code>s. You need to specify the <code>queryset=...</code> attribute.</p> <p>Example:</p> <pre><code>class Department(models.Model): name = models.CharField() active = models.BooleanField() class Employee(models.Model): name = models.CharField(...
1
2016-09-29T21:42:49Z
[ "python", "django-forms", "filtering", "django-1.9" ]
Concatenate nested python lists column-wise (similar to numpy.hstack() )
39,778,025
<p>I am trying to concatenate two nested lists column-wise in Python. This is similar to numpy.hstack() but is in base Python with Python lists. I am able to do this in the following way. Is there a better, potentially faster way of concatenating nested lists column-wise?</p> <pre><code>list_a = [[2, 2], [4, 4], [6, 6...
0
2016-09-29T18:58:18Z
39,778,026
<p>List comprehension might not be faster, but it is cleaner.</p> <pre><code>[a + b for a,b in zip(list_a,list_b)] </code></pre> <p>or</p> <pre><code>[a.extend(b) for a,b in zip(list_a,list_b)] </code></pre>
1
2016-09-29T18:58:18Z
[ "python", "list" ]
retrieve data sqlite3 into list python
39,778,032
<p>I want to retrieve data from sqlite3 table, this is my code, but I only get an empty list. I checked my query on the sqlite3 and it works fine there.</p> <pre><code>import sqlite3 conn = sqlite3.connect("testee.db") c = conn.cursor() myquery = ("SELECT stock FROM testproduct WHERE store=3;") c.execute(myquery) temp...
0
2016-09-29T18:58:25Z
39,778,140
<p>I found out the error just now. The database file in that directory was empty. I copied the filled in file to the directory python is running and it works fine.</p>
0
2016-09-29T19:05:45Z
[ "python", "sqlite", "sqlite3", "cursor", "fetchall" ]
Scrapy - processing items with pipeline
39,778,086
<p>I'm running <code>scrapy</code>from a <code>python script</code>.</p> <p>I was told that in <code>scrapy</code>, <code>responses</code> are built in <code>parse()</code>and further processed in <code>pipeline.py</code>. </p> <p>this is how my <code>framework</code> is set so far:</p> <p><strong>python script</str...
0
2016-09-29T19:01:33Z
39,778,588
<p>I suggest that you build well structured <code>item</code> in spider. In Scrapy Framework work flow, spider is used to built well-formed item, e.g., parse html, populate item instances and pipeline is used to do operations on item, e.g., filter item, store item.</p> <p>For your application, if I understand correctl...
0
2016-09-29T19:33:43Z
[ "python", "scrapy" ]
Modbus device halts communication without a reason
39,778,116
<p>My company has bought several room thermostats with modbus capability. Those are from China. When I communicate with them on Modbus RTU, interesting things happen. Devices sometimes dont respond to me at all. Then in following polls, they sometimes respond. But in the end, after some time, be it one hour or two days...
-2
2016-09-29T19:04:37Z
39,821,010
<p>By the look of your screenshot, I think that you are not waiting long enough for the thermostat's reply. First request: the reply from "instrument1" is not received in the time frame you have configured. So your program sends a request to "instrument2", but receives the late reply for "instrument1". The rest of your...
1
2016-10-02T19:48:56Z
[ "python", "modbus" ]
Understanding behaviour of self with static variables
39,778,235
<p>I am confused with the behaviour of self when it comes to dealing with static variables in python.From what I understand is that static variables can be accessed by either using <code>classname.variablename</code> or <code>self.variablename</code>. However changing the value of that variable differs. I realized that...
-1
2016-09-29T19:12:28Z
39,778,326
<p><code>self</code> in python is an ordinary name that binds the reference to the <em>instance</em> calling a class method. It is passed as the first argument to a method and by convention, it is bound to the name 'self'. When <code>self.variable = value</code> is called, you are setting the value of an instance varia...
1
2016-09-29T19:17:59Z
[ "python", "static-variables" ]
Understanding behaviour of self with static variables
39,778,235
<p>I am confused with the behaviour of self when it comes to dealing with static variables in python.From what I understand is that static variables can be accessed by either using <code>classname.variablename</code> or <code>self.variablename</code>. However changing the value of that variable differs. I realized that...
-1
2016-09-29T19:12:28Z
39,778,776
<p>Both classes and instances can have attributes.</p> <p>A class attribute is assigned to a class object. People sometimes call this a <em>"static variable"</em>.</p> <p>An instance attribute is assigned to an instance (<em>"instance variable"</em>).</p> <p>When an attribute of an object is <strong>read</strong>, a...
1
2016-09-29T19:46:37Z
[ "python", "static-variables" ]
How to change value inside function
39,778,404
<p>Very new to coding. I'm trying to learn myself Python by doing a little project I came up with. I realize this will be a slow process, but I just had a question about loops.</p> <p>This is what I'm trying to do:</p> <p>-The user inputs a list of numbers, and if a number in the list is more than 360, the function w...
2
2016-09-29T19:23:11Z
39,778,627
<p>You don't have to use <code>range(len(x))</code>. Instead, you can iterate over the elements in <code>x</code> explicitly.</p> <pre><code>def bearing(x): for item in x: item = item % 360 #This gets the remainder of dividing item by 360 if item &gt; 270: print(360 - item) eli...
0
2016-09-29T19:36:19Z
[ "python", "loops" ]
How to change value inside function
39,778,404
<p>Very new to coding. I'm trying to learn myself Python by doing a little project I came up with. I realize this will be a slow process, but I just had a question about loops.</p> <p>This is what I'm trying to do:</p> <p>-The user inputs a list of numbers, and if a number in the list is more than 360, the function w...
2
2016-09-29T19:23:11Z
39,778,777
<p>Instead of using assignment (<code>=</code>) you're using comparison (<code>==</code>). Try this:</p> <pre><code>def bearing(x): for i in range(len(x)): while x[i]&gt;=360: x[i]-=360 if x[i]&gt;270: x[i]=360-x[i] elif x[i]&gt;180: x[i]-=180 eli...
0
2016-09-29T19:46:41Z
[ "python", "loops" ]
How to change value inside function
39,778,404
<p>Very new to coding. I'm trying to learn myself Python by doing a little project I came up with. I realize this will be a slow process, but I just had a question about loops.</p> <p>This is what I'm trying to do:</p> <p>-The user inputs a list of numbers, and if a number in the list is more than 360, the function w...
2
2016-09-29T19:23:11Z
39,778,941
<p>You may or may not be familiar with the modulus operator (<code>%</code>). What that does is return the remainder from division, which is basically caffeinated subtraction anyway. For example, <code>5 % 3</code> would return <code>2</code> since <code>5 / 3 == 1 remainder 2</code>. Hopefully you can see how <code>us...
0
2016-09-29T19:56:59Z
[ "python", "loops" ]
Cache file handle to netCDF files in python
39,778,435
<p>Is there a way to cache python file handles? I have a function which takes a netCDF file path as input, opens it, extracts some data from the netCDF file and closes it. It gets called a lot of times, and the overhead of opening the file each time is high.</p> <p>How can I make it faster by maybe caching the file ha...
6
2016-09-29T19:25:04Z
39,821,062
<p>What about this?</p> <pre><code>filehandle = None def get_filehandle(filename): if filehandle is None or filehandle.closed(): filehandle = open(filename, "r") return filehandle </code></pre> <p>You may want to encapsulate this into a class to prevent other code from messing with the <code>filehandl...
-1
2016-10-02T19:54:59Z
[ "python", "netcdf" ]
Cache file handle to netCDF files in python
39,778,435
<p>Is there a way to cache python file handles? I have a function which takes a netCDF file path as input, opens it, extracts some data from the netCDF file and closes it. It gets called a lot of times, and the overhead of opening the file each time is high.</p> <p>How can I make it faster by maybe caching the file ha...
6
2016-09-29T19:25:04Z
39,917,248
<p>Yes, you can use following python libraries:</p> <ul> <li><a href="https://pypi.python.org/pypi/dill" rel="nofollow">dill</a> (required)</li> <li><a href="https://pypi.python.org/pypi/python-memcached" rel="nofollow">python-memcached</a> (optional)</li> </ul> <p>Let's follow the example. You have two files:</p> <...
2
2016-10-07T12:24:15Z
[ "python", "netcdf" ]
DRY way to declare several similar form fields
39,778,443
<p>Let's say I'm trying to declare a (django) Form class with several FileFields:</p> <pre><code>class = MyForm(forms.Form): file_0 = forms.FileField() file_1 = forms.FileField() ... </code></pre> <p>I have about 20 sequential inputs to declare - what's the best way to avoid typing this all out like a chu...
3
2016-09-29T19:25:26Z
39,778,489
<p>Use a loop:</p> <pre><code>files = [forms.FileInput() for i in range(20)] </code></pre>
1
2016-09-29T19:27:40Z
[ "python", "django" ]
DRY way to declare several similar form fields
39,778,443
<p>Let's say I'm trying to declare a (django) Form class with several FileFields:</p> <pre><code>class = MyForm(forms.Form): file_0 = forms.FileField() file_1 = forms.FileField() ... </code></pre> <p>I have about 20 sequential inputs to declare - what's the best way to avoid typing this all out like a chu...
3
2016-09-29T19:25:26Z
39,778,711
<p>You can use Django dynamic Form generation</p> <pre><code>from django import forms class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for i in range(20): self.fields["file_%d" % i] = forms.FileInput() </code></pre> <p>See ...
3
2016-09-29T19:42:23Z
[ "python", "django" ]
Fancy time series grouping operations with Pandas dataframe
39,778,471
<p>I'm updating an implementation I have to use <em>pandas</em> and take advantage of its functionality and I would appreciate some help. I have a pandas dataframe of events that looks like this:</p> <pre><code> ID Start End 0 243552 2010-12-12 23:00:53 2010-12-12 23:37:14 1 243621 2...
0
2016-09-29T18:21:29Z
39,790,370
<p>It's a difficult problem, but here is the solution:</p> <pre><code>import pandas as pd period = "10min" df = pd.read_csv("test.csv", parse_dates=[1, 2]) span = df.End - df.Start start_period = df.Start.dt.floor(period) end_period = df.End.dt.floor(period) start_count = start_period.value_counts(sort=False) end_c...
1
2016-09-30T11:22:03Z
[ "python", "pandas" ]
How to make auto increment field in django which starts from 10000
39,778,600
<p>I want to make an auto increment field in Django which starts from bigger value , I found use <strong>Autofield</strong> in models but It starts from 1 .</p> <pre><code>class University(models.Model): id = models.AutoField(primary_key=True) university_name = models.CharField(max_length=250, unique=True) ...
0
2016-09-29T19:34:49Z
39,779,380
<p>Rather then trying in front end , I suggest you to create sequences in backend (in Database) with starting higher numbers Sequence value.</p> <p>Hope this will solve your purposes.</p>
0
2016-09-29T20:26:10Z
[ "python", "mysql", "django", "django-models" ]
How to make auto increment field in django which starts from 10000
39,778,600
<p>I want to make an auto increment field in Django which starts from bigger value , I found use <strong>Autofield</strong> in models but It starts from 1 .</p> <pre><code>class University(models.Model): id = models.AutoField(primary_key=True) university_name = models.CharField(max_length=250, unique=True) ...
0
2016-09-29T19:34:49Z
39,781,679
<p>The simplest is to catch the <a href="https://docs.djangoproject.com/en/1.10/ref/signals/#post-migrate" rel="nofollow">post migrate signal</a></p> <pre><code>from django.apps import AppConfig from django.db.models.signals import post_migrate def my_callback(sender, **kwargs): if sender.name = 'myapp' try...
1
2016-09-29T23:48:06Z
[ "python", "mysql", "django", "django-models" ]
Caesar Cipher shift by two letters
39,778,606
<pre><code>def main(): cc = (input("Enter Message to Encrypt\n"))#user input shift = int(2) #shift length a=["a","b","c","d","e","f","g","h","i","j","k","l", "m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #reference list newa={} #new shifted reference list for i in range (0,len...
1
2016-09-29T19:35:06Z
39,778,694
<p>Iterate through the string <code>cc</code> and replace all the alphabets using the <code>get</code> method of <code>newa</code>. Characters that are not in the dictionary are left as is, by passing them as the default to <code>newa.get</code> when the key is missing: </p> <pre><code>newa = {} for i, x in enumerate(...
0
2016-09-29T19:41:34Z
[ "python", "encryption", "caesar-cipher" ]
Caesar Cipher shift by two letters
39,778,606
<pre><code>def main(): cc = (input("Enter Message to Encrypt\n"))#user input shift = int(2) #shift length a=["a","b","c","d","e","f","g","h","i","j","k","l", "m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #reference list newa={} #new shifted reference list for i in range (0,len...
1
2016-09-29T19:35:06Z
39,778,704
<p>Use mapping for every char, then join them back to create the encrypted message:</p> <pre><code>''.join(map(lambda x: chr((ord(x) - 97 + shift) % 26 + 97) if x in alphabet else x, cc.lower())) </code></pre> <p>Integrate it like that:</p> <pre><code>import string alphabet = string.ascii_lowercase cc = input('Enter...
0
2016-09-29T19:42:12Z
[ "python", "encryption", "caesar-cipher" ]
Caesar Cipher shift by two letters
39,778,606
<pre><code>def main(): cc = (input("Enter Message to Encrypt\n"))#user input shift = int(2) #shift length a=["a","b","c","d","e","f","g","h","i","j","k","l", "m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #reference list newa={} #new shifted reference list for i in range (0,len...
1
2016-09-29T19:35:06Z
39,778,719
<p>Use a dictionary to map inputs to outputs</p> <pre><code>shifted_a = a[-shift:] + a[:-shift] cipher = {a[i]: shifted_a[i] for i in range(len(a))} output = ''.join(cipher[char] for char in cc) </code></pre>
0
2016-09-29T19:42:51Z
[ "python", "encryption", "caesar-cipher" ]
Caesar Cipher shift by two letters
39,778,606
<pre><code>def main(): cc = (input("Enter Message to Encrypt\n"))#user input shift = int(2) #shift length a=["a","b","c","d","e","f","g","h","i","j","k","l", "m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #reference list newa={} #new shifted reference list for i in range (0,len...
1
2016-09-29T19:35:06Z
39,779,010
<p>I would just build transition table and use it to decode string.</p> <pre><code>import string shift = 2 letters = string.ascii_lowercase + string.ascii_uppercase transtable = str.maketrans({letters[i]: letters[(i + shift) % len(letters)] for i in range(len(letters))}) cc = input('Enter...
0
2016-09-29T20:01:38Z
[ "python", "encryption", "caesar-cipher" ]
Caesar Cipher shift by two letters
39,778,606
<pre><code>def main(): cc = (input("Enter Message to Encrypt\n"))#user input shift = int(2) #shift length a=["a","b","c","d","e","f","g","h","i","j","k","l", "m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #reference list newa={} #new shifted reference list for i in range (0,len...
1
2016-09-29T19:35:06Z
39,779,355
<p>I'll throw my solution in there. It should be pretty clear how it works...</p> <pre><code>import string index_lookup = {letter: index for index, letter in enumerate(string.ascii_lowercase)} def caesar_letter(l, shift=2): new_index = index_lookup[l] + shift return string.ascii_lowercase[new_index % len(ind...
0
2016-09-29T20:23:32Z
[ "python", "encryption", "caesar-cipher" ]
Template View - kwargs and **kwargs
39,778,657
<p>I am reading about Template views through a tutorial and some of the code kind of confused me. The author used this code sample</p> <pre><code>from django.utils.timezone import now class AboutUsView(TemplateView): template_name = 'about_us.html' def get_context_data(self, **kwargs): context = super(AboutU...
3
2016-09-29T19:38:24Z
39,778,758
<p>In a function declaration, <code>**kwargs</code> will take all unspecified keyword arguments and convert them into a dictionary.</p> <pre><code>&gt;&gt;&gt; test_dict = {'a':1, 'b':2} &gt;&gt;&gt; def test(**kwargs): ... print (kwargs) ... &gt;&gt;&gt; test(**test_dict) {'b': 2, 'a': 1} </code></pre> <p>Note t...
3
2016-09-29T19:45:42Z
[ "python", "django" ]
Template View - kwargs and **kwargs
39,778,657
<p>I am reading about Template views through a tutorial and some of the code kind of confused me. The author used this code sample</p> <pre><code>from django.utils.timezone import now class AboutUsView(TemplateView): template_name = 'about_us.html' def get_context_data(self, **kwargs): context = super(AboutU...
3
2016-09-29T19:38:24Z
39,778,764
<p>Here at your function definition, it is accepting multiple arguments, and parsing them into a dict. <code>def get_context_data(self, **kwargs):</code> </p> <p>So now, kwargs is a dictionary object. So if you pass it to <code>.get_context_data(kwargs)</code> it would have to expect only a single incoming argument, ...
2
2016-09-29T19:45:53Z
[ "python", "django" ]
pandas reset_index after groupby.value_counts()
39,778,686
<p>I am trying to groupby a column and compute value counts on another column.</p> <pre><code>import pandas as pd dftest = pd.DataFrame({'A':[1,1,1,1,1,1,1,1,1,2,2,2,2,2], 'Amt':[20,20,20,30,30,30,30,40, 40,10, 10, 40,40,40]}) print(dftest) </code></pre> <p>dftest looks like</p> <pre><code> A Am...
2
2016-09-29T19:41:03Z
39,778,707
<p>You need parameter <code>name</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>, because <code>Series</code> name is same as name of one of levels of <code>MultiIndex</code>:</p> <pre><code>df_grouped.reset_index(n...
3
2016-09-29T19:42:16Z
[ "python", "pandas", "dataframe", "data-manipulation", "data-science" ]
Optional Synchronous Interface to Asynchronous Functions
39,778,901
<p>I'm writing a library which is using Tornado Web's <code>tornado.httpclient.AsyncHTTPClient</code> to make requests which gives my code a <code>async</code> interface of:</p> <pre><code>async def my_library_function(): return await ... </code></pre> <p>I want to make this interface optionally serial if the use...
1
2016-09-29T19:54:50Z
39,781,803
<p>When you want to call such a function synchronously, use <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" rel="nofollow">run_until_complete</a>:</p> <pre><code>asyncio.get_event_loop().run_until_complete(here_we_go()) </code></pre> <p>Of course, if you...
1
2016-09-30T00:07:59Z
[ "python", "asynchronous", "tornado", "synchronous" ]
UTF8 Character in URL String
39,778,909
<p>I wrote a little Python script that parses a website. I got a "ä" character in form of <code>\u00e4</code> in a url from a link like <code>http://foo.com/h\u00e4ppo</code>, and I need <code>http://foo.com/häppo</code>.</p>
0
2016-09-29T19:55:16Z
39,779,478
<p>The character <code>\u00e4</code> which you have is already correct. That is in fact <code>ä</code>.</p> <p>Sometimes, the representation (<code>repr</code>) of a string will display it in the escaped form, just as backslash <code>\</code> will be display as escaped <code>\\</code>. That part is fine.</p> <h2>The...
0
2016-09-29T20:32:15Z
[ "python", "url", "encoding" ]
UTF8 Character in URL String
39,778,909
<p>I wrote a little Python script that parses a website. I got a "ä" character in form of <code>\u00e4</code> in a url from a link like <code>http://foo.com/h\u00e4ppo</code>, and I need <code>http://foo.com/häppo</code>.</p>
0
2016-09-29T19:55:16Z
39,779,578
<p>Unluckily this depends heavily on the encoding of the site you parsed, as well as your local IO encoding. </p> <p>I'm not really sure if you can translate it after parsing, and if it's really worth the work. If you have the chance to parse it again you can try using python's <code>decode()</code> function, like:</p...
0
2016-09-29T20:38:48Z
[ "python", "url", "encoding" ]
Connect to Oracle database using pyodbc
39,778,968
<p>I would like to connect to an Oracle database with python through pyodbc. I have installed oracle driver and I tried the following script:</p> <pre><code>import pyodbc connectString = """ DRIVER={Oracle in OraClient12Home1}; SERVER=some_oracle_db.com:1521; SID=oracle_...
2
2016-09-29T19:58:44Z
39,779,248
<p>Looks Like your missing a PORT</p> <p>Try this way</p> <p><strong>NOTE:</strong> Depending on your Server the syntax can be different this will work for Windows without DSN using an SQL Server Driver.</p> <pre><code>connectString = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID...
0
2016-09-29T20:17:12Z
[ "python", "oracle" ]
Connect to Oracle database using pyodbc
39,778,968
<p>I would like to connect to an Oracle database with python through pyodbc. I have installed oracle driver and I tried the following script:</p> <pre><code>import pyodbc connectString = """ DRIVER={Oracle in OraClient12Home1}; SERVER=some_oracle_db.com:1521; SID=oracle_...
2
2016-09-29T19:58:44Z
39,779,556
<p>You have to specify server or hostname (or IP address in connection string for your database server is running.</p>
0
2016-09-29T20:37:20Z
[ "python", "oracle" ]
Connect to Oracle database using pyodbc
39,778,968
<p>I would like to connect to an Oracle database with python through pyodbc. I have installed oracle driver and I tried the following script:</p> <pre><code>import pyodbc connectString = """ DRIVER={Oracle in OraClient12Home1}; SERVER=some_oracle_db.com:1521; SID=oracle_...
2
2016-09-29T19:58:44Z
39,779,729
<p>Thank. Solved problem with cx_Oracle. </p>
0
2016-09-29T20:47:44Z
[ "python", "oracle" ]
How to identify a string as being a byte literal?
39,778,978
<p>In Python 3, if I have a string such that:</p> <pre><code>print(some_str) </code></pre> <p>yields something like this:</p> <pre><code>b'This is the content of my string.\r\n' </code></pre> <p>I know it's a byte literal. </p> <p>Is there a function that can be used to determine if that string is in byte literal ...
7
2016-09-29T19:59:29Z
39,779,024
<p>The easiest and, arguably, best way to do this would be by utilizing the built-in <a href="https://docs.python.org/3/library/functions.html#isinstance"><code>isinstance</code></a> with the <code>bytes</code> type:</p> <pre><code>some_str = b'hello world' if isinstance(some_str, bytes): print('bytes') elif isins...
13
2016-09-29T20:02:36Z
[ "python", "string", "python-3.x" ]