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
Plotting networkx graph: node labels adjacent to nodes?
39,876,123
<p>I am trying to plot association rules and am having a difficult time getting the node labels below to "follow" the nodes. That is, I would like each label to automatically be near its respective node without having to hard-code any values. The output from below doesn't even include some of the node labels. How can I...
0
2016-10-05T14:03:57Z
39,880,971
<p>When you call</p> <pre><code>nx.draw(G, node_size = 100) </code></pre> <p>and then</p> <pre><code>pos = nx.spring_layout(G) </code></pre> <p>you are creating two sets of positions. The solution is to first get the positions, and then use them for both, nodes and labels.</p> <pre><code>pos = nx.spring_layout(G) ...
1
2016-10-05T18:10:45Z
[ "python", "nodes", "networkx" ]
Efficient converting of numpy int array with shape (M, N, P) array to 2D object array with (N, P) shape
39,876,136
<p>From a 3D array with the shape (M, N, P) of data type <code>int</code>, I would like to get a 2D array of shape (N, P) of data type <code>object</code> and have this done with reasonable efficiency.</p> <p>I'm happy with the objects being of either <code>tuple</code>, <code>list</code> or <code>numpy.ndarray</code>...
3
2016-10-05T14:04:21Z
39,879,187
<p>So for a smaller <code>m</code>:</p> <pre><code>In [513]: m = np.mgrid[:3,:4] In [514]: m.shape Out[514]: (2, 3, 4) In [515]: m Out[515]: array([[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2]], [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]) In [516]: ll = list(zip(*(v.ravel() for v...
1
2016-10-05T16:22:30Z
[ "python", "numpy" ]
Add tabstop in python expression in UltiSnip
39,876,144
<p>I made a modification of the example given by UltiSnip doc:</p> <pre><code>snippet "be(gin)?( (\S+))?" "begin{} / end{}" br \begin{${1:`!p snip.rv = match.group(3) if match.group(2) is not None else "something"`}}${2:`!p if match.group(2) is not None and match.group(3) != "proof": snip.rv = "\label{"+t[1]+":}"`...
0
2016-10-05T14:04:40Z
39,886,190
<p>I get a work version, but not clean in code:</p> <p><code>snippet "be(gin)?( (\S+))?" "begin{} / end{}" br \begin{${1:`!p snip.rv = match.group(3) if match.group(2) is not None else "something"`}}${2:`!p if match.group(2) is not None and match.group(3) != "proof": snip.rv = '\label{'+t[1]+':'`$4`!p if match.gro...
0
2016-10-06T01:39:39Z
[ "python", "vim-plugin", "ultisnips" ]
Update pandas dataframe with values from another dataframe
39,876,316
<p>Assuming a dataframe where values from any of the columns can change, Given another dataframe which contains the old value, new value and column it belongs to, how to update dataframe using information about changes? For example:</p> <pre><code>&gt;&gt;&gt; my_df x y z 0 1 2 5 1 2 3 9 2 ...
0
2016-10-05T14:12:03Z
39,876,622
<p>You can create a dictionary for the changes as follows:</p> <pre><code>d = {i: dict(zip(j['old_value'], j['new_value'])) for i, j in my_df_2.groupby('changed_col')} d Out: {'x': {1: 12, 2: 10}, 'y': {4: 23}, 'z': {9: 20}} </code></pre> <p>Then use it in <a href="http://pandas.pydata.org/pandas-docs/stable/generat...
1
2016-10-05T14:24:25Z
[ "python", "pandas" ]
Update pandas dataframe with values from another dataframe
39,876,316
<p>Assuming a dataframe where values from any of the columns can change, Given another dataframe which contains the old value, new value and column it belongs to, how to update dataframe using information about changes? For example:</p> <pre><code>&gt;&gt;&gt; my_df x y z 0 1 2 5 1 2 3 9 2 ...
0
2016-10-05T14:12:03Z
39,876,649
<p>You can use the update method. See <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.update.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.update.html</a></p> <p>Example:</p> <pre><code>old_df = pd.DataFrame({"a":np.arange(5...
0
2016-10-05T14:25:47Z
[ "python", "pandas" ]
Make a Tv simulator - Python
39,876,384
<p>I am really new to Python and I have to make a tv simulator. I have searched basically the entire net but I cant really find my answer. My problem is that we have to save the state of the tv in a file and when we reopen the programm it must retrieve its previous state i.e. channel, show, volume. I use pickle for sav...
-2
2016-10-05T14:15:00Z
39,876,600
<p>Using global variables for reading is no problem, thus explaining that the <code>save</code> feature works, but assignments to globals are not automatic: You have to make your variables global or it will create local variables instead that will be lost as soon as they go out of scope (thus explaining why your state ...
1
2016-10-05T14:23:25Z
[ "python", "pickle" ]
Pandas : Getting unique rows for a given column but conditional on some criteria of other columns
39,876,389
<p>I'm using python 2.7. From a given data as follows:</p> <pre><code>data = pd.DataFrame({'id':['001','001','001','002','002','003','003','003','004','005'], 'status':['ground','unknown','air','ground','unknown','ground','unknown','unknown','unknown','ground'], 'value':[10,-5,12...
0
2016-10-05T14:15:09Z
39,877,620
<p>One option would be changing the type of status column to category and sorting based on that in groupby.agg:</p> <pre><code>df['status'] = df['status'].astype('category', categories=['air', 'ground', 'unknown'], ordered=True) df.sort_values('status').groupby('id').agg({'status': 'first', 'value': ['sum', 'count']}...
2
2016-10-05T15:05:13Z
[ "python", "pandas" ]
Pandas : Getting unique rows for a given column but conditional on some criteria of other columns
39,876,389
<p>I'm using python 2.7. From a given data as follows:</p> <pre><code>data = pd.DataFrame({'id':['001','001','001','002','002','003','003','003','004','005'], 'status':['ground','unknown','air','ground','unknown','ground','unknown','unknown','unknown','ground'], 'value':[10,-5,12...
0
2016-10-05T14:15:09Z
39,877,656
<p>You want to use <code>groupby</code> on id. This is easy for value and count but trickier for the status. We need to write our own function which takes a pandas Series and returns a single attribute.</p> <pre><code>def group_status(x): if (x=='air').any(): y = 'air' elif (x=='ground').any(): ...
2
2016-10-05T15:06:44Z
[ "python", "pandas" ]
Python Imports failing. Relative imports, package recognition, __init__.py , __package__, __all__
39,876,409
<p>I've been reading a lot of threads, the PEP articles related to this problem, which are around 4 of them, but none of them gives a clear idea on some points and I still can't do relative imports. </p> <p>In fact, the contents of my main package is not listed at all.</p> <p><strong>REEDITION. I modified all the pos...
1
2016-10-05T14:16:05Z
39,903,118
<p>This is a circular dependency issue. It's very similar to this <a href="http://stackoverflow.com/questions/9252543/importerror-cannot-import-name-x/23836838#23836838">question</a>, but differs in that you are trying import a module from a package, rather than a class from a module. The best solution in this case is ...
1
2016-10-06T18:23:06Z
[ "python", "import", "python-2.x" ]
Python Imports failing. Relative imports, package recognition, __init__.py , __package__, __all__
39,876,409
<p>I've been reading a lot of threads, the PEP articles related to this problem, which are around 4 of them, but none of them gives a clear idea on some points and I still can't do relative imports. </p> <p>In fact, the contents of my main package is not listed at all.</p> <p><strong>REEDITION. I modified all the pos...
1
2016-10-05T14:16:05Z
39,904,382
<p>This is a Python bug that exists in Python versions prior to 3.5. See <a href="http://bugs.python.org/issue992389" rel="nofollow">issue 992389</a> where it was discussed (for many years) and <a href="http://bugs.python.org/issue17636" rel="nofollow">issue 17636</a> where the common cases of the issue were fixed.</p>...
0
2016-10-06T19:40:38Z
[ "python", "import", "python-2.x" ]
Retrieving data from Pandas based on iloc and user input
39,876,415
<p>I have a small SQLite DB with data about electrical conductors. The program prints the list of names and Pandas ID, accepts user input of that ID, and then prints all the information about the selected conductor.</p> <p>I am trying to figure out how to then select a specific item from a specified column - later, I'...
0
2016-10-05T14:16:22Z
39,876,675
<p>If I understand correctly, the 'getCond' will be the index of the row you want to select, and 'Amps' is the column. I think you can just do this to return the 'getCond' row of the 'Amps' column.</p> <p>df.loc[getCond, 'Amps']</p>
1
2016-10-05T14:26:33Z
[ "python", "sqlite", "pandas" ]
MultiIndex Slicing requires the index to be fully lexsorted
39,876,416
<p>I have a data frame with index (<code>year</code>, <code>foo</code>), where I would like to select the X largest observations of <code>foo</code> where <code>year == someYear</code>.</p> <p>My approach was </p> <pre><code>df.sort_index(level=[0, 1], ascending=[1, 0], inplace=True) df.loc[pd.IndexSlice[2002, :10], ...
1
2016-10-05T14:16:22Z
39,877,051
<p><code>ascending</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow">should be a boolean, not a list</a>. Try sorting this way:</p> <p><code>df.sort_index(ascending=True, inplace=True)</code></p>
0
2016-10-05T14:41:57Z
[ "python", "pandas" ]
MultiIndex Slicing requires the index to be fully lexsorted
39,876,416
<p>I have a data frame with index (<code>year</code>, <code>foo</code>), where I would like to select the X largest observations of <code>foo</code> where <code>year == someYear</code>.</p> <p>My approach was </p> <pre><code>df.sort_index(level=[0, 1], ascending=[1, 0], inplace=True) df.loc[pd.IndexSlice[2002, :10], ...
1
2016-10-05T14:16:22Z
39,877,111
<p>To get the <code>xth</code> observations of the second level as wanted, one can combine <code>loc</code> with <code>iloc</code>:</p> <pre><code>df.sort_index(level=[0, 1], ascending=[1, 0], inplace=True) df.loc[2015].iloc[:10] </code></pre> <p>works as expected. This does not answer the weird index locking w.r.t. ...
0
2016-10-05T14:44:25Z
[ "python", "pandas" ]
Can someone help me installing pyHook?
39,876,454
<p>I have python 3.5 and I can't install pyHook. I tried every method possible. pip, open the cmd directly from the folder, downloaded almost all the pyHook versions. Still can't install it. I get this error :' Could not find a version that satisfies the requirment pyHook. I have windows 10, 64 bit, Can someone help ...
-3
2016-10-05T14:17:50Z
40,008,811
<p>This is how I did it...</p> <ol> <li>Download the py hook module that matches your version of python from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook" rel="nofollow" title="Here">here</a>. Make sure that if you have python 32 bit you download the 32 bit module (even if you have windows 64x) and vice ...
0
2016-10-12T21:39:38Z
[ "python", "python-3.x", "pyhook" ]
Can someone help me installing pyHook?
39,876,454
<p>I have python 3.5 and I can't install pyHook. I tried every method possible. pip, open the cmd directly from the folder, downloaded almost all the pyHook versions. Still can't install it. I get this error :' Could not find a version that satisfies the requirment pyHook. I have windows 10, 64 bit, Can someone help ...
-3
2016-10-05T14:17:50Z
40,068,100
<p>I am really sorry for the dumb question! I installed it now. All i needed to do is to navigate to the folder with the pyHook in it, in CMD. I didn't know how to do it at first, so I jumped this step over, with the tought that it doesn't mean anything. Sorry again and thank you so much for all your responses ! </p>
0
2016-10-16T07:47:38Z
[ "python", "python-3.x", "pyhook" ]
Name error in Python in 'self' definition
39,876,485
<p>Getting <code>Name Error:</code> in python code as shared below. I am a beginner in Python.</p> <pre><code>from PyQt4 import QtGui, QtCore import sys import I2CGenericFrame import os class I2CApp(QtGui.QMainWindow, I2CGenericFrame.Ui_winI2CMain): def __init__(self): super(self.__class__, self).__init__...
-1
2016-10-05T14:18:54Z
39,876,545
<p><code>self</code> is an argument like any other that is passed in a method. It has no meaning in the class body outside of a method.</p> <p>You can resolve this by fixing the indentation so that it is referenced inside the <code>__init__</code> method:</p> <pre><code>class I2CApp(QtGui.QMainWindow, I2CGenericFrame...
1
2016-10-05T14:21:18Z
[ "python", "linux" ]
Name error in Python in 'self' definition
39,876,485
<p>Getting <code>Name Error:</code> in python code as shared below. I am a beginner in Python.</p> <pre><code>from PyQt4 import QtGui, QtCore import sys import I2CGenericFrame import os class I2CApp(QtGui.QMainWindow, I2CGenericFrame.Ui_winI2CMain): def __init__(self): super(self.__class__, self).__init__...
-1
2016-10-05T14:18:54Z
39,876,587
<p>the variable <code>self</code> is passed to methods automatically when you call them from an object. Your line of code <code>self.cmbBusListBox.addItem("Slect ..")</code> is not contained within a method of the Class and therefore it does not know what <code>self</code> is. This is probably an indentation error. ...
0
2016-10-05T14:22:40Z
[ "python", "linux" ]
Would a valid request URL ever have a '.html' extension in web2py?
39,876,488
<p>The <a href="http://web2py.com/books/default/chapter/29/04/the-core" rel="nofollow">web2py book's "Core" chapter</a> says:</p> <blockquote> <p>web2py maps GET/POST requests of the form:</p> </blockquote> <pre><code>http://127.0.0.1:8000/a/c/f.html/x/y/z?p=1&amp;q=2 </code></pre> <blockquote> <p>to function f ...
1
2016-10-05T14:18:59Z
39,878,783
<p>The part after the dot is used by web2py to render the proper view. Both <code>a/c/f.html</code> and <code>a/c/f.json</code> calls the same function (<code>f</code> inside the <code>c.py</code> controller), but the former will render <code>views/c/f.html</code> while the later <code>views/c/f.json</code> (if presen...
2
2016-10-05T16:00:48Z
[ "python", "validation", "web2py" ]
How do i print out the right Id with my output
39,876,504
<p>I am working with sklearn and pandas and my prediction is coming out as an array without the right id, which has been set as the index.</p> <p>My code:</p> <pre><code>train = train.set_index('activity_id') test = test.set_index('activity_id') y_train = train['outcome'] x_train = train.drop('people_id', axis=1) x_...
0
2016-10-05T14:19:49Z
39,878,895
<p>From what you have written I believe you are trying to show your index for x_test next to the y_pred values generated by x_test.</p> <p>This can be done by turning the numpy array output from <code>model.predict(x_test)</code> into a DataFrame. Then we can set the index of the new DataFrame to be the same as that o...
1
2016-10-05T16:06:44Z
[ "python", "pandas", "scikit-learn" ]
How to merge two dataframes in Spark Hadoop without common key?
39,876,536
<p>I am trying to join two dataframes.</p> <p>data: DataFrame[_1: bigint, _2: vector]</p> <p>cluster: DataFrame[cluster: bigint]</p> <pre><code>result = data.join(broadcast(cluster)) </code></pre> <p>The strange thing is, that all the executors are failing on the joining step.</p> <p>I have no idea what I could do...
-2
2016-10-05T14:21:04Z
39,959,105
<p>What does work is this:</p> <pre><code>data = sqlContext.read.parquet(data_path) data = data.withColumn("id", monotonicallyIncreasingId()) cluster = sqlContext.read.parquet(cluster_path) cluster = cluster.withColumn("id", monotonicallyIncreasingId()) result = data.join(cluster, on="id") </code></pre> <p>Adding...
0
2016-10-10T13:10:59Z
[ "python", "hadoop", "apache-spark", "spark-dataframe", "parquet" ]
Read and Write separately in python
39,876,608
<p>I'm trying to create a very simple program in python that needs to read input from the user and write output accordingly. I need an output similar to this:</p> <pre><code>$./program.py say something: Hello World result: hello world </code></pre> <p>The thing is that i need to read input indefinitely, each time the...
3
2016-10-05T14:23:51Z
39,876,686
<p>You can do veeeery simple trick:</p> <pre><code>from os import system while True: system('clear') # or 'cls' if you are running windows user_input = input('say something:') print('result: ' + user_input) input() </code></pre>
2
2016-10-05T14:27:02Z
[ "python", "terminal" ]
Read and Write separately in python
39,876,608
<p>I'm trying to create a very simple program in python that needs to read input from the user and write output accordingly. I need an output similar to this:</p> <pre><code>$./program.py say something: Hello World result: hello world </code></pre> <p>The thing is that i need to read input indefinitely, each time the...
3
2016-10-05T14:23:51Z
39,917,409
<p>I believe this is what you want:</p> <pre><code>import colorama colorama.init() no = 0 while True: user_input = str(raw_input('\033[2A'*no + '\033[KSay something: ')) print '\033[KResult: ' + user_input no = 1 </code></pre> <p>This how it looks after entering the string:</p> <p><a href="http://i.stack...
2
2016-10-07T12:32:47Z
[ "python", "terminal" ]
How to use Python with beautifulsoup to merge siblings
39,876,623
<p>How do I merge siblings together and display the output one beside each other. </p> <p><strong>EX.</strong></p> <pre><code>dat=""" &lt;div class="col-md-1"&gt; &lt;table class="table table-hover"&gt; &lt;tr&gt; &lt;th&gt;Name:&lt;/th&gt; &lt;td&gt;&lt;strong&gt;John&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;...
2
2016-10-05T14:24:26Z
39,876,791
<p>Why don't process the table <em>row by row</em>:</p> <pre><code>soup = BeautifulSoup(dat, 'html.parser') for row in soup.select(".table tr"): label, value = row.find_all(["th", "td"]) print(label.get_text() + " " + value.get_text()) </code></pre> <p>Prints:</p> <pre><code>Name: John Last Name: Doe Email: ...
1
2016-10-05T14:31:41Z
[ "python", "html" ]
How to use Python with beautifulsoup to merge siblings
39,876,623
<p>How do I merge siblings together and display the output one beside each other. </p> <p><strong>EX.</strong></p> <pre><code>dat=""" &lt;div class="col-md-1"&gt; &lt;table class="table table-hover"&gt; &lt;tr&gt; &lt;th&gt;Name:&lt;/th&gt; &lt;td&gt;&lt;strong&gt;John&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;...
2
2016-10-05T14:24:26Z
39,877,171
<p>Use this</p> <pre><code>soup = BeautifulSoup(dat, 'html.parser') table = soup.find_all('table', attrs={'class': ['table', 'table-hover']}) for buf in table: for row in buf.find_all('tr'): print(row.th.string, row.td.string) </code></pre> <p>Output</p> <pre><code>Name: John Last Name: Doe Email: jd@mai...
0
2016-10-05T14:46:36Z
[ "python", "html" ]
Python windows service to automatically grant folder permissions creates duplicate ACEs
39,876,729
<p>I wrote a windows service in Python that scans a given directory for new folders. Whenever a new folder is created, the service creates 4 sub-folders and grants each one a different set of permissions. The problem is that within those subfolders, any folders created (essentially tertiary level, or sub-sub-folders) h...
3
2016-10-05T14:28:53Z
40,023,796
<p>So the problem here is in the win32security.SetFileSecurity() function. As per MSDN, this function is obsolete (see: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa379577(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/aa379577(v=vs.85).aspx</a>) and has be...
0
2016-10-13T14:26:58Z
[ "python", "windows", "file-permissions", "pywin32" ]
Where to keep SASS files in a Django project?
39,876,761
<p>I understand that static files (such as CSS, JS, images) in a Django project are ideally to be kept in a <code>static/</code> directory, whether inside an app or the project root.</p> <p>A sample folder structure may look like</p> <p><code>project_root/my_app/static/my_app/css</code>, <code>js</code> or <code>img<...
0
2016-10-05T14:30:01Z
39,877,206
<p>Keep assets in <code>assets</code> directory. Here is simple project layout I use (many things are omitted):</p> <pre><code>[project root directory] ├── apps/ | ├── [app]/ | └── __init__.py | ├── assets/ | ├── styles...
0
2016-10-05T14:48:16Z
[ "python", "django", "sass" ]
Scipy ode solver
39,876,781
<p>Using scipy version 0.18.0 and really scratching my head at the moment. I reduced the code to the following minimal example:</p> <h1>try to solve the easiest differential equation possible</h1> <pre><code>def phase(t, y): c1 = y dydt = - c1 return dydt c1 = 1.0 y0 = c1 t = np.linspace(0,1,100) ode_ob...
0
2016-10-05T14:31:07Z
39,891,902
<p>Found this issue on github <a href="https://github.com/scipy/scipy/issues/1976" rel="nofollow">https://github.com/scipy/scipy/issues/1976</a> This basically explains how it works and when you think how these initial value solvers work ( stepwise into direction of the final point ) it gets clearer why this is done th...
0
2016-10-06T09:05:06Z
[ "python", "scipy" ]
Flask Default server issue
39,876,845
<p>To be Clear, I am well aware that flask's built in server which uses werkzeug cannot be used as a full blown server and should be replaced with Mod_wsgi or something else.</p> <p>But , My requirement is to serve only one request at a time but if another request comes in while the first one is being served, it shoul...
0
2016-10-05T14:33:52Z
39,877,902
<p><code>flask.Flask.run</code> accepts keyword arguments eg. <code>threaded=True</code> that it forwards to <code>werkzeug.serving.run_simple</code> two of those arguments are: threaded which enables threading, and processes, which you can set to have Werkzeug spawn more than one process to handle requests. So if you ...
0
2016-10-05T15:18:42Z
[ "python", "flask", "server" ]
How to identify which .pyd files are required for the execution of exe files generated using py2exe module
39,876,902
<p>I have written a python script and generated an exe using py2exe on Windows 32 bit OS. While I'm trying to execute the generated exe file, I'm getting the below error:</p> <hr> <pre><code>Traceback (most recent call last): File "program01.py", line 3, in &lt;module&gt; File "PIL\Image.pyc", line 67, in &lt;mod...
0
2016-10-05T14:35:43Z
39,879,368
<p>You can include modules by adding <code>options</code> argument into <code>setup</code>:</p> <pre><code> options = {'py2exe': {'bundle_files': 1, 'compressed': True, "includes" : ['os', 'sys', 'math', 'aggdraw', 'PIL', 'xml.etree.ElementTree', 'lxml.etree' ]} } </code></pre> <p>Only thing that could be diffe...
0
2016-10-05T16:32:14Z
[ "python", "pydev", "py2exe", "pillow", "pyd" ]
SQLAlchemy query using both ilike and contains as filters
39,877,109
<p>I'm trying to use both .contains and .ilike to filter a query from a string value.</p> <p>For example the query should look something like this:</p> <pre><code>model.query.filter(model.column.contains.ilike("string").all() </code></pre> <p>Currently querying by .contains returns case sensitive results. And queryi...
-1
2016-10-05T14:44:20Z
39,878,153
<p>foo = model.query.filter(model.column.ilike("%"+ string_variable +"%")).all()</p>
0
2016-10-05T15:30:54Z
[ "python", "sqlalchemy" ]
Insert missing weekdays in pandas dataframe and fill them with NaN
39,877,184
<p>I am trying to insert missing weekdays in a time series dataframe such has </p> <pre><code>import pandas as pd from pandas.tseries.offsets import * df = pd.DataFrame([['2016-09-30', 10, 2020], ['2016-10-03', 20, 2424], ['2016-10-05', 5, 232]], columns=['date', 'price', 'vol']).set_index('date') df['date'] = pd.to_d...
0
2016-10-05T14:47:03Z
39,877,325
<p>You can use reindex:</p> <pre><code>df.index = pd.to_datetime(df.index) df.reindex(pd.date_range('2016-09-30', '2016-10-05', freq=BDay())) Out: price vol 2016-09-30 10.0 2020.0 2016-10-03 20.0 2424.0 2016-10-04 NaN NaN 2016-10-05 5.0 232.0 </code></pre>
1
2016-10-05T14:52:37Z
[ "python", "python-2.7", "pandas", "datetimeindex" ]
Insert missing weekdays in pandas dataframe and fill them with NaN
39,877,184
<p>I am trying to insert missing weekdays in a time series dataframe such has </p> <pre><code>import pandas as pd from pandas.tseries.offsets import * df = pd.DataFrame([['2016-09-30', 10, 2020], ['2016-10-03', 20, 2424], ['2016-10-05', 5, 232]], columns=['date', 'price', 'vol']).set_index('date') df['date'] = pd.to_d...
0
2016-10-05T14:47:03Z
39,880,123
<p>Alternatively, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">pandas.DataFrame.resample()</a>, specifying 'B' for <em>Business Day</em> with no need to specify beginning or end date sequence as along as the dataframe maintains a datetime inde...
2
2016-10-05T17:17:43Z
[ "python", "python-2.7", "pandas", "datetimeindex" ]
Python: Open Excel Workbook using Win32 COM Api
39,877,278
<p>I'm using the following code to open and display a workbook within Excel:</p> <pre><code>import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Workbooks.Open('my_sheet.xlsm') ws = wb.Worksheets('blaaaa') excel.Visible = True </code></pre> <p>When the File 'my_sheet....
-1
2016-10-05T14:51:06Z
39,880,844
<p>While you found a solution, consider using <a href="https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions" rel="nofollow">try/except/finally</a> block. Currently your code will leave the Excel.exe process running in background (check Task Manager if using Windows) even if you close the visible wor...
1
2016-10-05T18:03:07Z
[ "python", "excel", "winapi", "com-interface" ]
How to download my file from HDInsight cluster that is saved from pd.to_csv()
39,877,341
<p>I have a HDInsight cluster running Spark 1.6.2 &amp; Jupyter In a jupyter notebook I run my pyspark commands and some of the output is processed in pandas dataframe.</p> <p>As the last step I would like to save out my pandas dataframe to a csv file and either:</p> <ol> <li>save it to the 'jupyter filesystem' and d...
0
2016-10-05T14:53:26Z
39,891,156
<p>Per my experience, the second question that you encountered is due to the version of the azure storage client library for python. For the old version, the library doesn't include the method which you invoked in your code. The following URL is useful for you.</p> <p><a href="http://stackoverflow.com/questions/3555...
0
2016-10-06T08:27:00Z
[ "python", "azure", "pandas", "azure-storage-blobs" ]
Names of objects in a list?
39,877,498
<p>I'm trying to iteratively write dictionaries to file, but am having issues creating the unique filenames for each dict.</p> <pre><code>def variable_to_value(value): for n, v in globals().items(): if v == value: return n else: return None a = {'a': [1,2,3]} b = {'b': [4,5,6]} c ...
2
2016-10-05T15:00:21Z
39,877,727
<p>Python doesn't actually work like this.</p> <p>Objects in Python don't have innate names. It's the names that belong to an object, not the other way around: an object can have many names (or no names at all).</p> <p>You're getting two copies of "obj" printed, because at the time you call <code>variable_to_value</c...
0
2016-10-05T15:09:33Z
[ "python", "list", "introspection" ]
Names of objects in a list?
39,877,498
<p>I'm trying to iteratively write dictionaries to file, but am having issues creating the unique filenames for each dict.</p> <pre><code>def variable_to_value(value): for n, v in globals().items(): if v == value: return n else: return None a = {'a': [1,2,3]} b = {'b': [4,5,6]} c ...
2
2016-10-05T15:00:21Z
39,877,731
<p>The function returns the first name it finds referencing an object in your <code>globals()</code>. However, at each iteration, the name <code>obj</code> will reference each of the objects. So either the name <code>a</code>, <code>b</code> or <code>c</code> is returned or <code>obj</code>, depending on the one which ...
1
2016-10-05T15:10:00Z
[ "python", "list", "introspection" ]
Names of objects in a list?
39,877,498
<p>I'm trying to iteratively write dictionaries to file, but am having issues creating the unique filenames for each dict.</p> <pre><code>def variable_to_value(value): for n, v in globals().items(): if v == value: return n else: return None a = {'a': [1,2,3]} b = {'b': [4,5,6]} c ...
2
2016-10-05T15:00:21Z
39,877,760
<p>The problem is that <code>obj</code>, your iteration variable is also in <code>globals</code>. Whether you get <code>a</code> or <code>obj</code> is just by luck. You can't solve the problem in general because an object can have any number of assignments in globals. You could update your code to exclude known refere...
2
2016-10-05T15:11:39Z
[ "python", "list", "introspection" ]
Names of objects in a list?
39,877,498
<p>I'm trying to iteratively write dictionaries to file, but am having issues creating the unique filenames for each dict.</p> <pre><code>def variable_to_value(value): for n, v in globals().items(): if v == value: return n else: return None a = {'a': [1,2,3]} b = {'b': [4,5,6]} c ...
2
2016-10-05T15:00:21Z
39,878,309
<p>So you want to find the name of any object available in the <code>globals()</code>?</p> <p>Inside the <code>for</code> loop, <code>globals() dict</code> is being mutated, adding <code>obj</code> in its namespace. So on your second pass, you have two references to the same object (originally only referenced by the n...
0
2016-10-05T15:37:36Z
[ "python", "list", "introspection" ]
Select Iframe inside other tags on Selenium
39,877,503
<p>Good day everyone.</p> <p>First, here is a TL;DR version: </p> <p>I need to select an element inside an iframe which is also inside many other HTML tags.</p> <p>Now, the actual problem:</p> <p>Today I`m trying to solve a little problem I have at work. Every day I need to perform a time-consuming task of filling ...
1
2016-10-05T15:00:29Z
39,920,218
<p>Looks like the line of code used to switch to the iframe is causing the error</p> <pre><code>driver.switch_to_frame(driver.find_element_by_tag_name("descrpt_ifr")) </code></pre> <p>'descrpt_ifr' is not a tag name. Change it to </p> <pre><code>driver.switch_to_frame(driver.find_element_by_id("descrpt_ifr")) </code...
1
2016-10-07T14:55:26Z
[ "python", "html", "selenium", "iframe", "xpath" ]
Find specific files in subdirs using Python os.walk
39,877,560
<p>In Windows, if I ran:</p> <p>dir NP_???.LAS</p> <p>I get 2 files:</p> <p>NP_123.LAS</p> <p>NP_1234.LAS</p> <p>Using fmatch with NP_????.LAS mask I get only NP_1234.LAS, not NP_123.LAS.</p> <p>Below, the code I´m running:</p> <pre><code>def FindFiles(directory, pattern): flist=[] for root, dirs, files...
-1
2016-10-05T15:02:36Z
39,880,476
<p>You could use <a href="https://docs.python.org/2/library/re.html" rel="nofollow">re</a> to give you more flexibility by allowing actual regular expressions. The regular expression "[0-9]{3,4}" matches either 3 or 4 digit numbers. </p> <pre><code>def FindFiles(directory, pattern): flist=[] for root, dirs, fi...
0
2016-10-05T17:40:55Z
[ "python", "os.walk" ]
Use of getattr on a class with data descriptor
39,877,574
<p>While using data descriptors in building classes, I came across a strange behavior of getattr function on a class.</p> <pre><code># this is a data descriptor class String(object): def __get__(self, instance, owner): pass def __set__(self, instance, value): pass # This defines a class A with...
-4
2016-10-05T15:03:12Z
39,877,704
<p><code>getattr(A, 'a')</code> triggers the descriptor protocol, even on classes, so <code>String.__get__(None, A)</code> is called.</p> <p>That returns <code>None</code> because your <code>String.__get__()</code> method has no explicit <code>return</code> statement.</p> <p>From the <a href="https://docs.python.org/...
1
2016-10-05T15:08:37Z
[ "python", "python-2.7", "class", "getattr" ]
Use of getattr on a class with data descriptor
39,877,574
<p>While using data descriptors in building classes, I came across a strange behavior of getattr function on a class.</p> <pre><code># this is a data descriptor class String(object): def __get__(self, instance, owner): pass def __set__(self, instance, value): pass # This defines a class A with...
-4
2016-10-05T15:03:12Z
39,877,724
<p><code>getattr(A, 'a')</code> is the same as <code>A.a</code>. This calls the respective descriptor, if present. So it provides the value presented by the descriptor, which is <code>None</code>. </p>
0
2016-10-05T15:09:19Z
[ "python", "python-2.7", "class", "getattr" ]
How to create `input_fn` using `read_batch_examples` with `num_epochs` set?
39,877,710
<p>I have a basic <code>input_fn</code> that can be used with Tensorflow Estimators below. It works flawlessly without setting the <code>num_epochs</code> parameter; the obtained tensor has a discrete shape. Pass in <code>num_epochs</code> as anything other than <code>None</code> results in an unknown shape. My issue l...
0
2016-10-05T15:08:50Z
40,052,668
<p>I have solved the above issue by creating a function specific to what's expected on an <code>input_fn</code>; it takes in a dense column and creates a SparseTensor without knowing shape. The function was made possible using <code>tf.range</code> and <code>tf.shape</code>. Without further ado, here is the working gen...
0
2016-10-14T22:06:36Z
[ "python", "tensorflow", "skflow" ]
Does it make sense to use cross-correlation on arrays of timestamps?
39,877,725
<p>I want to find the offset between two arrays of timestamps. They could represent, let's say, the onset of beeps in two audio tracks.</p> <p><strong>Note</strong>: There may be extra or missing onsets in either track.</p> <p>I found some information about cross-correlation (e.g. <a href="https://dsp.stackexchange.c...
8
2016-10-05T15:09:24Z
39,920,991
<p>Yes it does make sense. This is commonly done in matlab. Here is a link to a similar application:</p> <p><a href="http://www.mathworks.com/help/signal/ug/cross-correlation-of-delayed-signal-in-noise.html" rel="nofollow">http://www.mathworks.com/help/signal/ug/cross-correlation-of-delayed-signal-in-noise.html</a></p...
3
2016-10-07T15:34:52Z
[ "python", "fft", "waveform", "cross-correlation" ]
Does it make sense to use cross-correlation on arrays of timestamps?
39,877,725
<p>I want to find the offset between two arrays of timestamps. They could represent, let's say, the onset of beeps in two audio tracks.</p> <p><strong>Note</strong>: There may be extra or missing onsets in either track.</p> <p>I found some information about cross-correlation (e.g. <a href="https://dsp.stackexchange.c...
8
2016-10-05T15:09:24Z
40,000,970
<p>If <code>track_1</code> and <code>track_2</code> are timestamps of beeps and both catch all of the beeps, then there's no need to build a waveform and do cross-correlation. Just find the average delay between the two arrays of beep timestamps:</p> <pre><code>import numpy as np frequency = 44100 num_samples = 10 * ...
3
2016-10-12T14:16:08Z
[ "python", "fft", "waveform", "cross-correlation" ]
Using list comprehension to create a list of lists in a recursive function
39,877,809
<p>I am experimenting with recursive functions. My goal is to produce:</p> <blockquote> <p>A function <code>combo</code> that generates all non-increasing series that add up to n</p> </blockquote> <p>Some sample inputs/outputs:</p> <pre><code>&gt;&gt;&gt; print (combo(3)) [[3], [2, 1], [1, 1, 1]] &gt;&gt;&gt; prin...
1
2016-10-05T15:14:23Z
39,877,938
<p>Convert <em>extending</em> to <em>appending</em> and it becomes easier to grok how to convert this:</p> <pre><code>res = [] for i in range(limit, 0, -1): if i == n: res.append([i]) else: # this is the generator expression pulled out of the res.extend() call for x in combo(n - i, min(...
4
2016-10-05T15:20:17Z
[ "python", "recursion", "list-comprehension" ]
python pattern recognition in data
39,877,816
<p>I have a large (order of 10k) set of data, let’s say in the form of key-value:</p> <pre><code>A -&gt; 2 B -&gt; 5 C -&gt; 7 D -&gt; 1 E -&gt; 13 F -&gt; 1 G -&gt; 3 . . . </code></pre> <p>Also a smaller sample set (order of 10):</p> <pre><code>X -&gt; 6 Y -&gt; 8 Z -&gt; 14 . . . </code></pre> <p>Although the...
0
2016-10-05T15:14:44Z
39,879,165
<p>First, you need to think about a loss function, i.e. why is solution 1 better than solution 2? Can you come up with an objective score function such that lower scores are always better? </p> <p>E.g. in your example, is this solution any worse:</p> <pre><code>X -&gt; C Y -&gt; C Z -&gt; E </code></pre> <p>Once you...
1
2016-10-05T16:21:20Z
[ "python", "pattern-matching", "tensorflow" ]
How to optionally pass arguments with non-default values in Python?
39,877,826
<p>I have a following method:</p> <pre><code>def a(b='default_b', c='default_c', d='default_d'): # … pass </code></pre> <p>And I have some command-line interface that allows either to provide variables <code>user_b</code>, <code>user_c</code>, <code>user_d</code> or to set them to <code>None</code> - i.e. t...
1
2016-10-05T15:15:11Z
39,877,888
<pre><code>arg_dict = {} if user_b is not None: arg_dict["b"] = user_b if user_c is not None: arg_dict["c"] = user_c if user_d is not None: arg_dict["d"] = user_d a(**arg_dict) </code></pre> <p>Not exactly pretty though.</p> <p>A nicer way would just be to re-write your function <code>a</code> to accept ...
2
2016-10-05T15:17:53Z
[ "python", "syntactic-sugar" ]
How to optionally pass arguments with non-default values in Python?
39,877,826
<p>I have a following method:</p> <pre><code>def a(b='default_b', c='default_c', d='default_d'): # … pass </code></pre> <p>And I have some command-line interface that allows either to provide variables <code>user_b</code>, <code>user_c</code>, <code>user_d</code> or to set them to <code>None</code> - i.e. t...
1
2016-10-05T15:15:11Z
39,878,272
<p>You could write a function that filters out unwanted values then use it to scrub the target function call.</p> <pre><code>def scrub_params(**kw): return {k:v for k,v in kw if v is not None} some_function(**scrub_params(foo=args.foo, bar=args.bar)) </code></pre>
0
2016-10-05T15:36:27Z
[ "python", "syntactic-sugar" ]
sorting records with in grouped item in a dataframe
39,877,898
<p>Objective : I am trying to sort rows within a group in DataFrame [in python and pyspark]</p> <p>This is what I have,</p> <pre><code>id time 1 10 1 8 1 1 1 5 2 1 2 8 </code></pre> <p>This is what I am looking for,</p> <pre><code>id time delta 1 1 7 1 8 2 1 10 0 1 1 ...
0
2016-10-05T15:18:34Z
39,878,815
<p>You can use lag over a window:</p> <pre><code>from pyspark.sql.functions import lag from pyspark.sql.window import Window df = sc.parallelize([ (1, 10), (1, 8 ), (1, 1), (1, 5), (2, 1), (2, 8), ]).toDF(["id", "time"]) df.withColumn("delta", df["time"] - lag("time", 1).over(Window().partitionBy("id"...
0
2016-10-05T16:02:11Z
[ "python", "pandas", "dataframe", "pyspark", "spark-dataframe" ]
Unknown reason of dead multiprocessing in python-3.5
39,877,986
<p>I have a data frame <code>df</code> contains information of two-hundred-thousand items. And now I want to measure their pair-wise similarity and pick up the top <code>n</code> pairs. That means, I should calculate nearly tens of billions calculation. Given the huge computation cost, I choose to run it via multiproce...
1
2016-10-05T15:22:34Z
39,878,114
<p>There's little to go on, but try:</p> <pre><code>vals = pool.imap(cal_sim, gen_pair()) ^ </code></pre> <p>instead: note that I changed "map" to "imap". As documented, <code>map()</code> blocks until the <em>entire</em> computation is complete, so you never get to your <code>for</code> loop until all ...
2
2016-10-05T15:28:45Z
[ "python", "multiprocessing", "python-3.5" ]
How to overcome MemoryError of numpy.unique
39,877,999
<p>I am using Numpy version 1.11.1 and have to deal with an two-dimensional array of</p> <pre><code>my_arr.shape = (25000, 25000) </code></pre> <p>All values are integer, and I need a unique list of the arrays values. When using <code>lst = np.unique(my_arr)</code> I am getting:</p> <pre><code>Traceback (most recent...
1
2016-10-05T15:23:12Z
39,878,179
<p>Python 32-bit can't access more than 4 GiB RAM (often ~2.5 GiB). The obvious answer would be to use the 64-bit version. If that doesn't work, another solution would be to use <code>numpy.memmap</code> and memory-map the array into a file stored on disk.</p>
0
2016-10-05T15:32:02Z
[ "python", "arrays", "numpy" ]
Finding Set of strings from list of pairs (string, int) with maximum int value
39,878,076
<p>I have a list of <code>(str,int)</code> pairs </p> <p><code>list_word = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS', 2), ('ARE', 2), ('FRIENDS', 1), ('DOGS', 2)]</code></p> <p>This basically says how many times each word showed up in a text. </p> <p>What I want to get is the set o...
0
2016-10-05T15:26:50Z
39,878,239
<p>Two linear scans, first to find the maximal element:</p> <pre><code>maxcount = max(map(itemgetter(1), mylist)) </code></pre> <p>then a second to pull out the values you care about:</p> <pre><code>maxset = {word for word, count in mylist if count == maxcount}, maxcount </code></pre> <p>If you needed to get the s...
2
2016-10-05T15:34:52Z
[ "python", "string", "set", "max", "pair" ]
Finding Set of strings from list of pairs (string, int) with maximum int value
39,878,076
<p>I have a list of <code>(str,int)</code> pairs </p> <p><code>list_word = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS', 2), ('ARE', 2), ('FRIENDS', 1), ('DOGS', 2)]</code></p> <p>This basically says how many times each word showed up in a text. </p> <p>What I want to get is the set o...
0
2016-10-05T15:26:50Z
39,878,371
<p>Through the use of <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow" title="list comprehensions">list comprehensions</a> you can first select the maximum occurrence and then filter the strings accordingly</p> <pre><code>list = [('AND', 1), ('BECAUSE', 1), ('OF', 1),...
0
2016-10-05T15:40:55Z
[ "python", "string", "set", "max", "pair" ]
Finding Set of strings from list of pairs (string, int) with maximum int value
39,878,076
<p>I have a list of <code>(str,int)</code> pairs </p> <p><code>list_word = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS', 2), ('ARE', 2), ('FRIENDS', 1), ('DOGS', 2)]</code></p> <p>This basically says how many times each word showed up in a text. </p> <p>What I want to get is the set o...
0
2016-10-05T15:26:50Z
39,878,658
<p>Convert <code>list</code> to <code>dict</code> with <em>key</em> as count and <em>value</em> as set of words. Find the <code>max</code> value of key, and it;s corresponding value</p> <pre><code>from collections import defaultdict my_list = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS'...
0
2016-10-05T15:54:56Z
[ "python", "string", "set", "max", "pair" ]
Finding Set of strings from list of pairs (string, int) with maximum int value
39,878,076
<p>I have a list of <code>(str,int)</code> pairs </p> <p><code>list_word = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS', 2), ('ARE', 2), ('FRIENDS', 1), ('DOGS', 2)]</code></p> <p>This basically says how many times each word showed up in a text. </p> <p>What I want to get is the set o...
0
2016-10-05T15:26:50Z
39,880,002
<p>While the more pythonic solutions are certainly easier on the eye, unfortunately the requirement for two scans, or building data-structures you don't really want is significantly slower.</p> <p>The following fairly boring solution is about ~55% faster than the dict solution, and ~70% faster than the comprehension b...
0
2016-10-05T17:10:32Z
[ "python", "string", "set", "max", "pair" ]
Running time in a while loop (really slow)
39,878,086
<p>Following is my code:</p> <pre><code>import socket import time mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('www.py4inf.com', 80)) mysock.send(b'GET /code/romeo.txt HTTP/1.1\n') mysock.send(b'Host: www.py4inf.com\n\n') all = b"" while True: data = mysock.recv(512) all = all + ...
0
2016-10-05T15:27:15Z
39,878,994
<p>Web servers don't have to close connections immediately.In fact, they may be looking for another http request. Just add <code>print(data)</code> after the recv and you'll see you get the data, then a pause, then <code>b''</code>, meaning the server finally closed the socket.</p> <p>You'll also notice that the serv...
0
2016-10-05T16:10:54Z
[ "python", "sockets" ]
Change characters inside a .txt file with script
39,878,109
<p>I have a text file:<br> <code>3.4 - New York, United States</code> </p> <p>I need to create a script (preferably written in python) that can change the <code>-</code> (dash) character to a <code>,</code> (comma) character,</p> <p>And then save the output as a .csv file</p>
-2
2016-10-05T15:28:38Z
39,878,822
<p>Use the CSV module, here is a stackoverflow example, <a href="http://stackoverflow.com/questions/6916542/writing-list-of-strings-to-excel-csv-file-in-python">Writing List of Strings to Excel CSV File in Python</a>. If you want to replace the "-" with a "," open the file and read the string, replace it with <code>str...
0
2016-10-05T16:02:24Z
[ "python", "csv" ]
Find a string that is not identical with Python
39,878,226
<p>So.. here's what i'm trying to do.. For each line in the datafile, check if the other file contains this string.</p> <p>I tried some stuff from other posts, but non of them were any good.</p> <p>The code below says it didnt find any of the string it was looking for, even while they were present somewhere in the fi...
0
2016-10-05T15:34:30Z
39,878,467
<p>Assuming the content of the first file is not extremely large, you can read the entire file as string and then check using string containment:</p> <pre><code>def search(): file1_content = open('/home/example/file1.txt').read() datafile = open('/home/user/datafile.txt') for line in datafile: if ...
3
2016-10-05T15:45:03Z
[ "python" ]
Find a string that is not identical with Python
39,878,226
<p>So.. here's what i'm trying to do.. For each line in the datafile, check if the other file contains this string.</p> <p>I tried some stuff from other posts, but non of them were any good.</p> <p>The code below says it didnt find any of the string it was looking for, even while they were present somewhere in the fi...
0
2016-10-05T15:34:30Z
39,878,629
<p>You can read the file into a <code>set</code> and then check for inclusion in the second file. <code>set</code>'s are typically faster at checking inclusion that lists.</p> <pre><code>def search(): file1 = set(open('/home/example/file1.txt')) datafile= open('/home/user/datafile.txt', 'r') for line in d...
0
2016-10-05T15:53:47Z
[ "python" ]
Find a string that is not identical with Python
39,878,226
<p>So.. here's what i'm trying to do.. For each line in the datafile, check if the other file contains this string.</p> <p>I tried some stuff from other posts, but non of them were any good.</p> <p>The code below says it didnt find any of the string it was looking for, even while they were present somewhere in the fi...
0
2016-10-05T15:34:30Z
40,114,272
<p>I found the answer.</p> <pre><code>def search(): datafile = open('/codes/python/datafile.txt') for line in datafile: file1 = open('/codes/python/file1.txt').read() line = line.rstrip() if line in file1: print '%s found' % line else: print '%s not foun...
0
2016-10-18T17:13:23Z
[ "python" ]
8 Queens (pyglet-python)
39,878,289
<p>I'm trying to make 8 queens game on pyglet. I have succesfully generated board.png on window. Now when I paste queen.png image on it, I want it to show only queen on it not the white part. I removed white part using photoshop, but as I call it on board.png in pyglet it again shows that white part please help.</p> <...
-2
2016-10-05T15:36:54Z
39,880,233
<p>Your image is a rectangle. So necessarily, you will have a white space around your queen whatever you do. </p> <p>I would recommend a bit of hacking (it's not very beautiful) and create two queen versions: queen_yellow and queen_black. Whenever the queen is standing on a yellow tile, display queen_yellow, and other...
0
2016-10-05T17:25:17Z
[ "python", "pyglet" ]
Export 2Gb+ SELECT to CSV with Python (out of Memory)
39,878,329
<p>I'm trying to export a large file from Netezza (using Netezza ODBC + pyodbc), this solution throws memoryError, If I loop without "list" it's VERY slow. do you have any idea of a intermediate solution that doesn't kill my server/python process but can run faster?</p> <pre><code>cursorNZ.execute(sql) archi = open("c...
1
2016-10-05T15:38:45Z
39,878,460
<p>Don't use <code>cursorNZ.fetchall()</code>.</p> <p>Instead, loop through the cursor directly:</p> <pre><code>with open("c:/test.csv", "w") as archi: # note the fixed '/' cursorNZ.execute(sql) for fila in cursorNZ: registro = '' for campo in fila: campo = str(campo) ...
4
2016-10-05T15:44:44Z
[ "python", "csv", "export-to-csv", "netezza" ]
Clion can't find external module in python file
39,878,401
<p>Hell everyone,<br> I'm using CLion for a C++ project.<br> I have a some python files in this project too. ( boost python).<br> The python files import a module generated by cmake.<br> It works properly if I do : </p> <blockquote> <p>$ cd buildDir<br> $ python mypythonFile.py</p> </blockquote> <p>But in CL...
0
2016-10-05T15:42:13Z
39,898,862
<p>CLion uses CMake for creation a project model (extracts compiler switches for c/cpp files, detects files that need to be compiled and etc), but it does not inherit the environment. At least in current implementation.</p> <p>The problem is that there is a <a href="https://youtrack.jetbrains.com/issue/CPP-3090" rel="...
0
2016-10-06T14:36:29Z
[ "python", "cmake", "clion" ]
Largest (n) numbers with Index and Column name in Pandas DataFrame
39,878,426
<p>I wish to find out the largest 5 numbers in a DataFrame and store the Index name and Column name for these 5 values.</p> <p>I am trying to use nlargest() and idxmax methods but failing to achieve what i want. My code is as below:</p> <pre><code>import numpy as np import pandas as pd from pandas import Series, D...
0
2016-10-05T15:43:32Z
39,878,597
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.nlargest.html" rel="nofollow"><code>nlargest</code></a>:</p> <pre><code>max_vals = df.stack().nlar...
2
2016-10-05T15:51:50Z
[ "python", "pandas", "numpy", "dataframe", "data-analysis" ]
Model instance not reflecting data passed from pre_save in custom field
39,878,528
<p>I have a custom field for generating slug and I am using it in my model.</p> <p>The strange thing I can't figure out is why is the value I am generating in this custom field's method <code>pre_save</code> not set on the current instance. </p> <p><strong>My question is not about generating slug different way but ab...
1
2016-10-05T15:48:26Z
39,878,704
<p>The instance's slug field was updated between the call to save and the write into the database. The current instance's slug value is <em>stale</em></p> <p>To get the slug value which was written into the DB, the instance has to updated by <em>refetching</em> from the database:</p> <pre><code>instance = MyModel.obj...
1
2016-10-05T15:57:33Z
[ "python", "django" ]
shopify python api: how do add new assets to published theme?
39,878,552
<p>The shopify docs are horrible, I couldn't find any info on adding new assets to an existing shopify store.</p> <p>We're developing an app that needs to add some css and liquid files.</p> <p>Can someone here can shed some light on how to achieve this simple task?</p> <p>Thanks</p>
1
2016-10-05T15:49:43Z
39,878,643
<p>Just put your css in the assets folder and link it in the .liquid file with this:</p> <pre><code>{{ 'style.css' | asset_url | stylesheet_tag }} </code></pre>
0
2016-10-05T15:54:09Z
[ "python", "shopify" ]
shopify python api: how do add new assets to published theme?
39,878,552
<p>The shopify docs are horrible, I couldn't find any info on adding new assets to an existing shopify store.</p> <p>We're developing an app that needs to add some css and liquid files.</p> <p>Can someone here can shed some light on how to achieve this simple task?</p> <p>Thanks</p>
1
2016-10-05T15:49:43Z
39,903,099
<pre><code>asset = shopify.Asset() asset.key = "templates/josh.liquid" asset.value = "{% comment %} Liquid is cool {% endcomment %}" success = asset.save() </code></pre> <p>Be careful; if an asset already exists with the same key then it will be overwritten. You can find out more from the <a href="https://help.shopify...
0
2016-10-06T18:21:57Z
[ "python", "shopify" ]
memory leak in batch matrix factorization with tensorflow
39,878,628
<p>suppose I have a rate matrix <code>R</code> and I want to factorize it to matrices <code>U</code> and <code>V</code> with tensorflow</p> <p>without batch size its simple problem and could be solve with following code:</p> <pre><code># define Variables u = tf.Variable(np.random.rand(R_dim_1, output_dim), dtype=tf.f...
0
2016-10-05T15:53:33Z
39,900,876
<p>I just solve this problem by sending the updated values of <code>U</code> and <code>V</code> as placeholder and then assign <code>U</code> and <code>V</code> to these passed parameters so the created graph will stay the same on different iterations. here is the code:</p> <pre><code># define variables u = tf.Variabl...
0
2016-10-06T16:10:25Z
[ "python", "memory-leaks", "tensorflow", "batch-updates", "matrix-factorization" ]
Overload operator at runtime
39,878,667
<p>Is it possible to overload a operator at runtime? I tried the following code example:</p> <pre><code>class A(): pass a = A() a.__eq__ = lambda self, other: False a == a # this should return False since the __eq__-method should be overloaded but it returns # True like object.__eq__ would a.__eq__(a, a) # ...
1
2016-10-05T15:55:33Z
39,878,791
<p>Magic/double underscore methods are looked up on the class, not on the instance. So you need to override the class's method, not the instance. There are two ways to do this.</p> <p>Either directly assign to the class as such:</p> <pre><code>class A: pass a = A() A.__eq__ = lambda self, other: False print(a ==...
2
2016-10-05T16:01:09Z
[ "python", "operator-overloading" ]
Cannot assign a device to node
39,878,698
<p>I followed <a href="https://medium.com/@hamedmp/exporting-trained-tensorflow-models-to-c-the-right-way-cf24b609d183#.qajf9shah" rel="nofollow">this tutoriel</a> to export my own trained tensorflow model to c++ and I got errors when I call <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/pytho...
0
2016-10-05T15:57:12Z
39,879,061
<p>The error means op <code>save/Const_1</code> is trying to get placed on GPU, and there's no GPU implementation of that node. In fact <code>Const</code> nodes are CPU only and are stored as part of Graph object, so it can't be placed on GPU. One work-around is to run with <code>allow_soft_placement=True</code>, or to...
2
2016-10-05T16:15:04Z
[ "python", "tensorflow" ]
Dynamically add class variables to classes inheriting mixin class
39,878,756
<p>I've got a mixin class, that adds some functionality to inheriting classes, but the mixin requires some class attributes to be present, for simplicity let's say only one property <code>handlers</code>. So this would be the usage of the mixin:</p> <pre><code>class Mixin: pass class Something(Mixin): handler...
2
2016-10-05T15:59:34Z
39,884,418
<p>Your problem is very real, and Python folks have thought of this for Python 3.6 (still unrealsed) on. For now (up to Python 3.5), if your attributes can wait to exist until your classes are first instantiated, you could put cod to create a (class) attribute on the <code>__new__</code> method of your mixin class itse...
3
2016-10-05T22:03:17Z
[ "python", "python-3.x" ]
How does APScheduler save the jobs in the database? (Python)
39,878,785
<p>I am trying to figure out how looks the schema of a sqlite database after I save some jobs using Advanced Python Scheduler. I need it because I want to show the job in a UI. I tried to write a simple script which saves a job :</p> <pre><code>from pytz import utc from apscheduler.schedulers.background import Backgr...
0
2016-10-05T16:00:49Z
39,882,319
<p>You're creating two schedulers but only starting the one with default configuration.</p>
1
2016-10-05T19:39:50Z
[ "python", "sqlite", "apscheduler" ]
Django - Migrating from Sqlite3 to Postgresql
39,878,801
<p>I'm trying to deploy my Django app in Heroku, so I have to switch to PostgreSQL and I've been following these <a href="http://stackoverflow.com/questions/28648695/migrate-django-development-database-sql3-to-heroku">steps</a></p> <p>However when I run <code>python manage.py migrate</code></p> <p>I get the following...
1
2016-10-05T16:01:40Z
39,879,044
<p>You must use this command:</p> <pre><code>python manage.py makemigrations </code></pre> <p>before your command</p> <pre><code>python manage.py migrate </code></pre>
1
2016-10-05T16:14:08Z
[ "python", "django", "postgresql", "heroku" ]
Django - Migrating from Sqlite3 to Postgresql
39,878,801
<p>I'm trying to deploy my Django app in Heroku, so I have to switch to PostgreSQL and I've been following these <a href="http://stackoverflow.com/questions/28648695/migrate-django-development-database-sql3-to-heroku">steps</a></p> <p>However when I run <code>python manage.py migrate</code></p> <p>I get the following...
1
2016-10-05T16:01:40Z
39,879,212
<p>Why do you have the <code>id</code> field on the Genre model? You don't need that.</p>
0
2016-10-05T16:23:46Z
[ "python", "django", "postgresql", "heroku" ]
Python2.7: Untar files in parallel mode (with threading)
39,878,877
<p>I'm learning Python threading and in the same time trying to improve my old untaring script. </p> <p>The main part of it looks like:</p> <pre><code>import tarfile, os, threading def untar(fname, path): print "Untarring " + fname try: ut = tarfile.open(os.path.join(path,fname), "r:gz") ut.e...
0
2016-10-05T16:06:06Z
39,880,561
<p>What might be happening is that your script is returning before the threads actually complete. You can wait for a thread to complete with <code>Thread.join()</code>. Maybe try something like this:</p> <pre><code>threads = [] for filename in ListTarFiles: t = threading.Thread(target=untar, args = (filename,path...
0
2016-10-05T17:46:05Z
[ "python", "multithreading", "tarfile" ]
Change default tkinter entry value in python
39,878,878
<pre><code>checkLabel = ttk.Label(win,text = " Check Amount ", foreground = "blue") checkLabel.grid(row = 0 , column = 1) checkEntry = ttk.Entry(win, textvariable = checkVariable) checkEntry.grid(row = 1, column = 1, sticky = 'w') </code></pre> <p>How do I change the defualt entry field from displaying 0?</p>
-2
2016-10-05T16:06:07Z
39,879,154
<p>Set the value of <code>checkVariable</code> to <code>''</code> (the empty string) before you create the <code>Entry</code> object? The statement to use would be</p> <pre><code>checkVariable.set('') </code></pre> <p>But then <code>checkVariable</code> would have to be a <code>StringVar</code>, and you would have to...
0
2016-10-05T16:20:43Z
[ "python", "tkinter" ]
Change default tkinter entry value in python
39,878,878
<pre><code>checkLabel = ttk.Label(win,text = " Check Amount ", foreground = "blue") checkLabel.grid(row = 0 , column = 1) checkEntry = ttk.Entry(win, textvariable = checkVariable) checkEntry.grid(row = 1, column = 1, sticky = 'w') </code></pre> <p>How do I change the defualt entry field from displaying 0?</p>
-2
2016-10-05T16:06:07Z
39,879,466
<p>Use the entry widget's function, <code>.insert()</code> and <code>.delete()</code>. Here is an example. </p> <pre><code>entry = tk.Entry(root) entry.insert(END, "Hello") # this will start the entry with "Hello" in it # you may want to add a delay or something here. entry.delete(0, END) # this will delete everythin...
1
2016-10-05T16:37:50Z
[ "python", "tkinter" ]
Python- Multiple dynamic inheritance
39,878,892
<p>I'm having trouble with getting multiple dynamic inheritance to work. These examples make the most sense to me(<a href="http://stackoverflow.com/questions/21060073/dynamic-inheritance-in-python">here</a> and <a href="http://stackoverflow.com/questions/32104219/dynamic-multiple-inheritance-in-python">here</a>), but ...
0
2016-10-05T16:06:39Z
39,878,988
<p><code>arg</code> is a tuple, you can't use a tuple as a base class.</p> <p>Use <code>type()</code> to create a new class instead; it takes a class name, a tuple of base classes (can be empty) and the class body (a dictionary).</p> <p>I'd keep the methods for your class in a mix-in method:</p> <pre><code>class Bui...
1
2016-10-05T16:10:34Z
[ "python", "class", "inheritance", "dynamic" ]
Python- Multiple dynamic inheritance
39,878,892
<p>I'm having trouble with getting multiple dynamic inheritance to work. These examples make the most sense to me(<a href="http://stackoverflow.com/questions/21060073/dynamic-inheritance-in-python">here</a> and <a href="http://stackoverflow.com/questions/32104219/dynamic-multiple-inheritance-in-python">here</a>), but ...
0
2016-10-05T16:06:39Z
39,881,627
<p>The error in your original code is caused by failing to use tuple expansion in the class definition. I would suggest simplifying your code to this:</p> <pre><code># Get software software = os.getenv('SOFTWARE') BaseClasses = [QtGui.QWidget] if software == 'maya': from maya.app.general.mayaMixin import MayaQWid...
1
2016-10-05T18:53:34Z
[ "python", "class", "inheritance", "dynamic" ]
python Numpy transpose and calculate
39,878,921
<p>I am relatively new to python and numpy. I am currently trying to replicate the following table as shown in the image in python using numpy.</p> <p><a href="http://i.stack.imgur.com/nVKbb.png" rel="nofollow"><img src="http://i.stack.imgur.com/nVKbb.png" alt="enter image description here"></a> As in the figure, I ha...
0
2016-10-05T16:07:33Z
39,879,492
<p>This piece of code does the calculation for the example of the subgroup, I am not sure if this is what you actually want, in that case post a comment here and I will edit</p> <pre><code>import numpy as np array_1=np.array([(1,-1,10),(1,0,10),(1,-2,15),(1,-3,1),(1,-4,1);(1,0,12),(1,-5,16)]) #transpose the matrix tr...
1
2016-10-05T16:39:27Z
[ "python", "arrays", "pandas", "numpy" ]
python Numpy transpose and calculate
39,878,921
<p>I am relatively new to python and numpy. I am currently trying to replicate the following table as shown in the image in python using numpy.</p> <p><a href="http://i.stack.imgur.com/nVKbb.png" rel="nofollow"><img src="http://i.stack.imgur.com/nVKbb.png" alt="enter image description here"></a> As in the figure, I ha...
0
2016-10-05T16:07:33Z
39,879,588
<p>Try this out :</p> <pre><code>import numpy as np import pandas as pd a=np.array([(1,-1,10),(1,0,10),(1,-2,15),(1,-3,1),(1,-4,1),(1,0,12),(1,-5,16)], dtype=[('group',float),('sub_group',float),('value',float)]) df = pd.DataFrame(a) for i in df.index: col_name = str(int(df['sub_group'][i])) df[col_name] = N...
1
2016-10-05T16:46:14Z
[ "python", "arrays", "pandas", "numpy" ]
Creating file from Django <InMemoryUploadedFile>
39,878,944
<p>I have a couple of .xlsx files uploaded from a form within a Django website. For reasons that aren't worth explaining, I need to get a file path for these file objects as opposed to performing actions directly upon them. Tl;dr: I'd have to spend days re-writing a ton of someone else's code. </p> <p>Is the following...
0
2016-10-05T16:08:30Z
39,884,192
<p>NamedTemporaryFile. The with block does all the cleanup for you, and the Named version of this means the temp file can be handed off by filename to some other process if you have to go that far. Sorta example (note this is mostly coded on the fly so no promises of working code here)</p> <pre><code>import tempfile d...
1
2016-10-05T21:42:52Z
[ "python", "django", "python-2.7" ]
502 Bad Gateway nginx/1.1.19 on django
39,879,034
<p>I am new to this. I took the image of running django application and spawned the new vm that points to a different database but I am getting this "502 Bad Gateway nginx/1.1.1"</p> <p>when i tested this in development mode, it works fine but not otherwise.</p> <p>i looked into /var/log/nginx/access.log and error.l...
0
2016-10-05T16:13:11Z
39,879,669
<p>Error <strong>502 Bad Gateway</strong> means that the NGINX server used to access your site couldn't communicate properly with the <em>upstream server</em> (your application server).</p> <p>This can mean that either or both of your NGINX server and your Django Application server are configured incorrectly.</p> <p>...
1
2016-10-05T16:51:22Z
[ "python", "django", "nginx" ]
How do I get conversion with "OverflowError: Python int too large to convert to C long" error working on Windows Server 2012?
39,879,047
<p>When running this on Anaconda Python 2.7.12, Pandas 18.1, Windows Server 2012:</p> <pre><code>df['z'] = df['y'].str.replace(' ', '').astype(int) </code></pre> <p>I get this error:</p> <pre><code>OverflowError: Python int too large to convert to C long </code></pre> <p>I do not get this error on MacOS 10.11 or Ub...
2
2016-10-05T16:14:12Z
39,885,044
<p><code>int</code> is interpreted by numpy by as the <code>np.int_</code> dtype, which corresponds to a C integer. On Windows, even on a 64 bit system, this is a 32 bit integer. </p> <p>So if you need to cast larger values, specify a 64 bit integer using</p> <pre><code>.astype('int64') </code></pre>
2
2016-10-05T23:08:49Z
[ "python", "c++", "pandas", "numpy", "anaconda" ]
Python - Socket - Networking - Very Simple
39,879,091
<p>Unfortunately I am unable to find an answer for this even after an hour of searching.</p> <p>I borrowed this from online tutorials - Youtube - Draps</p> <pre><code>import socket, threading, time, wx tLock = threading.Lock() shutdown = False def receiving(name, sock): while not shutdown: try: ...
0
2016-10-05T16:17:03Z
39,879,206
<p>I'm not 100% sure on the first question but for the second one <code>shutdown</code> is a global variable. Any threads spawned from the main thread have the ability to see the <code>shutdown</code></p> <p>Can you post the socket error you are getting?</p>
1
2016-10-05T16:23:32Z
[ "python", "multithreading", "sockets", "networking" ]
Unexpected Behavior When Appending Multiple List Inside function in PyQt GUI
39,879,092
<p>I am experiencing strange behavior while trying to append to two different lists from inside of the same function. </p> <pre><code>x = 0 y = 0 list_1 = [] list_2 = [] def append_function(self): self.x += 1 self.y += 1 self.list_1.append(self.x) self.list_2.append(self.y) print self.list...
1
2016-10-05T16:17:10Z
39,880,815
<p>The problem is unique to the Iron Python console in the Spyder IDE. Running the code in another python terminal produces the expected result.</p>
0
2016-10-05T18:01:38Z
[ "python", "python-2.7", "pyqt4" ]
TypeError: reduce() of empty sequence with no initial value when merging
39,879,243
<p>I have dataframes which look like this:</p> <p>df1</p> <pre><code>Value Hectares_2006 1 10 5 15 </code></pre> <p>df2</p> <pre><code>Value Hectares_2007 1 20 5 5 </code></pre> <p>df3</p> <pre><code>Value Hectares_2008 1 22 5 3 </code></pre> <p>and I want to merge them ...
0
2016-10-05T16:25:25Z
39,879,518
<p>As mentioned in the comments, you need to un-indent the <code>dfs=...</code> line so that it's outside of the for loop. Otherwise, <code>list1</code> will be empty on the first iteration of the loop if the first file seen doesn't contain <code>.dbf</code>, which will cause the empty sequence error.</p>
1
2016-10-05T16:40:54Z
[ "python", "pandas" ]
how do i replace a character in a string by range?
39,879,334
<p>For example:</p> <pre><code>url = 'www.google.com/bla.bla' </code></pre> <p>I need to replace '.' with '' in the last 7 characters ==> 'www.google.com/blabla'</p> <p>I have tried :</p> <pre><code>for i in range(15,22): if url[i]=='.': url = url.replace('.', "") </code></pre> <p>But i get this error:<...
2
2016-10-05T16:30:29Z
39,879,405
<p>You need to change your <code>if</code> line since a single <code>=</code> is for assignment not comparison:</p> <pre><code>if url[i] == '.': </code></pre> <p>And note then when using <code>replace()</code> you will need to update the original string (<code>url</code>) since <code>replace()</code> will return a ne...
3
2016-10-05T16:34:11Z
[ "python", "string" ]
how do i replace a character in a string by range?
39,879,334
<p>For example:</p> <pre><code>url = 'www.google.com/bla.bla' </code></pre> <p>I need to replace '.' with '' in the last 7 characters ==> 'www.google.com/blabla'</p> <p>I have tried :</p> <pre><code>for i in range(15,22): if url[i]=='.': url = url.replace('.', "") </code></pre> <p>But i get this error:<...
2
2016-10-05T16:30:29Z
39,879,425
<p>In one line:</p> <pre><code>url = url[:-7] + (url[-7:].replace('.', '')) </code></pre>
4
2016-10-05T16:35:26Z
[ "python", "string" ]
how do i replace a character in a string by range?
39,879,334
<p>For example:</p> <pre><code>url = 'www.google.com/bla.bla' </code></pre> <p>I need to replace '.' with '' in the last 7 characters ==> 'www.google.com/blabla'</p> <p>I have tried :</p> <pre><code>for i in range(15,22): if url[i]=='.': url = url.replace('.', "") </code></pre> <p>But i get this error:<...
2
2016-10-05T16:30:29Z
39,879,434
<p>Thanks to @Patrick for pointing out the flaw in my previous answer.</p> <hr> <p>Instead of using <code>range()</code>, just use list comprehension and string indices:</p> <pre><code>url = 'www.google.com/bla.bla' url = url[:15] + ''.join([c for c in url[15:] if c!= '.']) </code></pre> <p>Explanation.</p> <ul> <...
0
2016-10-05T16:36:19Z
[ "python", "string" ]
how do i replace a character in a string by range?
39,879,334
<p>For example:</p> <pre><code>url = 'www.google.com/bla.bla' </code></pre> <p>I need to replace '.' with '' in the last 7 characters ==> 'www.google.com/blabla'</p> <p>I have tried :</p> <pre><code>for i in range(15,22): if url[i]=='.': url = url.replace('.', "") </code></pre> <p>But i get this error:<...
2
2016-10-05T16:30:29Z
39,879,465
<p>A more <em>generic approach</em> would be to <em>split</em> the URL, replace the dot and then <em>join</em>:</p> <pre><code>In [1]: url = 'www.google.com/bla.bla' In [2]: s = url.split("/") In [3]: s[1] = s[1].replace(".", "") In [4]: "/".join(s) Out[4]: 'www.google.com/blabla' </code></pre>
6
2016-10-05T16:37:47Z
[ "python", "string" ]
What are metaclass bases in python?
39,879,345
<p>I'm trying to extend django-allauth to do something specific to my projects. I'm basically trying to write my own wrapper on top of django-allauth, and want the installation, configuration and other stuff to be quite similar to allauth.<br> For this, I started with extending <code>AppSettings</code> class from <code...
1
2016-10-05T16:31:06Z
39,879,916
<p>It doesn't look like you should be able to inherit from <code>AllAuthAppSettings</code></p> <p>The <code>django-allauth</code> package is doing some very ugly python magic</p> <pre><code>import sys # noqa app_settings = AppSettings('ACCOUNT_') app_settings.__name__ = __name__ sys.modules[__name__] = app_settings ...
1
2016-10-05T17:05:21Z
[ "python", "django", "class", "metaclass" ]
How do you make two turtles draw at once in Python?
39,879,410
<p>How do you make two turtles draw at once? I know how to make turtles draw and how to make two or more but I don't know how you can make them draw at the same time. Please help!</p>
-4
2016-10-05T16:34:31Z
39,880,134
<p>Here's a minimalist example using timer events:</p> <pre><code>import turtle t1 = turtle.Turtle(shape="turtle") t2 = turtle.Turtle(shape="turtle") t1.setheading(45) t2.setheading(-135) def move_t1(): t1.forward(1) turtle.ontimer(move_t1, 10) def move_t2(): t2.forward(1) turtle.ontimer(move_t2, 1...
1
2016-10-05T17:18:48Z
[ "python", "turtle-graphics" ]
Recursively go through all directories until you find a certain file in Python
39,879,638
<p>What's the best way in Python to recursively go through all directories until you find a certain file? I want to look through all the files in my directory and see if the file I'm looking for is in that directory. If I cannot find it, I go to the parent directory and repeat the process. I also want to count how ma...
0
2016-10-05T16:49:11Z
39,879,675
<pre><code>def findPath(startDir,targetFile): file_count = 0 for i,(current_dir,dirs,files) in enumerate(os.walk(startDir)): file_count += len(files) if targetFile in files: return (i,file_count,os.path.join(current_dir,targetFile)) return (i,file_count,None) print findPath("C:\\...
0
2016-10-05T16:51:39Z
[ "python", "file", "recursion", "directory" ]
Recursively go through all directories until you find a certain file in Python
39,879,638
<p>What's the best way in Python to recursively go through all directories until you find a certain file? I want to look through all the files in my directory and see if the file I'm looking for is in that directory. If I cannot find it, I go to the parent directory and repeat the process. I also want to count how ma...
0
2016-10-05T16:49:11Z
39,879,686
<p>Don't re-invent the directory-recursion wheel. Just use the <a href="https://docs.python.org/3/library/os.html#os.walk" rel="nofollow"><code>os.walk()</code> function</a>, which gives you a loop over a recursive traversal of directories:</p> <pre><code>def walkfs(startdir, findfile): dircount = 0 filecount ...
3
2016-10-05T16:52:15Z
[ "python", "file", "recursion", "directory" ]
Can I efficiently create a pandas data frame from semi-structured binary data?
39,879,711
<p>I need to convert large binary files to n x 3 arrays. The data is a series of image frames defined by (x, y, time) coordinates. Each frame uses two 32-bit integers to define the n x 3 dimensions, and n triplets of 16-bit integers to define the (x, y, time) values. The result is a binary structure that looks like:</p...
2
2016-10-05T16:53:26Z
39,880,537
<p>Each time you append to the data frame, you are copying the whole thing to a new location in memory. You will want to initialise the data frame with a numpy array with the full final size, and then index into that with iloc(), etc. when you populate it with the imaging data.</p> <p>Also, is there a specific reason ...
0
2016-10-05T17:44:35Z
[ "python", "pandas", "numpy", "binary" ]
Can I efficiently create a pandas data frame from semi-structured binary data?
39,879,711
<p>I need to convert large binary files to n x 3 arrays. The data is a series of image frames defined by (x, y, time) coordinates. Each frame uses two 32-bit integers to define the n x 3 dimensions, and n triplets of 16-bit integers to define the (x, y, time) values. The result is a binary structure that looks like:</p...
2
2016-10-05T16:53:26Z
39,922,295
<p>The <code>count</code> parameter simplified this by allowing <code>np.fromfile</code> to take advantage of the structure defined by the <code>int32</code> values. The following <code>for</code> loop creates each image frame individually:</p> <pre><code>f = open('file.bin', 'rb') for i in np.arange(1,15001,1): ...
0
2016-10-07T16:48:02Z
[ "python", "pandas", "numpy", "binary" ]
Django materialize
39,879,746
<p>So I have in my <code>forms.py</code>:</p> <pre><code> auto_current_type = forms.ModelMultipleChoiceField(label="Авто:", queryset=Auto_current_type.objects.all(), widget=forms.CheckboxSelectMultiple()) </code></pre> <p>My template:</p> <pre><code>&lt;div ...
0
2016-10-05T16:55:22Z
39,881,310
<p>so I have found solution <a href="https://pypi.python.org/pypi/django-materialize-form/0.1.1" rel="nofollow">here</a></p> <p>hope this will help</p>
-1
2016-10-05T18:31:11Z
[ "python", "django", "forms", "django-forms", "materialize" ]
Searching rows of one dataframe in another dataframe in Python
39,879,845
<p>I have two data frames in python:</p> <pre><code> df1 A B C 1 1 0 1 2 1 0 1 2 . . . . . . df2 T W S Y 7 4 5 [1] 8 12 4 [0,7] 10 14 6 [2,3] </code></pre> <p>I ...
0
2016-10-05T17:01:31Z
39,880,734
<p>You can do a merge of the two dataframes and filter the result. I am not sure how optimized it will be, but it will do the job faster than python for loops.</p>
1
2016-10-05T17:56:25Z
[ "python", "list", "search", "dataframe" ]