qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
7,549,403
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it..
2011/09/25
[ "https://Stackoverflow.com/questions/7549403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715578/" ]
``` import os, zipfile if 'filenames.txt' in os.listdir('.'): print 'file is in current dir' else: zf = zipfile.ZipFile('files.zip') zf.extract('filenames.txt') ```
From the documentation ```none $ pydoc os.path.exists Help on function exists in os.path: os.path.exists = exists(path) Test whether a path exists. Returns False for broken symbolic links ```
7,549,403
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it..
2011/09/25
[ "https://Stackoverflow.com/questions/7549403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715578/" ]
``` import os.path try: os.path.isFile(fname) # play with the file except: # unzip file ```
From the documentation ```none $ pydoc os.path.exists Help on function exists in os.path: os.path.exists = exists(path) Test whether a path exists. Returns False for broken symbolic links ```
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall using this class. Also, you might find this [blog post](http://austringer.net/wp/index.php/2011/05/20/plotting-a-dolphin-biosonar-click-train/) useful, since the author shows that you might obtain some 'visual bug' in some specific situation (depending on the view angle chosen). Below is an example of a waterfall made with matplotlib (image from the blog post): [![image](https://i.stack.imgur.com/sqRcC.png)](https://i.stack.imgur.com/sqRcC.png) (source: [austringer.net](http://austringer.net/images/biosonar/wfall_demo.png))
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show() ``` ![http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots](https://i.stack.imgur.com/9iLhI.png) I don't know how to get results as nice as Matlab does. --- If you want more, you may also have a look at [MayaVi](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/faq.html#how-is-mplot3d-different-from-mayavi): <http://mayavi.sourceforge.net/>
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show() ``` ![http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots](https://i.stack.imgur.com/9iLhI.png) I don't know how to get results as nice as Matlab does. --- If you want more, you may also have a look at [MayaVi](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/faq.html#how-is-mplot3d-different-from-mayavi): <http://mayavi.sourceforge.net/>
The Wikipedia type of [Waterfall chart](http://en.wikipedia.org/wiki/Waterfall_chart) one can obtain also like this: ``` import numpy as np import pandas as pd def waterfall(series): df = pd.DataFrame({'pos':np.maximum(series,0),'neg':np.minimum(series,0)}) blank = series.cumsum().shift(1).fillna(0) df.plot(kind='bar', stacked=True, bottom=blank, color=['r','b']) step = blank.reset_index(drop=True).repeat(3).shift(-1) step[1::3] = np.nan plt.plot(step.index, step.values,'k') test = pd.Series(-1 + 2 * np.random.rand(10), index=list('abcdefghij')) waterfall(test) ```
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show() ``` ![http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots](https://i.stack.imgur.com/9iLhI.png) I don't know how to get results as nice as Matlab does. --- If you want more, you may also have a look at [MayaVi](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/faq.html#how-is-mplot3d-different-from-mayavi): <http://mayavi.sourceforge.net/>
I have generated a function that replicates the matlab waterfall behaviour in matplotlib. That is: 1. It generates the 3D shape as many independent and parallel 2D curves 2. Its color comes from a colormap in the z values I started from two examples in matplotlib documentation: [multicolor lines](https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html) and [multiple lines in 3d plot](https://matplotlib.org/examples/mplot3d/polys3d_demo.html). From these examples, I only saw possible to draw lines whose color varies following a given colormap according to its z value following the example, which is reshaping the input array to draw the line by segments of 2 points and setting the color of the segment to the z mean value between these 2 points. Thus, given the input matrixes `n,m` matrixes `X`,`Y` and `Z`, the function loops over the smallest dimension between `n,m` to plot each of the waterfall plot independent lines as a line collection of the 2 points segments as explained above. ``` def waterfall_plot(fig,ax,X,Y,Z,**kwargs): ''' Make a waterfall plot Input: fig,ax : matplotlib figure and axes to populate Z : n,m numpy array. Must be a 2d array even if only one line should be plotted X,Y : n,m array kwargs : kwargs are directly passed to the LineCollection object ''' # Set normalization to the same values for all plots norm = plt.Normalize(Z.min().min(), Z.max().max()) # Check sizes to loop always over the smallest dimension n,m = Z.shape if n>m: X=X.T; Y=Y.T; Z=Z.T m,n = n,m for j in range(n): # reshape the X,Z into pairs points = np.array([X[j,:], Z[j,:]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # The values used by the colormap are the input to the array parameter lc = LineCollection(segments, cmap='plasma', norm=norm, array=(Z[j,1:]+Z[j,:-1])/2, **kwargs) line = ax.add_collection3d(lc,zs=(Y[j,1:]+Y[j,:-1])/2, zdir='y') # add line to axes fig.colorbar(lc) # add colorbar, as the normalization is the same for all # it doesent matter which of the lc objects we use ax.auto_scale_xyz(X,Y,Z) # set axis limits ``` Therefore, plots looking like matlab waterfall can be easily generated with the same input matrixes as a matplotlib surface plot: ``` import numpy as np; import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from mpl_toolkits.mplot3d import Axes3D # Generate data x = np.linspace(-2,2, 500) y = np.linspace(-2,2, 60) X,Y = np.meshgrid(x,y) Z = np.sin(X**2+Y**2)-.2*X # Generate waterfall plot fig = plt.figure() ax = fig.add_subplot(111, projection='3d') waterfall_plot(fig,ax,X,Y,Z,linewidth=1.5,alpha=0.5) ax.set_xlabel('X'); ax.set_ylabel('Y'); ax.set_zlabel('Z') fig.tight_layout() ``` [![default waterfall](https://i.stack.imgur.com/PtfJp.png)](https://i.stack.imgur.com/PtfJp.png) The function assumes that when generating the meshgrid, the `x` array is the longest, and by default the lines have fixed y, and its the x coordinate what varies. However, if the size of the `y` array is longer, the matrixes are transposed, generating the lines with fixed x. Thus, generating the meshgrid with the sizes inverted (`len(x)=60` and `len(y)=500`) yields: [![non default waterfall](https://i.stack.imgur.com/kD6Av.png)](https://i.stack.imgur.com/kD6Av.png) To see what are the possibilities of the `**kwargs` argument, refer to the [LineCollection class documantation](https://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection) and to its [`set_` methods](https://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection.set).
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall using this class. Also, you might find this [blog post](http://austringer.net/wp/index.php/2011/05/20/plotting-a-dolphin-biosonar-click-train/) useful, since the author shows that you might obtain some 'visual bug' in some specific situation (depending on the view angle chosen). Below is an example of a waterfall made with matplotlib (image from the blog post): [![image](https://i.stack.imgur.com/sqRcC.png)](https://i.stack.imgur.com/sqRcC.png) (source: [austringer.net](http://austringer.net/images/biosonar/wfall_demo.png))
The Wikipedia type of [Waterfall chart](http://en.wikipedia.org/wiki/Waterfall_chart) one can obtain also like this: ``` import numpy as np import pandas as pd def waterfall(series): df = pd.DataFrame({'pos':np.maximum(series,0),'neg':np.minimum(series,0)}) blank = series.cumsum().shift(1).fillna(0) df.plot(kind='bar', stacked=True, bottom=blank, color=['r','b']) step = blank.reset_index(drop=True).repeat(3).shift(-1) step[1::3] = np.nan plt.plot(step.index, step.values,'k') test = pd.Series(-1 + 2 * np.random.rand(10), index=list('abcdefghij')) waterfall(test) ```
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall using this class. Also, you might find this [blog post](http://austringer.net/wp/index.php/2011/05/20/plotting-a-dolphin-biosonar-click-train/) useful, since the author shows that you might obtain some 'visual bug' in some specific situation (depending on the view angle chosen). Below is an example of a waterfall made with matplotlib (image from the blog post): [![image](https://i.stack.imgur.com/sqRcC.png)](https://i.stack.imgur.com/sqRcC.png) (source: [austringer.net](http://austringer.net/images/biosonar/wfall_demo.png))
I have generated a function that replicates the matlab waterfall behaviour in matplotlib. That is: 1. It generates the 3D shape as many independent and parallel 2D curves 2. Its color comes from a colormap in the z values I started from two examples in matplotlib documentation: [multicolor lines](https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html) and [multiple lines in 3d plot](https://matplotlib.org/examples/mplot3d/polys3d_demo.html). From these examples, I only saw possible to draw lines whose color varies following a given colormap according to its z value following the example, which is reshaping the input array to draw the line by segments of 2 points and setting the color of the segment to the z mean value between these 2 points. Thus, given the input matrixes `n,m` matrixes `X`,`Y` and `Z`, the function loops over the smallest dimension between `n,m` to plot each of the waterfall plot independent lines as a line collection of the 2 points segments as explained above. ``` def waterfall_plot(fig,ax,X,Y,Z,**kwargs): ''' Make a waterfall plot Input: fig,ax : matplotlib figure and axes to populate Z : n,m numpy array. Must be a 2d array even if only one line should be plotted X,Y : n,m array kwargs : kwargs are directly passed to the LineCollection object ''' # Set normalization to the same values for all plots norm = plt.Normalize(Z.min().min(), Z.max().max()) # Check sizes to loop always over the smallest dimension n,m = Z.shape if n>m: X=X.T; Y=Y.T; Z=Z.T m,n = n,m for j in range(n): # reshape the X,Z into pairs points = np.array([X[j,:], Z[j,:]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # The values used by the colormap are the input to the array parameter lc = LineCollection(segments, cmap='plasma', norm=norm, array=(Z[j,1:]+Z[j,:-1])/2, **kwargs) line = ax.add_collection3d(lc,zs=(Y[j,1:]+Y[j,:-1])/2, zdir='y') # add line to axes fig.colorbar(lc) # add colorbar, as the normalization is the same for all # it doesent matter which of the lc objects we use ax.auto_scale_xyz(X,Y,Z) # set axis limits ``` Therefore, plots looking like matlab waterfall can be easily generated with the same input matrixes as a matplotlib surface plot: ``` import numpy as np; import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from mpl_toolkits.mplot3d import Axes3D # Generate data x = np.linspace(-2,2, 500) y = np.linspace(-2,2, 60) X,Y = np.meshgrid(x,y) Z = np.sin(X**2+Y**2)-.2*X # Generate waterfall plot fig = plt.figure() ax = fig.add_subplot(111, projection='3d') waterfall_plot(fig,ax,X,Y,Z,linewidth=1.5,alpha=0.5) ax.set_xlabel('X'); ax.set_ylabel('Y'); ax.set_zlabel('Z') fig.tight_layout() ``` [![default waterfall](https://i.stack.imgur.com/PtfJp.png)](https://i.stack.imgur.com/PtfJp.png) The function assumes that when generating the meshgrid, the `x` array is the longest, and by default the lines have fixed y, and its the x coordinate what varies. However, if the size of the `y` array is longer, the matrixes are transposed, generating the lines with fixed x. Thus, generating the meshgrid with the sizes inverted (`len(x)=60` and `len(y)=500`) yields: [![non default waterfall](https://i.stack.imgur.com/kD6Av.png)](https://i.stack.imgur.com/kD6Av.png) To see what are the possibilities of the `**kwargs` argument, refer to the [LineCollection class documantation](https://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection) and to its [`set_` methods](https://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection.set).
61,575,311
I am trying to open up data from a CSV file in my Visual Studio terminal and receive: '''' ``` Traceback (most recent call last): File "/home/jubal/ CrashCourse Python Notes/Chapter 16 CC/Downloading Date/csv format/highs_lows.py", line 7, in <module> with open(filename) as f: FileNotFoundError: [Errno 2] No such file or directory: 'sitka_weather_2018_full.csv' ``` '''' and here is the program highs\_lows.py, it is saved in the same folder as sitka\_weather\_2018\_full.csv '''' ``` import csv filename = 'sitka_weather_2018_full.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) highs = [] for row in reader: highs.append(row[8]) print(highs) ``` '''' My latop run linux mint 19.2 cinnamon, also I am able to run this program just fine with jupyter notebook but when I try to convert into a python program and run it in the VS code terminal is when this problem occurs. Newbie to programming so any help would be great. Thanks for your time!
2020/05/03
[ "https://Stackoverflow.com/questions/61575311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10457351/" ]
So the question says that `N` can be upto 10000, but your code assumes that it is no bigger than 100.
Regarding LTE, you are almost there. Try to replace the ``` for (int j = i + 1; j <= i + (p - 1); j++) tmp += skill[i] - skill[j]; ``` loop with the constant time expression. Hint: when the most skillful player leaves the window, by how much the training time for the rest players gets decreased?
64,397,933
I have a simple webpage that uses that okta web api: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous" /> <title>Simple Web Page</title> <style> h1 { margin: 2em 0; } </style> <!-- widget stuff here --> <script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.16.0/js/okta-sign-in.min.js" type="text/javascript"></script> <link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.16.0/css/okta-sign-in.min.css" type="text/css" rel="stylesheet" /> <link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.16.0/css/okta-theme.css" type="text/css" rel="stylesheet" /> </head> <body> <div class="container"> <h1 class="text-center">Test</h1> <div id="messageBox" class="jumbotron"> You are not logged in. </div> <!-- where the sign-in form will be displayed --> <div id="okta-login-container"></div> </div> <script type="text/javascript"> var oktaSignIn = new OktaSignIn({ baseUrl: "{{ https://dev-8490637.okta.com }}", clientId: "{{ 0oa97ptccRHXCE3kN5d5 }}", authParams: { issuer: "default", responseType: ["token", "id_token"], display: "page", }, }); if (oktaSignIn.token.hasTokensInUrl()) { oktaSignIn.token.parseTokensFromUrl( // If we get here, the user just logged in. function success(res) { var accessToken = res[0]; var idToken = res[1]; oktaSignIn.tokenManager.add("accessToken", accessToken); oktaSignIn.tokenManager.add("idToken", idToken); window.location.hash = ""; document.getElementById("messageBox").innerHTML = "Hello, " + idToken.claims.email + "! You just logged in! :)"; }, function error(err) { console.error(err); } ); } else { oktaSignIn.session.get(function (res) { // If we get here, the user is already signed in. if (res.status === "ACTIVE") { document.getElementById("messageBox").innerHTML = "Hello, " + res.login + "! You are *still* logged in! :)"; return; } oktaSignIn.renderEl( { el: "#okta-login-container" }, function success(res) {}, function error(err) { console.error(err); } ); }); } </script> </body> </html> ``` I have python installed on my laptop. When I open the terminal of visual studio code that contain my index.html file I use the commands: ```none cd C:\Users\marta\test (directory where my code is) python -m http.server 8080 (redirect to port 8080) ``` I checked if my firewall/anti-virus was enable google to run and its correct. The problem: When I load the http://localhost:8080/ is continuing show me this error: ![localhost refused to connect.](https://i.stack.imgur.com/CSQ9A.png)
2020/10/17
[ "https://Stackoverflow.com/questions/64397933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14465519/" ]
If you have created a custom mass update script you would have created parameters accessed like : ``` runtime.getCurrentScript().getParameter({name:'custscript....'}); ``` If so and you are then triggering the work flow via: ``` workflow.initiate({ recordType:'customer', ... ``` then you might do something like: ``` /** * @NApiVersion 2.x * @NScriptType MassUpdateScript */ define(["N/runtime", "N/workflow"], function (runtime, workflow) { function each(params) { workflow.initiate({ workflowId:'customworkflow_target_id' recordType: params.type, recordId: params.id defaultValues:{ custworkflow_field_1:runtime.getCurrentScript().getParameter({name:'custscript_field_1'}) // and so on. of course you'll probably dereference runtime.getCurrentScript() if you have multiple parameters // You'll have to define workflow fields for every value you want to pass. // custscript_field_1 is from the id of the workflow fields. // For sanity's sake I recommend giving your script parameters similar ids as the workflow field ids } }); } exports.each = each; }); ```
Create parameters in your script then when you are calling the custom action script in the workflow, pass the workflow field values to the script parameters.
31,361,482
I'm writing a porting a basic python script and creating a similarly basic Flask application. I have a file consisting of a bunch of functions that I'd like access to within my Flask application. Here's what I have so far for my views: ``` from flask import render_template from app import app def getRankingList(): return 'hey everyone!' @app.route("/") @app.route("/index") def index(): rankingsList = getRankingsList() return render_template('index.html', rankingsList = rankingsList) if __name__ == '__main__': app.run(debug=True) ``` Ideally, I'd have access to all of the functions from my original script and make use of them within my `getRankingsList()` function. I've googled around and can't seem to sort out how to do this, however. Any idea
2015/07/11
[ "https://Stackoverflow.com/questions/31361482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316501/" ]
Simply have another python script file (for example `helpers.py`) in the same directory as your main flask .py file. Then at the top of your main flask file, you can do `import helpers` which will let you access any function in helpers by adding `helpers.` before it (for example `helpers.exampleFunction()`). Or you can do `from helpers import exampleFunction` and use `exampleFunction()` directly in your code. Or `from helpers import *` to import and use all the functions directly in your code.
Just import your file as usual and use functions from it: ``` # foo.py def bar(): return 'hey everyone!' ``` And in the main file: ``` # main.py from flask import render_template from app import app from foo import bar def getRankingList(): return 'hey everyone!' @app.route("/") @app.route("/index") def index(): rankingsList = getRankingsList() baz = bar() # Function from your foo.py return render_template('index.html', rankingsList=rankingsList) if __name__ == '__main__': app.run(debug=True) ```
33,775,658
So I have this operation in python `x = int(v,base=2)` which takes `v`as a Binary String. What would be the inverse operation to that? For example, given `1101000110111111011001100001` it would return `219936353`, so I want to get this binary string from the `219936353` number. Thanks
2015/11/18
[ "https://Stackoverflow.com/questions/33775658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3770881/" ]
Try out the bin() function. ``` bin(yourNumber)[2:] ``` will give you string containing bits for your number.
``` num = 219936353 print("{:b}".format(num)) --output:-- 1101000110111111011001100001 ``` The other solutions are all wrong: ``` num = 1 string = bin(1) result = int(string, 10) print(result) --output:-- Traceback (most recent call last): File "1.py", line 4, in <module> result = int(string, 10) ValueError: invalid literal for int() with base 10: '0b1' ``` You would have to do this: ``` num = 1 string = bin(1) result = int(string[2:], 10) print(result) #=> 1 ```
33,775,658
So I have this operation in python `x = int(v,base=2)` which takes `v`as a Binary String. What would be the inverse operation to that? For example, given `1101000110111111011001100001` it would return `219936353`, so I want to get this binary string from the `219936353` number. Thanks
2015/11/18
[ "https://Stackoverflow.com/questions/33775658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3770881/" ]
Try out the bin() function. ``` bin(yourNumber)[2:] ``` will give you string containing bits for your number.
``` >>> bin(219936353) '0b1101000110111111011001100001' ```
5,918,353
I'm quite new to python and trying to port a simple exploit I've written for a stack overflow (just a nop sled, shell code and return address). This isn't for nefarious purposes but rather for a security lecture at a university. Given a hex string (deadbeef), what are the best ways to: * represent it as a series of bytes * add or subtract a value * reverse the order (for x86 memory layout, i.e. efbeadde) Any tips and tricks regarding common tasks in exploit writing in python are also greatly appreciated.
2011/05/07
[ "https://Stackoverflow.com/questions/5918353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742620/" ]
In Python 2.6 and above, you can use the built-in [`bytearray`](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange) class. To create your `bytearray` object: ``` b = bytearray.fromhex('deadbeef') ``` To alter a byte, you can reference it using array notation: ``` b[2] += 7 ``` To reverse the `bytearray` in place, use `b.reverse()`. To create an iterator that iterates over it in reverse order, you can use the `reversed` function: `reversed(b)`. You may also be interested in the new `bytes` class in Python 3, which is like `bytearray` but immutable.
Not sure if this is the best way... ``` hex_str = "deadbeef" bytes = "".join(chr(int(hex_str[i:i+2],16)) for i in xrange(0,len(hex_str),2)) rev_bytes = bytes[::-1] ``` Or might be simpler: ``` bytes = "\xde\xad\xbe\xef" rev_bytes = bytes[::-1] ```
5,918,353
I'm quite new to python and trying to port a simple exploit I've written for a stack overflow (just a nop sled, shell code and return address). This isn't for nefarious purposes but rather for a security lecture at a university. Given a hex string (deadbeef), what are the best ways to: * represent it as a series of bytes * add or subtract a value * reverse the order (for x86 memory layout, i.e. efbeadde) Any tips and tricks regarding common tasks in exploit writing in python are also greatly appreciated.
2011/05/07
[ "https://Stackoverflow.com/questions/5918353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742620/" ]
In Python 2.6 and above, you can use the built-in [`bytearray`](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange) class. To create your `bytearray` object: ``` b = bytearray.fromhex('deadbeef') ``` To alter a byte, you can reference it using array notation: ``` b[2] += 7 ``` To reverse the `bytearray` in place, use `b.reverse()`. To create an iterator that iterates over it in reverse order, you can use the `reversed` function: `reversed(b)`. You may also be interested in the new `bytes` class in Python 3, which is like `bytearray` but immutable.
In Python 2.x, regular `str` values are binary-safe. You can use the [binascii](http://docs.python.org/library/binascii.html) module's `b2a_hex` and `a2b_hex` functions to convert to and from hexadecimal. You can use ordinary string methods to reverse or otherwise rearrange your bytes. However, doing any kind of arithmetic would require you to use the `ord` function to get numeric values for individual bytes, then `chr` to convert the result back, followed by concatenation to reassemble the modified string. For mutable sequences with easier arithmetic, use the [array](http://docs.python.org/library/array.html) module with type code `'B'`. These can be initialized from the results of `a2b_hex` if you're starting from hexadecimal.
28,771,226
I have a python list question: Input: ``` l=[2, 5, 6, 7, 10, 11, 12, 19, 20, 26, 28, 33, 34, 45, 46, 47, 50, 57, 59, 64, 67, 77, 79, 87, 93, 97, 106, 110, 111, 113, 115, 120, 125, 126, 133, 135, 142, 148, 160, 166, 169, 176, 202, 228, 234, 253, 274, 365, 433, 435, 436, 468, 476, 529, 570, 575, 577, 581, 614, 766, 813, 944, 1058, 1079, 1245, 1363, 1389, 1428, 1758, 2129, 2336, 2402, 2405, 2576, 3013, 3993, 7687, 8142, 8455, 8456] ``` Now I want to write mark the numbers in a [0]\*10000 list, such that the beginning is like: Output: ``` lp=[0,1,0,0,1,...] ``` The second and fifth elements are marked since they appeared in the input.
2015/02/27
[ "https://Stackoverflow.com/questions/28771226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556250/" ]
As you loop through the original array, check whether the current element is the next one in the sequence. If not, use another loop to generate the missing elements: ``` var dataParsed = []; var lastTime = data[0][0]; var timeStep = 60000; for (var i = 0; i < data.length; i++) { var curTime = data[i][0]; if (curTime > lastTime + timeStep) { for (var time = lastTime + timeStep; time < curTime; time += timeStep) { dataParse.push([time, 0]); } } dataParse.push(data[i]); lastTime = curTime; } ```
You can have a loop which counts from first timestamp to the last, incremented by 60 seconds. Then populate a new array with current values + missing values like below. ``` var dataParsed = []; for(var i=data[0][0], j=0; i<=data[data.length-1][0]; i+=60000) { if(i == data[j][0]) { dataParsed.push(data[j]); j++; } else { dataParsed.push([i, 0]); } } ```
63,922,241
I am trying to use python Ctypes to interface to a C++ class I have been provided. I've gotten most everything working in terms of reading/writing member data and calling methods. But The class Im trying to exercise (call it ClassA) relies on an external Class (call it classB). see: ``` //main.cc This is existing caller code. everything is c++ so using it is easy include "ClassA.hh" include "ClassB.hh" void main() { ClassB objB(x,y,z); ClassA objA(a,b, &objB); objA.DoStuff(); } ``` But I'm not ready to do the work to bind and expose classB in python via ctypes. For those who haven't used ctypes, you basically write some C bindings, and call them in python. The class A binding might look like: ``` //at the bottom of ClassA.hh extern "C" { ClassA* ObjaNew(int x, int y) { return new ClassA(x,y);} void ObjaDoStuff(ClassA* objPtr) { objPtr->DoStuff();} } ``` And then the calling code in python might look like ``` mylib = ctypes.cdll('mylib.so') myPyObj = mylib.ObjaNew(5,6) // executes ObjaNew mylib.ObjaDoStuff(myPyObj) // executes ObjaDoStuff ``` An important point being that python ctypes supports native-ish c types only. Creating, Passing or Getting a class or struct or std::vector through the Ctypes interface is work. For example: this link is code that one would need to write to be able to allocate a c++ vector: <https://stackoverflow.com/a/16887455/2312509> So, what I think I want to do is this: ``` //classA.hh class ClassA{ public: ClassA(int a, int b, ClassB* p_objb) { //This is the existing constructor ; //whatever m_objb = p_objb; } ClassA(int a, int b) { // This is my new constructor ClassB *objB = new ClassB(x,y,z); ClassA(a,b,objB); } ``` I've done this and it compiles, but I can't actually run it yet. My concern is that objB is deallocated, because I can't see it as a member, despite it being allocated in the body of a constructor. I feel like if the call to new was being assigned to a member data pointer It would be right, because that how it works, but the assignment to a local pointer, and then passing the local pointer might fail. I think I could maybe create a child class that inherits from both, like: ``` ClassAB: public b():public a(){ //But the A constructor still would need to NOT rely on the existence of ObjB m_objb = &this; } ``` I've not written a whole bunch of C++, so I don't know what the right answer is, But I feel like this isn't a new or novel concept.
2020/09/16
[ "https://Stackoverflow.com/questions/63922241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312509/" ]
Given that you didnt show any code its hard to tell what your really trying to do. However assuming your mean nodes like in a tree then below simple example shows how you could recursivly work back up the tree to show the relationships. this of course is not a complete example but should give you an idea. ```py class node(): def __init__(self, name, parent=None): self.name = name self.parent: node = parent def get_bottom_up_ancestors(self): if self.parent: return [self.name] + self.parent.get_bottom_up_ancestors() return [self.name] def get_top_down_ancestors(self): return self.get_bottom_up_ancestors()[::-1] root = node("Top") child1 = node("first", parent=root) child2 = node("second", parent=root) grandchild1 = node("grandchild", parent=child1) print(grandchild1.get_bottom_up_ancestors()) print(grandchild1.get_top_down_ancestors()) ``` **OUTPUT** ```none ['grandchild', 'first', 'Top'] ['Top', 'first', 'grandchild'] ```
I don't quite understand what you are talking about but from what I DO understand there is no such thing as a parent object only parent classes so a node parent would not be possible
28,915,587
How can i split a **single** key-value pair into dictionary in python? ``` s = "x=y" sp = s.split('=', 1) for key,value in sp: print(key, "==", value) ``` I did not find anything helpful, except using nested `for` and `dict()` which is really unclear.
2015/03/07
[ "https://Stackoverflow.com/questions/28915587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3367446/" ]
``` >>> s = "x=y" >>> dict([s.split('=', 1)]) {'x': 'y'} ```
``` In [1]: s = "x=y" In [2]: sp = s.split('=', 1) In [3]: i=iter(sp) In [4]: new_dict=dict(zip(i,i)) In [5]: new_dict Out[5]: {'x': 'y'} ``` **dict-** It is used for creating a new dictionary. **zip-** It is used for iterating over two lists in parallel. **iter-** Returns a iterator.
28,915,587
How can i split a **single** key-value pair into dictionary in python? ``` s = "x=y" sp = s.split('=', 1) for key,value in sp: print(key, "==", value) ``` I did not find anything helpful, except using nested `for` and `dict()` which is really unclear.
2015/03/07
[ "https://Stackoverflow.com/questions/28915587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3367446/" ]
Just split and unpack: ``` s = "x=y" key,value = s.split('=', 1) print(key, "==", value) x == y items = ["x=y","i=j","a=b"] for ele in items: key, value = ele.split('=', 1) print(key, "==", value) ```
``` In [1]: s = "x=y" In [2]: sp = s.split('=', 1) In [3]: i=iter(sp) In [4]: new_dict=dict(zip(i,i)) In [5]: new_dict Out[5]: {'x': 'y'} ``` **dict-** It is used for creating a new dictionary. **zip-** It is used for iterating over two lists in parallel. **iter-** Returns a iterator.
28,915,587
How can i split a **single** key-value pair into dictionary in python? ``` s = "x=y" sp = s.split('=', 1) for key,value in sp: print(key, "==", value) ``` I did not find anything helpful, except using nested `for` and `dict()` which is really unclear.
2015/03/07
[ "https://Stackoverflow.com/questions/28915587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3367446/" ]
Make it a 1-tuple - I'd also suggest using `str.partition` instead of `str.split`, eg: ``` >>> s = "x=y" >>> dict((s.partition('=')[::2],)) {'x': 'y'} ``` That way, you'll end up with `''` as the value for where no `=` is present. If there should be an `=` then `str.split` it, and let the exception propagate. If only everything after the last `=` should be the value, then `str.rpartition` it instead, eg: ``` >>> s = "x=y=z" >>> dict((s.rpartition('=')[::2],)) {'x=y': 'z'} ``` If you really need to guarantee there's a `=` and only one, so ensuring you have a key/val pair, then: ``` try: d = dict((s.split('=', 2),)) except ValueError: pass # do something appropriate - there's no `=` or more than one ``` And, an alternative, since you're only dealing with a **single** value, and as strings are immutable, it won't cause problems further down the line, then: ``` >>> s = 'x=y' >>> dict.fromkeys(*s.split('=', 2)) {'x': 'y'} ``` But seriously don't use `dict.fromkeys` for this - it's a FYI - it works in this circumstance, but I certainly wouldn't enjoy seeing it in the code base of a production system :)
``` In [1]: s = "x=y" In [2]: sp = s.split('=', 1) In [3]: i=iter(sp) In [4]: new_dict=dict(zip(i,i)) In [5]: new_dict Out[5]: {'x': 'y'} ``` **dict-** It is used for creating a new dictionary. **zip-** It is used for iterating over two lists in parallel. **iter-** Returns a iterator.
21,201,661
I am trying to get the output of serverStatus command via pymongo and then insert it into a mongodb collection. Here is the dictionary `{u'metrics': {u'getLastError': {u'wtime': {u'num': 0, u'totalMillis': 0}, u'wtimeouts': 0L}, u'queryExecutor': {u'scanned': 0L}, u'record': {u'moves': 0L}, u'repl': {u'buffer': {u'count': 0L, u'sizeBytes': 0L, u'maxSizeBytes': 268435456}, u'apply': {u'batches': {u'num': 0, u'totalMillis': 0}, u'ops': 0L}, u'oplog': {u'insert': {u'num': 0, u'totalMillis': 0}, u'insertBytes': 0L}, u'network': {u'bytes': 0L, u'readersCreated': 0L, u'getmores': {u'num': 0, u'totalMillis': 0}, u'ops': 0L}, u'preload': {u'docs': {u'num': 0, u'totalMillis': 0}, u'indexes': {u'num': 0, u'totalMillis': 0}}}, u'ttl': {u'passes': 108L, u'deletedDocuments': 0L}, u'operation': {u'fastmod': 0L, u'scanAndOrder': 0L, u'idhack': 0L}, u'document': {u'deleted': 0L, u'updated': 0L, u'inserted': 1L, u'returned': 0L}}, u'process': u'mongod', u'pid': 7073, u'connections': {u'current': 1, u'available': 818, u'totalCreated': 58L}, u'locks': {u'admin': {u'timeAcquiringMicros': {}, u'timeLockedMicros': {}}, u'local': {u'timeAcquiringMicros': {u'r': 1942L, u'w': 0L}, u'timeLockedMicros': {u'r': 72369L, u'w': 0L}}, u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}}, u'cursors': {u'clientCursors_size': 0, u'timedOut': 0, u'totalOpen': 0}, u'globalLock': {u'totalTime': 6517358000L, u'lockTime': 145679L, u'currentQueue': {u'total': 0, u'writers': 0, u'readers': 0}, u'activeClients': {u'total': 0, u'writers': 0, u'readers': 0}}, u'extra_info': {u'note': u'fields vary by platform', u'page_faults': 21, u'heap_usage_bytes': 62271152}, u'uptime': 6518.0, u'network': {u'numRequests': 103, u'bytesOut': 106329, u'bytesIn': 6531}, u'uptimeMillis': 6517358L, u'recordStats': {u'local': {u'pageFaultExceptionsThrown': 0, u'accessesNotInMemory': 0}, u'pageFaultExceptionsThrown': 0, u'accessesNotInMemory': 0}, u'version': u'2.4.8', u'dur': {u'compression': 0.0, u'journaledMB': 0.0, u'commits': 30, u'writeToDataFilesMB': 0.0, u'commitsInWriteLock': 0, u'earlyCommits': 0, u'timeMs': {u'writeToJournal': 0, u'dt': 3077, u'remapPrivateView': 0, u'prepLogBuffer': 0, u'writeToDataFiles': 0}}, u'mem': {u'resident': 36, u'supported': True, u'virtual': 376, u'mappedWithJournal': 160, u'mapped': 80, u'bits': 64}, u'opcountersRepl': {u'getmore': 0, u'insert': 0, u'update': 0, u'command': 0, u'query': 0, u'delete': 0}, u'indexCounters': {u'missRatio': 0.0, u'resets': 0, u'hits': 0, u'misses': 0, u'accesses': 0}, u'uptimeEstimate': 6352.0, u'host': u'kal-el', u'writeBacksQueued': False, u'localTime': datetime.datetime(2014, 1, 18, 8, 1, 30, 22000), u'backgroundFlushing': {u'last_finished': datetime.datetime(2014, 1, 18, 8, 0, 52, 713000), u'last_ms': 0, u'flushes': 108, u'average_ms': 1.1111111111111112, u'total_ms': 120}, u'opcounters': {u'getmore': 0, u'insert': 1, u'update': 0, u'command': 105, u'query': 108, u'delete': 0}, u'ok': 1.0, u'asserts': {u'msg': 0, u'rollovers': 0, u'regular': 0, u'warning': 0, u'user': 0}}` I am getting "Key '.' must not contain ." error. What could be the issue here? I am not seeing any . in the key name. Here is the traceback: ``` Traceback (most recent call last): File "src/mongodb_status.py", line 37, in <module> get_mongodb_status() File "src/mongodb_status.py", line 23, in get_mongodb_status md_status.insert(status_data) File "/home/guruprasad/dev/py/src/dnacraft_monitor_servers/venv/local/lib/python2.7/site-packages/pymongo/collection.py", line 362, in insert self.database.connection) bson.errors.InvalidDocument: key '.' must not contain '.' ```
2014/01/18
[ "https://Stackoverflow.com/questions/21201661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/649746/" ]
In the 14th line: ``` u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}} ``` For future safety, iterate through the keys, replace '.'s with '\_' or something, and then perform a write.
Here is a function which will remove '.' from your keys: ``` def fix_dict(data, ignore_duplicate_key=True): """ Removes dots "." from keys, as mongo doesn't like that. If the key is already there without the dot, the dot-value get's lost. This modifies the existing dict! :param ignore_duplicate_key: True: if the replacement key is already in the dict, now the dot-key value will be ignored. False: raise ValueError in that case. """ if isinstance(data, (list, tuple)): list2 = list() for e in data: list2.append(fix_dict(e)) # end if return list2 if isinstance(data, dict): # end if for key, value in data.items(): value = fix_dict(value) old_key = key if "." in key: key = old_key.replace(".", "") if key not in data: data[key] = value else: error_msg = "Dict key {key} containing a \".\" was ignored, as {replacement} already exists".format( key=key_old, replacement=key) if force: import warnings warnings.warn(error_msg, category=RuntimeWarning) else: raise ValueError(error_msg) # end if # end if del data[old_key] # end if data[key] = value # end for return data # end if return data # end def ```
21,201,661
I am trying to get the output of serverStatus command via pymongo and then insert it into a mongodb collection. Here is the dictionary `{u'metrics': {u'getLastError': {u'wtime': {u'num': 0, u'totalMillis': 0}, u'wtimeouts': 0L}, u'queryExecutor': {u'scanned': 0L}, u'record': {u'moves': 0L}, u'repl': {u'buffer': {u'count': 0L, u'sizeBytes': 0L, u'maxSizeBytes': 268435456}, u'apply': {u'batches': {u'num': 0, u'totalMillis': 0}, u'ops': 0L}, u'oplog': {u'insert': {u'num': 0, u'totalMillis': 0}, u'insertBytes': 0L}, u'network': {u'bytes': 0L, u'readersCreated': 0L, u'getmores': {u'num': 0, u'totalMillis': 0}, u'ops': 0L}, u'preload': {u'docs': {u'num': 0, u'totalMillis': 0}, u'indexes': {u'num': 0, u'totalMillis': 0}}}, u'ttl': {u'passes': 108L, u'deletedDocuments': 0L}, u'operation': {u'fastmod': 0L, u'scanAndOrder': 0L, u'idhack': 0L}, u'document': {u'deleted': 0L, u'updated': 0L, u'inserted': 1L, u'returned': 0L}}, u'process': u'mongod', u'pid': 7073, u'connections': {u'current': 1, u'available': 818, u'totalCreated': 58L}, u'locks': {u'admin': {u'timeAcquiringMicros': {}, u'timeLockedMicros': {}}, u'local': {u'timeAcquiringMicros': {u'r': 1942L, u'w': 0L}, u'timeLockedMicros': {u'r': 72369L, u'w': 0L}}, u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}}, u'cursors': {u'clientCursors_size': 0, u'timedOut': 0, u'totalOpen': 0}, u'globalLock': {u'totalTime': 6517358000L, u'lockTime': 145679L, u'currentQueue': {u'total': 0, u'writers': 0, u'readers': 0}, u'activeClients': {u'total': 0, u'writers': 0, u'readers': 0}}, u'extra_info': {u'note': u'fields vary by platform', u'page_faults': 21, u'heap_usage_bytes': 62271152}, u'uptime': 6518.0, u'network': {u'numRequests': 103, u'bytesOut': 106329, u'bytesIn': 6531}, u'uptimeMillis': 6517358L, u'recordStats': {u'local': {u'pageFaultExceptionsThrown': 0, u'accessesNotInMemory': 0}, u'pageFaultExceptionsThrown': 0, u'accessesNotInMemory': 0}, u'version': u'2.4.8', u'dur': {u'compression': 0.0, u'journaledMB': 0.0, u'commits': 30, u'writeToDataFilesMB': 0.0, u'commitsInWriteLock': 0, u'earlyCommits': 0, u'timeMs': {u'writeToJournal': 0, u'dt': 3077, u'remapPrivateView': 0, u'prepLogBuffer': 0, u'writeToDataFiles': 0}}, u'mem': {u'resident': 36, u'supported': True, u'virtual': 376, u'mappedWithJournal': 160, u'mapped': 80, u'bits': 64}, u'opcountersRepl': {u'getmore': 0, u'insert': 0, u'update': 0, u'command': 0, u'query': 0, u'delete': 0}, u'indexCounters': {u'missRatio': 0.0, u'resets': 0, u'hits': 0, u'misses': 0, u'accesses': 0}, u'uptimeEstimate': 6352.0, u'host': u'kal-el', u'writeBacksQueued': False, u'localTime': datetime.datetime(2014, 1, 18, 8, 1, 30, 22000), u'backgroundFlushing': {u'last_finished': datetime.datetime(2014, 1, 18, 8, 0, 52, 713000), u'last_ms': 0, u'flushes': 108, u'average_ms': 1.1111111111111112, u'total_ms': 120}, u'opcounters': {u'getmore': 0, u'insert': 1, u'update': 0, u'command': 105, u'query': 108, u'delete': 0}, u'ok': 1.0, u'asserts': {u'msg': 0, u'rollovers': 0, u'regular': 0, u'warning': 0, u'user': 0}}` I am getting "Key '.' must not contain ." error. What could be the issue here? I am not seeing any . in the key name. Here is the traceback: ``` Traceback (most recent call last): File "src/mongodb_status.py", line 37, in <module> get_mongodb_status() File "src/mongodb_status.py", line 23, in get_mongodb_status md_status.insert(status_data) File "/home/guruprasad/dev/py/src/dnacraft_monitor_servers/venv/local/lib/python2.7/site-packages/pymongo/collection.py", line 362, in insert self.database.connection) bson.errors.InvalidDocument: key '.' must not contain '.' ```
2014/01/18
[ "https://Stackoverflow.com/questions/21201661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/649746/" ]
In the 14th line: ``` u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}} ``` For future safety, iterate through the keys, replace '.'s with '\_' or something, and then perform a write.
A solution that worked for me was to wrap the dictionary inside a python list: ``` new_item_to_store = list(dict_to_store.items()) ```
21,201,661
I am trying to get the output of serverStatus command via pymongo and then insert it into a mongodb collection. Here is the dictionary `{u'metrics': {u'getLastError': {u'wtime': {u'num': 0, u'totalMillis': 0}, u'wtimeouts': 0L}, u'queryExecutor': {u'scanned': 0L}, u'record': {u'moves': 0L}, u'repl': {u'buffer': {u'count': 0L, u'sizeBytes': 0L, u'maxSizeBytes': 268435456}, u'apply': {u'batches': {u'num': 0, u'totalMillis': 0}, u'ops': 0L}, u'oplog': {u'insert': {u'num': 0, u'totalMillis': 0}, u'insertBytes': 0L}, u'network': {u'bytes': 0L, u'readersCreated': 0L, u'getmores': {u'num': 0, u'totalMillis': 0}, u'ops': 0L}, u'preload': {u'docs': {u'num': 0, u'totalMillis': 0}, u'indexes': {u'num': 0, u'totalMillis': 0}}}, u'ttl': {u'passes': 108L, u'deletedDocuments': 0L}, u'operation': {u'fastmod': 0L, u'scanAndOrder': 0L, u'idhack': 0L}, u'document': {u'deleted': 0L, u'updated': 0L, u'inserted': 1L, u'returned': 0L}}, u'process': u'mongod', u'pid': 7073, u'connections': {u'current': 1, u'available': 818, u'totalCreated': 58L}, u'locks': {u'admin': {u'timeAcquiringMicros': {}, u'timeLockedMicros': {}}, u'local': {u'timeAcquiringMicros': {u'r': 1942L, u'w': 0L}, u'timeLockedMicros': {u'r': 72369L, u'w': 0L}}, u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}}, u'cursors': {u'clientCursors_size': 0, u'timedOut': 0, u'totalOpen': 0}, u'globalLock': {u'totalTime': 6517358000L, u'lockTime': 145679L, u'currentQueue': {u'total': 0, u'writers': 0, u'readers': 0}, u'activeClients': {u'total': 0, u'writers': 0, u'readers': 0}}, u'extra_info': {u'note': u'fields vary by platform', u'page_faults': 21, u'heap_usage_bytes': 62271152}, u'uptime': 6518.0, u'network': {u'numRequests': 103, u'bytesOut': 106329, u'bytesIn': 6531}, u'uptimeMillis': 6517358L, u'recordStats': {u'local': {u'pageFaultExceptionsThrown': 0, u'accessesNotInMemory': 0}, u'pageFaultExceptionsThrown': 0, u'accessesNotInMemory': 0}, u'version': u'2.4.8', u'dur': {u'compression': 0.0, u'journaledMB': 0.0, u'commits': 30, u'writeToDataFilesMB': 0.0, u'commitsInWriteLock': 0, u'earlyCommits': 0, u'timeMs': {u'writeToJournal': 0, u'dt': 3077, u'remapPrivateView': 0, u'prepLogBuffer': 0, u'writeToDataFiles': 0}}, u'mem': {u'resident': 36, u'supported': True, u'virtual': 376, u'mappedWithJournal': 160, u'mapped': 80, u'bits': 64}, u'opcountersRepl': {u'getmore': 0, u'insert': 0, u'update': 0, u'command': 0, u'query': 0, u'delete': 0}, u'indexCounters': {u'missRatio': 0.0, u'resets': 0, u'hits': 0, u'misses': 0, u'accesses': 0}, u'uptimeEstimate': 6352.0, u'host': u'kal-el', u'writeBacksQueued': False, u'localTime': datetime.datetime(2014, 1, 18, 8, 1, 30, 22000), u'backgroundFlushing': {u'last_finished': datetime.datetime(2014, 1, 18, 8, 0, 52, 713000), u'last_ms': 0, u'flushes': 108, u'average_ms': 1.1111111111111112, u'total_ms': 120}, u'opcounters': {u'getmore': 0, u'insert': 1, u'update': 0, u'command': 105, u'query': 108, u'delete': 0}, u'ok': 1.0, u'asserts': {u'msg': 0, u'rollovers': 0, u'regular': 0, u'warning': 0, u'user': 0}}` I am getting "Key '.' must not contain ." error. What could be the issue here? I am not seeing any . in the key name. Here is the traceback: ``` Traceback (most recent call last): File "src/mongodb_status.py", line 37, in <module> get_mongodb_status() File "src/mongodb_status.py", line 23, in get_mongodb_status md_status.insert(status_data) File "/home/guruprasad/dev/py/src/dnacraft_monitor_servers/venv/local/lib/python2.7/site-packages/pymongo/collection.py", line 362, in insert self.database.connection) bson.errors.InvalidDocument: key '.' must not contain '.' ```
2014/01/18
[ "https://Stackoverflow.com/questions/21201661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/649746/" ]
In the 14th line: ``` u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}} ``` For future safety, iterate through the keys, replace '.'s with '\_' or something, and then perform a write.
An interesting point is that the keys through the dot are not saved for insert\_one And if you save the object, and then update it via find\_one\_and\_update, the keys through the dot will not throw an error Error: ``` product = {'name': 'test_product', 'links': {'test.xyz': 'https://...'}} product_id = products_collection.insert_one(product).inserted_id ``` Working version: ``` product = {'name': 'test_product', 'links': {}} product_id = self.products_collection.insert_one(product).inserted_id products_collection.find_one_and_update( {'_id': product_id}, {'$set': {'links': {'test.xyz': 'https://...'}}} ) ```
53,755,983
There is a related question [here](https://stackoverflow.com/questions/7001917/pause-python-generator). I am attempting to do [this](https://www.hackerrank.com/contests/projecteuler/challenges/euler024/copy-from/1311767864) project Euler challenge on HackerRank. What it requires is that you are able to derive the *n*th permutation of a string "abcdefghijklm". There are 13! permutations. I tried a simple solution where I used `for num, stry in zip(range(1, math.factorial(13)), itertools.permutations("abcdefghijklm"):`. That works, but it times out. What would be really nice is to store each value in a `dict` as I go along, and do something like this: ``` import itertools import math strt = "abcdefghijklm" dic = {} perms_gen = itertools.permutations(strt) idxs_gen = range(1, math.factorial(13)) curr_idx = 0 test_list = [1, 2, 5, 10] def get_elems(n): for num, stry in zip(idxs_gen, perms_gen): print(num) # debug str_stry = "".join(stry) dic[num] = str_stry if num == n: return str_stry for x in test_list: if curr_idx < x: print(get_elems(x)) else: print(dic[x]) ``` This doesn't work. I get this output instead: ``` 1 abcdefghijklm 1 2 abcdefghijlkm 1 2 3 4 5 abcdefghikjml 1 2 3 4 5 6 7 8 9 10 abcdefghilmkj ``` As I was writing this question, I apparently found the answer... to be continued.
2018/12/13
[ "https://Stackoverflow.com/questions/53755983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4476908/" ]
Pausing is built-in functionality for generators. It's half the point of generators. However, `range` is **not a generator**. It's a lazy sequence type. If you want an object where iterating over it again will resume where you last stopped, you want an iterator over the range object: ``` idsx_iter = iter(range(1, math.factorial(13))) ``` However, it would be simpler to save the `zip` iterator instead of two underlying iterators. Better yet, use `enumerate`: ``` indexed_permutations = enumerate(itertools.permutations(strt)) ``` You've got a lot more things that don't make sense in your code, though, like `curr_idx`, which just stays at 0 forever, or your `range` bounds, which produce 13!-1 indices instead of 13! indices, and really, you should be using a more efficient algorithm. For example, one based on figuring out how many permutations you skip ahead by setting the next element to a specific character, and using that to directly compute each element of the permutation.
The answer to the question in the title is "yes", you can pause and restart. How? Unexpectedly (to me), apparently `zip()` restarts the zipped generators despite them being previously defined (maybe someone can tell me why that happens?). So, I added `main_gen = zip(idxs_gen, perms_gen)` and changed to `for num, stry in zip(idxs_gen, perms_gen):` to `for num, stry in main_gen:`. I then get this output, which, assuming the strings are correct, is exactly what I wanted: ``` 1 abcdefghijklm 2 abcdefghijkml 3 4 5 abcdefghijmkl 6 7 8 9 10 abcdefghiklmj ``` After that change, the code looks like this: ``` import itertools import math strt = "abcdefghijklm" dic = {} perms_gen = itertools.permutations(strt) idxs_gen = range(1, math.factorial(13)) main_gen = zip(idxs_gen, perms_gen) curr_idx = 0 test_list = [1, 2, 5, 10] def get_elems(n): for num, stry in main_gen: print(num) str_stry = "".join(stry) dic[num] = str_stry if num == n: return str_stry for x in test_list: if curr_idx < x: print(get_elems(x)) else: print(dic[x]) ```
53,755,983
There is a related question [here](https://stackoverflow.com/questions/7001917/pause-python-generator). I am attempting to do [this](https://www.hackerrank.com/contests/projecteuler/challenges/euler024/copy-from/1311767864) project Euler challenge on HackerRank. What it requires is that you are able to derive the *n*th permutation of a string "abcdefghijklm". There are 13! permutations. I tried a simple solution where I used `for num, stry in zip(range(1, math.factorial(13)), itertools.permutations("abcdefghijklm"):`. That works, but it times out. What would be really nice is to store each value in a `dict` as I go along, and do something like this: ``` import itertools import math strt = "abcdefghijklm" dic = {} perms_gen = itertools.permutations(strt) idxs_gen = range(1, math.factorial(13)) curr_idx = 0 test_list = [1, 2, 5, 10] def get_elems(n): for num, stry in zip(idxs_gen, perms_gen): print(num) # debug str_stry = "".join(stry) dic[num] = str_stry if num == n: return str_stry for x in test_list: if curr_idx < x: print(get_elems(x)) else: print(dic[x]) ``` This doesn't work. I get this output instead: ``` 1 abcdefghijklm 1 2 abcdefghijlkm 1 2 3 4 5 abcdefghikjml 1 2 3 4 5 6 7 8 9 10 abcdefghilmkj ``` As I was writing this question, I apparently found the answer... to be continued.
2018/12/13
[ "https://Stackoverflow.com/questions/53755983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4476908/" ]
Sure you can consume part of an iterator `it`, just call `next(it)` to consume a single item. Or if you need to consume several at once you can write a function to consume `n` items from the iterator. In both cases you just need to take care that the iterator has not reached an end (`StopIteration` raised): ```py def consume(iterator, n): for i in range(n): try: yield next(iterator) except StopIteration: return ``` Which can then be used as such: ```py >>> r = iter(range(5)) >>> print(list(consume(r, 3))) [0, 1, 2] >>> print(list(consume(r, 3))) [3, 4] ``` In the end I don't see why you would need this for this particular problem, and as suggested there is a python function [`itertools.permutations`](https://docs.python.org/3.7/library/itertools.html#itertools.permutations) that already iterate over all permutations for you.
The answer to the question in the title is "yes", you can pause and restart. How? Unexpectedly (to me), apparently `zip()` restarts the zipped generators despite them being previously defined (maybe someone can tell me why that happens?). So, I added `main_gen = zip(idxs_gen, perms_gen)` and changed to `for num, stry in zip(idxs_gen, perms_gen):` to `for num, stry in main_gen:`. I then get this output, which, assuming the strings are correct, is exactly what I wanted: ``` 1 abcdefghijklm 2 abcdefghijkml 3 4 5 abcdefghijmkl 6 7 8 9 10 abcdefghiklmj ``` After that change, the code looks like this: ``` import itertools import math strt = "abcdefghijklm" dic = {} perms_gen = itertools.permutations(strt) idxs_gen = range(1, math.factorial(13)) main_gen = zip(idxs_gen, perms_gen) curr_idx = 0 test_list = [1, 2, 5, 10] def get_elems(n): for num, stry in main_gen: print(num) str_stry = "".join(stry) dic[num] = str_stry if num == n: return str_stry for x in test_list: if curr_idx < x: print(get_elems(x)) else: print(dic[x]) ```
53,755,983
There is a related question [here](https://stackoverflow.com/questions/7001917/pause-python-generator). I am attempting to do [this](https://www.hackerrank.com/contests/projecteuler/challenges/euler024/copy-from/1311767864) project Euler challenge on HackerRank. What it requires is that you are able to derive the *n*th permutation of a string "abcdefghijklm". There are 13! permutations. I tried a simple solution where I used `for num, stry in zip(range(1, math.factorial(13)), itertools.permutations("abcdefghijklm"):`. That works, but it times out. What would be really nice is to store each value in a `dict` as I go along, and do something like this: ``` import itertools import math strt = "abcdefghijklm" dic = {} perms_gen = itertools.permutations(strt) idxs_gen = range(1, math.factorial(13)) curr_idx = 0 test_list = [1, 2, 5, 10] def get_elems(n): for num, stry in zip(idxs_gen, perms_gen): print(num) # debug str_stry = "".join(stry) dic[num] = str_stry if num == n: return str_stry for x in test_list: if curr_idx < x: print(get_elems(x)) else: print(dic[x]) ``` This doesn't work. I get this output instead: ``` 1 abcdefghijklm 1 2 abcdefghijlkm 1 2 3 4 5 abcdefghikjml 1 2 3 4 5 6 7 8 9 10 abcdefghilmkj ``` As I was writing this question, I apparently found the answer... to be continued.
2018/12/13
[ "https://Stackoverflow.com/questions/53755983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4476908/" ]
Pausing is built-in functionality for generators. It's half the point of generators. However, `range` is **not a generator**. It's a lazy sequence type. If you want an object where iterating over it again will resume where you last stopped, you want an iterator over the range object: ``` idsx_iter = iter(range(1, math.factorial(13))) ``` However, it would be simpler to save the `zip` iterator instead of two underlying iterators. Better yet, use `enumerate`: ``` indexed_permutations = enumerate(itertools.permutations(strt)) ``` You've got a lot more things that don't make sense in your code, though, like `curr_idx`, which just stays at 0 forever, or your `range` bounds, which produce 13!-1 indices instead of 13! indices, and really, you should be using a more efficient algorithm. For example, one based on figuring out how many permutations you skip ahead by setting the next element to a specific character, and using that to directly compute each element of the permutation.
Sure you can consume part of an iterator `it`, just call `next(it)` to consume a single item. Or if you need to consume several at once you can write a function to consume `n` items from the iterator. In both cases you just need to take care that the iterator has not reached an end (`StopIteration` raised): ```py def consume(iterator, n): for i in range(n): try: yield next(iterator) except StopIteration: return ``` Which can then be used as such: ```py >>> r = iter(range(5)) >>> print(list(consume(r, 3))) [0, 1, 2] >>> print(list(consume(r, 3))) [3, 4] ``` In the end I don't see why you would need this for this particular problem, and as suggested there is a python function [`itertools.permutations`](https://docs.python.org/3.7/library/itertools.html#itertools.permutations) that already iterate over all permutations for you.
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Your error is this: ``` unable to execute gcc-4.2: No such file or directory ``` Which means that `gcc-4.2` is not installed. Either downgrade (or upgrade) your GCC version, or modify the package to build with just the `gcc` command. A bit more hacky would be to `ln` `gcc-4.2` to the `gcc` command.
I've found the easiest way to install PIL on 10.7 is to create a symlink from gcc-4.2 to gcc. ``` sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 easy_install pil ```
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Your error is this: ``` unable to execute gcc-4.2: No such file or directory ``` Which means that `gcc-4.2` is not installed. Either downgrade (or upgrade) your GCC version, or modify the package to build with just the `gcc` command. A bit more hacky would be to `ln` `gcc-4.2` to the `gcc` command.
try this ``` $ sudo apt-get install python-dev ```
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Your error is this: ``` unable to execute gcc-4.2: No such file or directory ``` Which means that `gcc-4.2` is not installed. Either downgrade (or upgrade) your GCC version, or modify the package to build with just the `gcc` command. A bit more hacky would be to `ln` `gcc-4.2` to the `gcc` command.
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Same problem. Lion, latest xcode. I downloaded and installed a fresh 2.7.2 python and a single virtualenv. ``` $ which pip /opt/local/py_env/default/bin/pip (default)default $ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> quit() (default)default $ which python /opt/local/py_env/default/bin/python ``` I added: ``` export CC=/usr/bin/gcc ``` based on the many answers here about why pip/easy\_install, etc. are having trouble with Lion. That solved the compiling issue, but it fails with the same error on the link step: ``` /usr/bin/gcc -fno-strict-aliasing -fno-common -dynamic -isysroot /DeveloperSDKs/MacOSX10.6.sdk -g -O2 -DNDEBUG -g -O3 -arch i386 -arch x86_64 PSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x080401 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/Library/PostgreSQL/8.4/include -I/Library/PostgreSQL/8.4/include/postgresql/server -c psycopg/typecast.c -o build/temp.macosx-10.6-intel-2.7/psycopg/typecast.o gcc-4.2 -bundle -undefined dynamic_lookup -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g -arch i386 -arch x86_64 build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o build/temp.macosx-10.6-intel-2.7/psycopg/green.o build/temp.macosx-10.6-intel-2.7/psycopg/pqpath.o build/temp.macosx-10.6-intel-2.7/psycopg/utils.o build/temp.macosx-10.6-intel-2.7/psycopg/bytes_format.o build/temp.macosx-10.6-intel-2.7/psycopg/connection_int.o build/temp.macosx-10.6-intel-2.7/psycopg/connection_type.o build/temp.macosx-10.6-intel-2.7/psycopg/cursor_int.o build/temp.macosx-10.6-intel-2.7/psycopg/cursor_type.o build/temp.macosx-10.6-intel-2.7/psycopg/lobject_int.o build/temp.macosx-10.6-intel-2.7/psycopg/lobject_type.o build/temp.macosx-10.6-intel-2.7/psycopg/notify_type.o build/temp.macosx-10.6-intel-2.7/psycopg/xid_type.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_asis.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_binary.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_datetime.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_list.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pboolean.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pdecimal.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pint.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pfloat.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_qstring.o build/temp.macosx-10.6-intel-2.7/psycopg/microprotocols.o build/temp.macosx-10.6-intel-2.7/psycopg/microprotocols_proto.o build/temp.macosx-10.6-intel-2.7/psycopg/typecast.o -L/Library/PostgreSQL/8.4/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.6-intel-2.7/psycopg2/_psycopg.so unable to execute gcc-4.2: No such file or directory ``` 1) I thought that by installing my own Python 2.7.2 that I'd get around the need to use the CC trick because I installed my python fresh. Why not? 2) Is there a similar trick for the name of the linker? This might be getting pretty deep into distutils. **EDIT: RESOLVED** Following many blog/SO suggestions the following worked for me: Recall I am using virtualenv running python 2.7.2 0) added symlink to /bin: ln -s /usr/bin/gcc gcc-4.2 1) Installed latest Postgres. I upgraded from 8.4 to 9.1. Did not uninstall 8.4, did not lose my databases. 2) added /Library/PostgreSQL/9.1/bin to $PATH. I did this in my .profile because I already had 8.4/bin in there, probably for much the same reason. 3) pip install psycopg2 I still am not sure why I need the symlink in this situation. Perhaps because I did not build 2.7.2 from source. However, my django/postgres apps all work. The symlink lets me install other packages that also reference gcc-4.2 in my virtualenv.
I've found the easiest way to install PIL on 10.7 is to create a symlink from gcc-4.2 to gcc. ``` sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 easy_install pil ```
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Same problem. Lion, latest xcode. I downloaded and installed a fresh 2.7.2 python and a single virtualenv. ``` $ which pip /opt/local/py_env/default/bin/pip (default)default $ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> quit() (default)default $ which python /opt/local/py_env/default/bin/python ``` I added: ``` export CC=/usr/bin/gcc ``` based on the many answers here about why pip/easy\_install, etc. are having trouble with Lion. That solved the compiling issue, but it fails with the same error on the link step: ``` /usr/bin/gcc -fno-strict-aliasing -fno-common -dynamic -isysroot /DeveloperSDKs/MacOSX10.6.sdk -g -O2 -DNDEBUG -g -O3 -arch i386 -arch x86_64 PSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x080401 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/Library/PostgreSQL/8.4/include -I/Library/PostgreSQL/8.4/include/postgresql/server -c psycopg/typecast.c -o build/temp.macosx-10.6-intel-2.7/psycopg/typecast.o gcc-4.2 -bundle -undefined dynamic_lookup -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g -arch i386 -arch x86_64 build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o build/temp.macosx-10.6-intel-2.7/psycopg/green.o build/temp.macosx-10.6-intel-2.7/psycopg/pqpath.o build/temp.macosx-10.6-intel-2.7/psycopg/utils.o build/temp.macosx-10.6-intel-2.7/psycopg/bytes_format.o build/temp.macosx-10.6-intel-2.7/psycopg/connection_int.o build/temp.macosx-10.6-intel-2.7/psycopg/connection_type.o build/temp.macosx-10.6-intel-2.7/psycopg/cursor_int.o build/temp.macosx-10.6-intel-2.7/psycopg/cursor_type.o build/temp.macosx-10.6-intel-2.7/psycopg/lobject_int.o build/temp.macosx-10.6-intel-2.7/psycopg/lobject_type.o build/temp.macosx-10.6-intel-2.7/psycopg/notify_type.o build/temp.macosx-10.6-intel-2.7/psycopg/xid_type.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_asis.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_binary.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_datetime.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_list.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pboolean.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pdecimal.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pint.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pfloat.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_qstring.o build/temp.macosx-10.6-intel-2.7/psycopg/microprotocols.o build/temp.macosx-10.6-intel-2.7/psycopg/microprotocols_proto.o build/temp.macosx-10.6-intel-2.7/psycopg/typecast.o -L/Library/PostgreSQL/8.4/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.6-intel-2.7/psycopg2/_psycopg.so unable to execute gcc-4.2: No such file or directory ``` 1) I thought that by installing my own Python 2.7.2 that I'd get around the need to use the CC trick because I installed my python fresh. Why not? 2) Is there a similar trick for the name of the linker? This might be getting pretty deep into distutils. **EDIT: RESOLVED** Following many blog/SO suggestions the following worked for me: Recall I am using virtualenv running python 2.7.2 0) added symlink to /bin: ln -s /usr/bin/gcc gcc-4.2 1) Installed latest Postgres. I upgraded from 8.4 to 9.1. Did not uninstall 8.4, did not lose my databases. 2) added /Library/PostgreSQL/9.1/bin to $PATH. I did this in my .profile because I already had 8.4/bin in there, probably for much the same reason. 3) pip install psycopg2 I still am not sure why I need the symlink in this situation. Perhaps because I did not build 2.7.2 from source. However, my django/postgres apps all work. The symlink lets me install other packages that also reference gcc-4.2 in my virtualenv.
try this ``` $ sudo apt-get install python-dev ```
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Same problem. Lion, latest xcode. I downloaded and installed a fresh 2.7.2 python and a single virtualenv. ``` $ which pip /opt/local/py_env/default/bin/pip (default)default $ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> quit() (default)default $ which python /opt/local/py_env/default/bin/python ``` I added: ``` export CC=/usr/bin/gcc ``` based on the many answers here about why pip/easy\_install, etc. are having trouble with Lion. That solved the compiling issue, but it fails with the same error on the link step: ``` /usr/bin/gcc -fno-strict-aliasing -fno-common -dynamic -isysroot /DeveloperSDKs/MacOSX10.6.sdk -g -O2 -DNDEBUG -g -O3 -arch i386 -arch x86_64 PSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x080401 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/Library/PostgreSQL/8.4/include -I/Library/PostgreSQL/8.4/include/postgresql/server -c psycopg/typecast.c -o build/temp.macosx-10.6-intel-2.7/psycopg/typecast.o gcc-4.2 -bundle -undefined dynamic_lookup -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g -arch i386 -arch x86_64 build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o build/temp.macosx-10.6-intel-2.7/psycopg/green.o build/temp.macosx-10.6-intel-2.7/psycopg/pqpath.o build/temp.macosx-10.6-intel-2.7/psycopg/utils.o build/temp.macosx-10.6-intel-2.7/psycopg/bytes_format.o build/temp.macosx-10.6-intel-2.7/psycopg/connection_int.o build/temp.macosx-10.6-intel-2.7/psycopg/connection_type.o build/temp.macosx-10.6-intel-2.7/psycopg/cursor_int.o build/temp.macosx-10.6-intel-2.7/psycopg/cursor_type.o build/temp.macosx-10.6-intel-2.7/psycopg/lobject_int.o build/temp.macosx-10.6-intel-2.7/psycopg/lobject_type.o build/temp.macosx-10.6-intel-2.7/psycopg/notify_type.o build/temp.macosx-10.6-intel-2.7/psycopg/xid_type.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_asis.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_binary.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_datetime.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_list.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pboolean.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pdecimal.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pint.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_pfloat.o build/temp.macosx-10.6-intel-2.7/psycopg/adapter_qstring.o build/temp.macosx-10.6-intel-2.7/psycopg/microprotocols.o build/temp.macosx-10.6-intel-2.7/psycopg/microprotocols_proto.o build/temp.macosx-10.6-intel-2.7/psycopg/typecast.o -L/Library/PostgreSQL/8.4/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.6-intel-2.7/psycopg2/_psycopg.so unable to execute gcc-4.2: No such file or directory ``` 1) I thought that by installing my own Python 2.7.2 that I'd get around the need to use the CC trick because I installed my python fresh. Why not? 2) Is there a similar trick for the name of the linker? This might be getting pretty deep into distutils. **EDIT: RESOLVED** Following many blog/SO suggestions the following worked for me: Recall I am using virtualenv running python 2.7.2 0) added symlink to /bin: ln -s /usr/bin/gcc gcc-4.2 1) Installed latest Postgres. I upgraded from 8.4 to 9.1. Did not uninstall 8.4, did not lose my databases. 2) added /Library/PostgreSQL/9.1/bin to $PATH. I did this in my .profile because I already had 8.4/bin in there, probably for much the same reason. 3) pip install psycopg2 I still am not sure why I need the symlink in this situation. Perhaps because I did not build 2.7.2 from source. However, my django/postgres apps all work. The symlink lets me install other packages that also reference gcc-4.2 in my virtualenv.
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
I've found the easiest way to install PIL on 10.7 is to create a symlink from gcc-4.2 to gcc. ``` sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 easy_install pil ```
try this ``` $ sudo apt-get install python-dev ```
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
I've found the easiest way to install PIL on 10.7 is to create a symlink from gcc-4.2 to gcc. ``` sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 easy_install pil ```
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/unpacking psycopg2==2.4.2 Running setup.py egg_info for package psycopg2 no previously-included directories found matching 'doc/src/_build' Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 Complete output from command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7: running install running build running build_py running build_ext building 'psycopg2._psycopg' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090004 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.6-intel-2.7/psycopg/psycopgmodule.o unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 ---------------------------------------- Command /Users/my_user/my_enviroment/bin/python -c "import setuptools;__file__='/Users/my_user/my_enviroment/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/b8/jflj9btd4rzb80xfmcy_rk140000gn/T/pip-lojVKc-record/install-record.txt --install-headers /Users/my_user/my_enviroment/bin/../include/site/python2.7 failed with error code 1 Storing complete log in /Users/my_user/.pip/pip.log ``` I am running OSX 10.7, Python 2.7.2, pip 1.0.2, Xcode 4. I have tried the following solutions, with no success: [Cannot install psycopg2 on OSX 10.6.7 with XCode4](https://stackoverflow.com/questions/5427157/cannot-install-psycopg2-on-osx-10-6-7-with-xcode4) [GCC error: command 'gcc-4.0' failed with exit status 1](https://stackoverflow.com/questions/7883372/gcc-error-command-gcc-4-0-failed-with-exit-status-1) Any thoughts? What other information would you need to know?
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
try this ``` $ sudo apt-get install python-dev ```
64,882,718
I'm using Rpy2 within python to call R but for some reason I am not able to load a a specific package, 'rmgarch'. I have installed it separately in R and it works when I import it in RStudio, but for whatever reason, it just doesn't wanna work in rpy2, even though rpy2 is perfectly happy importing other packages such as 'rugarch', 'Matrix', 'zoo', etc. They are all installed in the same library which is even more confusing for me. My question is, do you know an alternative way of calling/importing the package while coding in R? Note that I can import any other package. I tried using devtools because that's the only similar thing I can think of, but it doesn't exist in that universe. I am using R 4.0.3. Python version 3.7.6. An example of the use in Jupyter is: ``` import rpy2 import rpy2.robjects as robjects from rpy2.robjects import pandas2ri from rpy2.robjects.conversion import localconverter utils.install_packages('rmgarch') #;utils.install_pa...rugarch,... robjects.r('''         library('rugarch')         library('quantmod')         library('forecast')         library('rmgarch')         f <- function(u) {             l<-u         }         ''') ``` The error output is: ``` RRuntimeError: Error in library("rmgarch") : there is no package called ‘rmgarch’ ```
2020/11/17
[ "https://Stackoverflow.com/questions/64882718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14290433/" ]
You can integrate with something like this: ```js class BoxCast extends React.Component { componentDidMount() { const {broadcastChannelId, broadcastId} = this.props; this.$el = $(this.el); this.context = boxcast(this.$el); this.context.loadChannel(broadcastChannelId, { autoplay: true, showTitle: true, showDescription: true, showHighlights: true, showRelated: false, selectedBroadcastId: broadcastId }); } componentWillUnmount() { this.context.unload(); } render() { return <div ref={el => this.el = el} />; } } ``` And then using it from some other React component: ```js return ( <BoxCast broadcastChannelId={/* Something */} broadcastId={/* Something */} /> ) ```
This does not looks like its being React compatible. If you insist to use it from React, you'll need to [integrate it](https://reactjs.org/docs/integrating-with-other-libraries.html). It might be a tedious job and I discourage you from doing that. Look for another provider claiming to be React compatible.
54,896,846
What should I do if I want to get the sum of every 3 elements? ``` test_arr = [1,2,3,4,5,6,7,8] ``` It sounds like a map function ``` map_fn(arr, parallel_iterations = True, lambda a,b,c : a+b+c) ``` and the result of `map_fn(test_arr)` should be ``` [6,9,12,15,18,21] ``` which equals to ``` [(1+2+3),(2+3+4),(3+4+5),(4+5+6),(5+6+7),(6+7+8)] ``` --- I have worked out a solution after reviewing the official docs: <https://www.tensorflow.org/api_docs/python/tf/map_fn> ``` import tensorflow as tf def tf_map_elements_every(n, tf_op, input, dtype): if n >= input.shape[0]: return tf_op(input) else: return tf.map_fn( lambda params: tf_op(params), [input[i:i-n+1] if i !=n-1 else input[i:] for i in range(n)], dtype=dtype ) ``` Test ``` t = tf.constant([1, 2, 3, 4, 5, 6, 7, 8]) op = tf_map_elements_every(3, tf.reduce_sum, t, tf.int32) sess = tf.Session() sess.run(op) ``` `[Out]: array([ 6, 9, 12, 15, 18, 21])`
2019/02/27
[ "https://Stackoverflow.com/questions/54896846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5958473/" ]
It's even easier: use a list comprehension. Slice the list into 3-element segments and take the sum of each. Wrap those in a list. ``` [sum(test_arr[i-2:i+1]) for i in range(2, len(test_arr))] ```
Simply loop through your array until you are 3 from the end. ``` # Takes a collection as argument def map_function(array): # Initialise results and i results = [] int i = 0 # While i is less than 3 positions away from the end of the array while(i <= (len(array) - 3)): # Add the sum of the next 3 elements in results results.append(array[i] + array[i + 1] + array[i + 2] # Increment i i += 1 # Return the array return results ```
50,490,556
wx [event handlers](https://wxpython.org/Phoenix/docs/html/events_overview.html) attached with `.Bind(...)` receive as a parameter an event object with a `.Skip()` method. Calling `.Skip()` allows the event's default behaviour to happen; attaching a handler that does not call `.Skip()` suppresses the default behaviour. For instance, an `EVT_CHAR` handler that doesn't call `.Skip()` suppresses the default behaviour of entering the character into the field, thus blocking user input. How about `EVT_TEXT`? Does it have any default behaviour? It doesn't *seem* to - typing into a field with an `EVT_TEXT` handler *appears* to behave the same regardless of whether I call `.Skip()` or not. But is there some edge case or non-obvious effect that's affected by whether I call `.Skip()`, and which should therefore dictate my choice of whether to call it?
2018/05/23
[ "https://Stackoverflow.com/questions/50490556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709587/" ]
Not calling `wxEvent::Skip()` does 2 related but different things: it prevents the default event handler inside the underlying UI toolkit from from processing it and it also prevents any other handlers of the same event in your own code from processing it. The first aspect is indeed not important for command events, which typically don't have any default event handlers at the toolkit level. The second one still is, however, especially because command events bubble upwards the window hierarchy by default. So if you bound some handler to your text control and also happen to have a catch all `wxEVT_TEXT` handler at the frame level, you can easily see the difference between calling `Skip()` or not: the frame handler will only get the event if you do call it. From the practical point of view, you typically do *not* want to skip command event handlers as they should be processed once and once only. But it's not an absolute interdiction and there are situations when you may still do it, e.g. if your event handler didn't do anything with this particular event.
Generally speaking calling Skip() inside the event handler only make sense for non-wxCommandEvent handlers. You can just let the handler finish and you program will do next event iteration. Since wxEVT\_TEXT is wxCommandEvent event calling Skip() does not make much sense. However not calling Skip() on non-wxCommandEvent is bad and you really should know what you are doing if you omit such call.
13,173,029
My friend has an application written in `C` that comes with a GUI made using `GTK` under Linux. Now we want to rewrite the GUI in python (`wxpython` or `PyQT`). I don't have experience with Python and don't know how to make Python communicate with C. I'd like to know if this is possible and if yes, how should I go about implementing it?
2012/11/01
[ "https://Stackoverflow.com/questions/13173029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1703502/" ]
Yes its possible to call 'C' functions from Python. Please look into SWIG(deprecated) also Python provides its own Extensibility API. You might want to look into that. Also google CTypes. LINKS: [Python Extension](http://docs.python.org/2/extending/extending.html) A simple example: I used Cygwin on Windows for this. My python version on this machine is 2.6.8 - tested it with test.py loading the module called "myext.dll" - it works fine. You might want to modify the `Makefile` to make it work on your machine. original.h ---------- ``` #ifndef _ORIGINAL_H_ #define _ORIGINAL_H_ int _original_print(const char *data); #endif /*_ORIGINAL_H_*/ ``` original.c ---------- ``` #include <stdio.h> #include "original.h" int _original_print(const char *data) { return printf("o: %s",data); } ``` stub.c ------ ``` #include <Python.h> #include "original.h" static PyObject *myext_print(PyObject *, PyObject *); static PyMethodDef Methods[] = { {"printx", myext_print, METH_VARARGS,"Print"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initmyext(void) { PyObject *m; m = Py_InitModule("myext",Methods); } static PyObject *myext_print(PyObject *self, PyObject *args) { const char *data; int no_chars_printed; if(!PyArg_ParseTuple(args, "s", &data)){ return NULL; } no_chars_printed = _original_print(data); return Py_BuildValue("i",no_chars_printed); } ``` Makefile -------- ``` PYTHON_INCLUDE = -I/usr/include/python2.6 PYTHON_LIB = -lpython2.6 USER_LIBRARY = -L/usr/lib GCC = gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/include -I/usr/include/python2.6 win32 : myext.o - gcc -shared myext.o $(USER_LIBRARY) $(PYTHON_LIB) -o myext.dll linux : myext.o - gcc -shared myext.o $(USER_LIBRARY) $(PYTHON_LIB) -o myext.so myext.o: stub.o original.o - ld -r stub.o original.o -o myext.o stub.o: stub.c - $(GCC) -c stub.c -o stub.o original.o: original.c - $(GCC) -c original.c -o original.o clean: myext.o - rm stub.o original.o stub.c~ original.c~ Makefile~ ``` test.py ------- ``` import myext myext.printx('hello world') ``` OUTPUT ------ > > o: hello world > > >
> > Sorry but i don't have python experience so don't know how to make Python communicate with C program. > > > Yes, that's exactly how you do it. Turn your C code into a Python module, and then you can write the entire GUI in Python. See [Extending and Embedding the Python Interpreter](http://docs.python.org/2/extending/).
13,173,029
My friend has an application written in `C` that comes with a GUI made using `GTK` under Linux. Now we want to rewrite the GUI in python (`wxpython` or `PyQT`). I don't have experience with Python and don't know how to make Python communicate with C. I'd like to know if this is possible and if yes, how should I go about implementing it?
2012/11/01
[ "https://Stackoverflow.com/questions/13173029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1703502/" ]
Yes its possible to call 'C' functions from Python. Please look into SWIG(deprecated) also Python provides its own Extensibility API. You might want to look into that. Also google CTypes. LINKS: [Python Extension](http://docs.python.org/2/extending/extending.html) A simple example: I used Cygwin on Windows for this. My python version on this machine is 2.6.8 - tested it with test.py loading the module called "myext.dll" - it works fine. You might want to modify the `Makefile` to make it work on your machine. original.h ---------- ``` #ifndef _ORIGINAL_H_ #define _ORIGINAL_H_ int _original_print(const char *data); #endif /*_ORIGINAL_H_*/ ``` original.c ---------- ``` #include <stdio.h> #include "original.h" int _original_print(const char *data) { return printf("o: %s",data); } ``` stub.c ------ ``` #include <Python.h> #include "original.h" static PyObject *myext_print(PyObject *, PyObject *); static PyMethodDef Methods[] = { {"printx", myext_print, METH_VARARGS,"Print"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initmyext(void) { PyObject *m; m = Py_InitModule("myext",Methods); } static PyObject *myext_print(PyObject *self, PyObject *args) { const char *data; int no_chars_printed; if(!PyArg_ParseTuple(args, "s", &data)){ return NULL; } no_chars_printed = _original_print(data); return Py_BuildValue("i",no_chars_printed); } ``` Makefile -------- ``` PYTHON_INCLUDE = -I/usr/include/python2.6 PYTHON_LIB = -lpython2.6 USER_LIBRARY = -L/usr/lib GCC = gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/include -I/usr/include/python2.6 win32 : myext.o - gcc -shared myext.o $(USER_LIBRARY) $(PYTHON_LIB) -o myext.dll linux : myext.o - gcc -shared myext.o $(USER_LIBRARY) $(PYTHON_LIB) -o myext.so myext.o: stub.o original.o - ld -r stub.o original.o -o myext.o stub.o: stub.c - $(GCC) -c stub.c -o stub.o original.o: original.c - $(GCC) -c original.c -o original.o clean: myext.o - rm stub.o original.o stub.c~ original.c~ Makefile~ ``` test.py ------- ``` import myext myext.printx('hello world') ``` OUTPUT ------ > > o: hello world > > >
If you have an option between C or C#(Sharp) then go with C# and use visual studio, you can build the GUI by dragging and dropping components easy. If you want to do something in python look up **wxPython**. Java has a built in GUI builder known as swing. You'll need some tutorials, but unless this program doesn't need to be portable just go with C# and build it in 10 minutes . Also, you can write your code in C and export it as a python module which you can load from python. It`s not very complicated to set up some C functions and have a python GUI which calls them. To achieve this you can use **SWIG, Pyrex, BOOST**.
13,173,029
My friend has an application written in `C` that comes with a GUI made using `GTK` under Linux. Now we want to rewrite the GUI in python (`wxpython` or `PyQT`). I don't have experience with Python and don't know how to make Python communicate with C. I'd like to know if this is possible and if yes, how should I go about implementing it?
2012/11/01
[ "https://Stackoverflow.com/questions/13173029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1703502/" ]
> > Sorry but i don't have python experience so don't know how to make Python communicate with C program. > > > Yes, that's exactly how you do it. Turn your C code into a Python module, and then you can write the entire GUI in Python. See [Extending and Embedding the Python Interpreter](http://docs.python.org/2/extending/).
If you have an option between C or C#(Sharp) then go with C# and use visual studio, you can build the GUI by dragging and dropping components easy. If you want to do something in python look up **wxPython**. Java has a built in GUI builder known as swing. You'll need some tutorials, but unless this program doesn't need to be portable just go with C# and build it in 10 minutes . Also, you can write your code in C and export it as a python module which you can load from python. It`s not very complicated to set up some C functions and have a python GUI which calls them. To achieve this you can use **SWIG, Pyrex, BOOST**.
8,746,586
I'm using [python-mock](http://www.voidspace.org.uk/python/mock/) to mock out a file open call. I would like to be able to pass in fake data this way, so I can verify that `read()` is being called as well as using test data without hitting the filesystem on tests. Here's what I've got so far: ``` file_mock = MagicMock(spec=file) file_mock.read.return_value = 'test' with patch('__builtin__.open', create=True) as mock_open: mock_open.return_value = file_mock with open('x') as f: print f.read() ``` The output of this is `<mock.Mock object at 0x8f4aaec>` intead of `'test'` as I would assume. What am I doing wrong in constructing this mock? Edit: Looks like this: ``` with open('x') as f: f.read() ``` and this: ``` f = open('x') f.read() ``` are different objects. Using the mock as a context manager makes it return a new `Mock`, whereas calling it directly returns whatever I've defined in `mock_open.return_value`. Any ideas?
2012/01/05
[ "https://Stackoverflow.com/questions/8746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112785/" ]
This sounds like a good use-case for a `StringIO` object that already implements the file interface. Maybe you can make a `file_mock = MagicMock(spec=file, wraps=StringIO('test'))`. Or you could just have your function accept a file-like object and pass it a `StringIO` instead of a real file, avoiding the need for ugly monkey-patching. Have you looked the mock documentation? <http://www.voidspace.org.uk/python/mock/compare.html#mocking-the-builtin-open-used-as-a-context-manager>
building on @tbc0 answer, to support Python 2 and 3 (multi-version tests are helpful to port 2 to 3): ``` import sys module_ = "builtins" module_ = module_ if module_ in sys.modules else '__builtin__' try: import unittest.mock as mock except (ImportError,) as e: import mock with mock.patch('%s.open' % module_, mock.mock_open(read_data='test')): with open('/dev/null') as f: print(f.read()) ```
8,746,586
I'm using [python-mock](http://www.voidspace.org.uk/python/mock/) to mock out a file open call. I would like to be able to pass in fake data this way, so I can verify that `read()` is being called as well as using test data without hitting the filesystem on tests. Here's what I've got so far: ``` file_mock = MagicMock(spec=file) file_mock.read.return_value = 'test' with patch('__builtin__.open', create=True) as mock_open: mock_open.return_value = file_mock with open('x') as f: print f.read() ``` The output of this is `<mock.Mock object at 0x8f4aaec>` intead of `'test'` as I would assume. What am I doing wrong in constructing this mock? Edit: Looks like this: ``` with open('x') as f: f.read() ``` and this: ``` f = open('x') f.read() ``` are different objects. Using the mock as a context manager makes it return a new `Mock`, whereas calling it directly returns whatever I've defined in `mock_open.return_value`. Any ideas?
2012/01/05
[ "https://Stackoverflow.com/questions/8746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112785/" ]
In Python 3 the pattern is simply: ``` >>> import unittest.mock as um >>> with um.patch('builtins.open', um.mock_open(read_data='test')): ... with open('/dev/null') as f: ... print(f.read()) ... test >>> ``` (Yes, you can even mock /dev/null to return file contents.)
building on @tbc0 answer, to support Python 2 and 3 (multi-version tests are helpful to port 2 to 3): ``` import sys module_ = "builtins" module_ = module_ if module_ in sys.modules else '__builtin__' try: import unittest.mock as mock except (ImportError,) as e: import mock with mock.patch('%s.open' % module_, mock.mock_open(read_data='test')): with open('/dev/null') as f: print(f.read()) ```
63,307,054
I am learning how to code a game in python(version 3.6), and I have come across an error that has me lost. I tried to run my code and this error message that traced back to sprite.py(A file that I imported from python's library). This is the error message popped up: > > File "C:\Users\aveil\AppData\Roaming\Python\Python36\site-packages\pygame\sprite.py", line 142, > in add self.add(\*group) TypeError: add() argument after \* must be an iterable, not int >>> > > > This is the code that the traceback lead to: ``` has = self.__g.__contains__ for group in groups: if hasattr(group, '_spritegroup'): if not has(group): group.add_internal(self) self.add_internal(group) else: self.add(*group) ``` I did not paste the whole sprite.py file because it has 1.6k lines, but I hope this is enough context. I did not write sprite.py, and am still relatively new to coding, so this error has me stumped. I am not sure where the "int" is or how to change it from an integer to an "iterable". I would appreciate any suggestions!
2020/08/07
[ "https://Stackoverflow.com/questions/63307054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you may find useful the function "replace", also this will allow to do a backup for the file (if you want) ``` string backup = destination + ".bak"; File.Delete(backup); File.Replace(source, destination, backup, true); ``` You can play a little with that. More info: <https://learn.microsoft.com/en-us/dotnet/api/system.io.file.replace?view=netcore-3.1>
If the new image has the same name, you can check the existence of the file and delete it before creating the new file. Note: Make sure the file path is correct (filename along with extension should also be included). ``` if (File.Exists("smb://serverUsername:ServerPassword@serverIP/sharefile/fileToDelete.jpg")) { File.Delete("smb://serverUsername:ServerPassword@serverIP/sharefile/fileToDelete.jpg"); } ```
29,925,783
I am pretty new to programming with python. So apologies in advance: I have two python scripts which should share variables. Furthermore the first script (first.py) should call second script (second.py) first.py: ``` import commands x=5 print x cmd = "path-to-second/second.py" ou = commands.getoutput(cmd) print x ``` second.py looks like this ``` print x x=10 print x ``` I would expect the output: 5 5 10 10 In principle I need a way to communicate between the two scripts. Any solution which does this job is perfectly fine. Thank you for your help! Tim
2015/04/28
[ "https://Stackoverflow.com/questions/29925783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4723963/" ]
C++ does not provide some magical handling for your abstract logic, it cannot just work out that `File1=File2+File3` means you want to merge two files together. Firstly, those variables would have to be some form of 'type', and to have the logic you want, a type of your own devising. It would be constructed from a `std::string` which would be the file name. You would then need to define an `operator+`, this operator would have to some how combine the file names to produce a new one, then make a new file in the operating system, and then add the content of the other two files, finally return a new instance of this type which has this new file name. As I said in a comment though, you really shouldn't do this. Generally speaking, you should not overload operators in C++, unless doing so has VERY clear and obvious results. For instance, a (maths) vector class, fairly clear what `vector_a + vector_b` would (should) do. However, these 'files', it's not so clear, just look at the questions people had to ask. Just one of those should raise a big red flag that it is not a good idea. You should just use a 'normal' function to do what you want to do, something with a name that makes it clear what is going on.
Unfortunately you cannot add two files together like that Instead you have to use `ifstream` and `ofstream` from the `fstream` library Here is an example that you can use ``` std::ifstream file1( "Data1.txt" ) ; std::ifstream file2( "Data2.txt" ) ; std::ofstream combined_file( "dataOut.txt" ) ; combined_file << file1.rdbuf() << file2.rdbuf() ; ```
52,781,297
I setup Ubuntu server 18.04 LTS, LAMP, and mod\_mono (which appears to be working fine alongside PHP now by the way.) Got python working too; at first it gave an HTTP "Internal Server Error" message. `sudo chmod +x myfile.py` fixed this error and the code python generates is displayed fine. But any time the execute permission is removed from the file (such as by uploading a new version of the file), the execute bit is stripped and it breaks again. A work-around was implemented with incrontab, where the cgi-bin folder was monitored for changes and any new writes caused `chmod +x %f` to be ran on them. This worked for awhile, then stopped, and seems a hokey solution at best. Perl, PHP, even ASPX do not need to be marked executable - only python. **Is there any way Apache can "run" python *without* the file marked as executable?**
2018/10/12
[ "https://Stackoverflow.com/questions/52781297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4626146/" ]
I really struggled with this and finally managed to clear it with the following approach: ``` require './aws/aws-autoloader.php'; use Aws\Credentials\Credentials; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use Aws\Signature\SignatureV4; use Aws\Credentials\CredentialProvider; $url = '<your URL>'; $region = '<your region>'; $json = json_encode(["Yourpayload"=>"Please"]); $provider = CredentialProvider::defaultProvider(); $credentials = $provider()->wait(); # $credentials = new Credentials($access_key, $secret_key); # if you do not run from ec2 $client = new Client(); $request = new Request('POST', $url, [], $json); $s4 = new SignatureV4("execute-api", $region); $signedrequest = $s4->signRequest($request, $credentials); $response = $client->send($signedrequest); echo($response->getBody()); ``` This example assumes you are running from an EC2 or something that has an instance profile that is allowed to access this API gateway component and the AWS PHP SDK in the ./aws directory.
You can install AWS php sdk via composer `composer require aws/aws-sdk-php` and here is the github <https://github.com/aws/aws-sdk-php> . In case you want to do something simple or they don't have what you are looking for you can use `curl` in php to post data. ``` $ch = curl_init(); $data = http_build_query([ "entity" => "Business", "action" => "read", "limit" => 100 ]); curl_setopt_array($ch, [ CURLOPT_URL => "https://myendpoint.com/api", CURLOPT_FOLLOWLOCATION => true CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data ]); $response = curl_exec($ch); $error = curl_error($ch); ```
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just\_defines.h as above: ``` #define FOO_A 0x3 #define FOO_B 0x5 ``` Then: ``` swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py ``` Usage: ``` $ python Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import just >>> dir(just) ['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic'] >>> just.FOO_A 3 >>> just.FOO_B 5 >>> ``` If the .h file also contains entry points, then you need to link against some library (or more) to resolve those entry points. That makes the solution a little more complicated since you may have to hunt down the correct libs. But for a "just defines case" you don't have to worry about this.
`#define`s are macros, that have no meaning whatsoever outside of your C compiler's preprocessor. As such, they are the bane of multi-language programmers everywhere. (For example, see this Ada question: [Setting the license for modules in the linux kernel](https://stackoverflow.com/questions/11927590/setting-the-license-for-modules-in-the-linux-kernel) from two weeks ago). Short of running your source code through the C-preprocessor, there really is no good way to deal with them. I typically just figure out what they evalutate to (in complex cases, often there's no better way to do this than to actually compile and run the damn code!), and hard-code that value into my program. The (well one of the) annoying parts is that the C preprocessor is considered by C coders to be a very simple little thing that they often use without even giving a second thought to. As a result, they tend to be shocked that it causes big problems for interoperability, while we can deal with most other problems C throws at us fairly easily. In the simple case shown above, by far the easiest way to handle it would be to encode the same two values in constants in your python program somewhere. If keeping up with changes is a big deal, it probably wouldn't be too much trouble to write a Python program to parse those values out of the file. However, you'd have to realise that your C code would only re-evaluate those values on a compile, while your python program would do it whenever it runs (and thus should probably only be run when the C code is also compiled).
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionality from the top of the script: > > Read #define's and translate to Python code. > Handle #include statements. > Handle #define macros with one argument. > Anything that isn't recognized or doesn't translate into valid > Python is ignored. > > > Without filename arguments, acts as a filter. > If one or more filenames are given, output is written to corresponding > filenames in the local directory, translated to all uppercase, with > the extension replaced by ".py". > > > By passing one or more options of the form "-i regular\_expression" > you can specify additional strings to be ignored. This is useful > e.g. to ignore casts to u\_long: simply specify "-i '(u\_long)'". > > >
`#define`s are macros, that have no meaning whatsoever outside of your C compiler's preprocessor. As such, they are the bane of multi-language programmers everywhere. (For example, see this Ada question: [Setting the license for modules in the linux kernel](https://stackoverflow.com/questions/11927590/setting-the-license-for-modules-in-the-linux-kernel) from two weeks ago). Short of running your source code through the C-preprocessor, there really is no good way to deal with them. I typically just figure out what they evalutate to (in complex cases, often there's no better way to do this than to actually compile and run the damn code!), and hard-code that value into my program. The (well one of the) annoying parts is that the C preprocessor is considered by C coders to be a very simple little thing that they often use without even giving a second thought to. As a result, they tend to be shocked that it causes big problems for interoperability, while we can deal with most other problems C throws at us fairly easily. In the simple case shown above, by far the easiest way to handle it would be to encode the same two values in constants in your python program somewhere. If keeping up with changes is a big deal, it probably wouldn't be too much trouble to write a Python program to parse those values out of the file. However, you'd have to realise that your C code would only re-evaluate those values on a compile, while your python program would do it whenever it runs (and thus should probably only be run when the C code is also compiled).
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
`#define`s are macros, that have no meaning whatsoever outside of your C compiler's preprocessor. As such, they are the bane of multi-language programmers everywhere. (For example, see this Ada question: [Setting the license for modules in the linux kernel](https://stackoverflow.com/questions/11927590/setting-the-license-for-modules-in-the-linux-kernel) from two weeks ago). Short of running your source code through the C-preprocessor, there really is no good way to deal with them. I typically just figure out what they evalutate to (in complex cases, often there's no better way to do this than to actually compile and run the damn code!), and hard-code that value into my program. The (well one of the) annoying parts is that the C preprocessor is considered by C coders to be a very simple little thing that they often use without even giving a second thought to. As a result, they tend to be shocked that it causes big problems for interoperability, while we can deal with most other problems C throws at us fairly easily. In the simple case shown above, by far the easiest way to handle it would be to encode the same two values in constants in your python program somewhere. If keeping up with changes is a big deal, it probably wouldn't be too much trouble to write a Python program to parse those values out of the file. However, you'd have to realise that your C code would only re-evaluate those values on a compile, while your python program would do it whenever it runs (and thus should probably only be run when the C code is also compiled).
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #define DEBUG 1 #ifdef DEBUG #define DEBUG_FILE "debug.log" #else #define NOT_DEBUGGING 1 #endif ``` Using from Python: ``` >>> import configuration >>> print("The verbosity level is %s" % configuration.VERBOSE) The verbosity level is 3 >>> configuration.DEBUG_FILE '"debug.log"' >>> configuration.NOT_DEBUGGING is None True ```
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just\_defines.h as above: ``` #define FOO_A 0x3 #define FOO_B 0x5 ``` Then: ``` swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py ``` Usage: ``` $ python Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import just >>> dir(just) ['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic'] >>> just.FOO_A 3 >>> just.FOO_B 5 >>> ``` If the .h file also contains entry points, then you need to link against some library (or more) to resolve those entry points. That makes the solution a little more complicated since you may have to hunt down the correct libs. But for a "just defines case" you don't have to worry about this.
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionality from the top of the script: > > Read #define's and translate to Python code. > Handle #include statements. > Handle #define macros with one argument. > Anything that isn't recognized or doesn't translate into valid > Python is ignored. > > > Without filename arguments, acts as a filter. > If one or more filenames are given, output is written to corresponding > filenames in the local directory, translated to all uppercase, with > the extension replaced by ".py". > > > By passing one or more options of the form "-i regular\_expression" > you can specify additional strings to be ignored. This is useful > e.g. to ignore casts to u\_long: simply specify "-i '(u\_long)'". > > >
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just\_defines.h as above: ``` #define FOO_A 0x3 #define FOO_B 0x5 ``` Then: ``` swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py ``` Usage: ``` $ python Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import just >>> dir(just) ['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic'] >>> just.FOO_A 3 >>> just.FOO_B 5 >>> ``` If the .h file also contains entry points, then you need to link against some library (or more) to resolve those entry points. That makes the solution a little more complicated since you may have to hunt down the correct libs. But for a "just defines case" you don't have to worry about this.
If you're writing an extension module, use <http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro>
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just\_defines.h as above: ``` #define FOO_A 0x3 #define FOO_B 0x5 ``` Then: ``` swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py ``` Usage: ``` $ python Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import just >>> dir(just) ['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic'] >>> just.FOO_A 3 >>> just.FOO_B 5 >>> ``` If the .h file also contains entry points, then you need to link against some library (or more) to resolve those entry points. That makes the solution a little more complicated since you may have to hunt down the correct libs. But for a "just defines case" you don't have to worry about this.
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #define DEBUG 1 #ifdef DEBUG #define DEBUG_FILE "debug.log" #else #define NOT_DEBUGGING 1 #endif ``` Using from Python: ``` >>> import configuration >>> print("The verbosity level is %s" % configuration.VERBOSE) The verbosity level is 3 >>> configuration.DEBUG_FILE '"debug.log"' >>> configuration.NOT_DEBUGGING is None True ```
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionality from the top of the script: > > Read #define's and translate to Python code. > Handle #include statements. > Handle #define macros with one argument. > Anything that isn't recognized or doesn't translate into valid > Python is ignored. > > > Without filename arguments, acts as a filter. > If one or more filenames are given, output is written to corresponding > filenames in the local directory, translated to all uppercase, with > the extension replaced by ".py". > > > By passing one or more options of the form "-i regular\_expression" > you can specify additional strings to be ignored. This is useful > e.g. to ignore casts to u\_long: simply specify "-i '(u\_long)'". > > >
If you're writing an extension module, use <http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro>
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionality from the top of the script: > > Read #define's and translate to Python code. > Handle #include statements. > Handle #define macros with one argument. > Anything that isn't recognized or doesn't translate into valid > Python is ignored. > > > Without filename arguments, acts as a filter. > If one or more filenames are given, output is written to corresponding > filenames in the local directory, translated to all uppercase, with > the extension replaced by ".py". > > > By passing one or more options of the form "-i regular\_expression" > you can specify additional strings to be ignored. This is useful > e.g. to ignore casts to u\_long: simply specify "-i '(u\_long)'". > > >
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #define DEBUG 1 #ifdef DEBUG #define DEBUG_FILE "debug.log" #else #define NOT_DEBUGGING 1 #endif ``` Using from Python: ``` >>> import configuration >>> print("The verbosity level is %s" % configuration.VERBOSE) The verbosity level is 3 >>> configuration.DEBUG_FILE '"debug.log"' >>> configuration.NOT_DEBUGGING is None True ```
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: ``` #define FOO_A 0x3 #define FOO_B 0x5 ```
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
If you're writing an extension module, use <http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro>
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #define DEBUG 1 #ifdef DEBUG #define DEBUG_FILE "debug.log" #else #define NOT_DEBUGGING 1 #endif ``` Using from Python: ``` >>> import configuration >>> print("The verbosity level is %s" % configuration.VERBOSE) The verbosity level is 3 >>> configuration.DEBUG_FILE '"debug.log"' >>> configuration.NOT_DEBUGGING is None True ```
32,367,279
I start Django server with `python manage.py runserver` and then quit with CONTROL-C, but I can still access urls in `ROOT_URLCONF`, why?
2015/09/03
[ "https://Stackoverflow.com/questions/32367279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Probably you left another process running somewhere else. Here is how you can list all processes whose command contains `manage.py`: ``` ps ax | grep manage.py ``` Here is how you can kill them: ``` pkill -f manage.py ```
Without seeing your script, I would have to say that you have blocking calls, such as socket.recv() or os.system(executable) running at the time of the CTRL+C. Your script is stuck after the CTRL+C because python executes the `KeyboardInterrupt` AFTER the the current command is completed, but before the next one. If there is a blocking function waiting for a response, such as an exit code, packet, or URL, until it times out, you're stuck unless you abort it with task manager or by closing the console. In the case of threading, it kills all threads after it completes its current command. Again, if you have a blocking call, the thread will not exit until it receives its response.
32,367,279
I start Django server with `python manage.py runserver` and then quit with CONTROL-C, but I can still access urls in `ROOT_URLCONF`, why?
2015/09/03
[ "https://Stackoverflow.com/questions/32367279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Without seeing your script, I would have to say that you have blocking calls, such as socket.recv() or os.system(executable) running at the time of the CTRL+C. Your script is stuck after the CTRL+C because python executes the `KeyboardInterrupt` AFTER the the current command is completed, but before the next one. If there is a blocking function waiting for a response, such as an exit code, packet, or URL, until it times out, you're stuck unless you abort it with task manager or by closing the console. In the case of threading, it kills all threads after it completes its current command. Again, if you have a blocking call, the thread will not exit until it receives its response.
just type exit(), that is what I did and it worked
32,367,279
I start Django server with `python manage.py runserver` and then quit with CONTROL-C, but I can still access urls in `ROOT_URLCONF`, why?
2015/09/03
[ "https://Stackoverflow.com/questions/32367279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Probably you left another process running somewhere else. Here is how you can list all processes whose command contains `manage.py`: ``` ps ax | grep manage.py ``` Here is how you can kill them: ``` pkill -f manage.py ```
just type exit(), that is what I did and it worked
71,484,131
I am trying to extract a sub-array using logical indexes as, ``` a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) a Out[45]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) a[b, b] Out[49]: array([ 6, 16]) ``` python evaluates the logical indexes in b per element of a. However in matlab you can do something like ``` >> a = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] a = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 >> b = [2 4] b = 2 4 >> a(b, b) ans = 6 8 14 16 ``` how can I achieve the same result in python without doing, ``` c = a[:, b] c[b,:] Out[51]: array([[ 6, 8], [14, 16]]) ```
2022/03/15
[ "https://Stackoverflow.com/questions/71484131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10976198/" ]
Numpy supports logical indexing, though it is a little different than what you are familiar in MATLAB. To get the results you want you can do the following: ``` a[b][:,b] # first brackets isolates the rows, second brackets isolate the columns Out[27]: array([[ 6, 8], [14, 16]]) ``` The more "numpy" method will be understood after you will understand what happend in your case. `b = np.array([False, True, False, True])` is similar to `b=np.array([1,3])` and will be easier for me to explain. When writing `a[[1,3],[1,3]]` what happens is that numpy crates a (2,1) shape array, and places `a[1,1]` in the `[0]` location and `a[3,3]` in the second location. To create an output of shape (2,2), the indexing must have the same dimensionality. Therefore, the following will get your result: ``` a[[[1,1],[3,3]],[[1,3],[1,3]]] Out[28]: array([[ 6, 8], [14, 16]]) ``` **Explanation**: The indexing arrays are: ``` temp_rows = np.array([[1,1], [3,3]]) temp_cols = np.array([[1,3], [1,3]) ``` both arrays have dimensions of (2,2) and therefore, numpy will create an output of shape (2,2). Then, it places `a[1,1]` in location [0,0], `a[1,3]` in [0,1], `a[3,1]` in location [1,0] and `a[3,3]` in location [1,1]. This can be expanded to any shape but for your purposes, you wanted a shape of (2,2) After figuring this out, you can make things even simpler by utilizing the fact you if you insert a (2,1) array in the 1st dimension and a (1,2) array in the 2nd dimension, numpy will perform the broadcasting, similar to the MATLAB operation. This means that by using: ``` temp_rows = np.array([[1],[3]]) temp_cols = np.array([1,3]) ``` you can do: ``` a[[[1],[3]], [1,3]) Out[29]: array([[ 6, 8], [14, 16]]) ```
You could use [`np.ix_`](https://numpy.org/doc/stable/reference/generated/numpy.ix_.html) here. ``` a[np.ix_(b, b)] # array([[ 6, 8], # [14, 16]]) ``` --- Output returned by `np.ix_` ``` >>> np.ix_(b, b) (array([[1], [3]]), array([[1, 3]])) ```
71,484,131
I am trying to extract a sub-array using logical indexes as, ``` a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) a Out[45]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) a[b, b] Out[49]: array([ 6, 16]) ``` python evaluates the logical indexes in b per element of a. However in matlab you can do something like ``` >> a = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] a = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 >> b = [2 4] b = 2 4 >> a(b, b) ans = 6 8 14 16 ``` how can I achieve the same result in python without doing, ``` c = a[:, b] c[b,:] Out[51]: array([[ 6, 8], [14, 16]]) ```
2022/03/15
[ "https://Stackoverflow.com/questions/71484131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10976198/" ]
You could use [`np.ix_`](https://numpy.org/doc/stable/reference/generated/numpy.ix_.html) here. ``` a[np.ix_(b, b)] # array([[ 6, 8], # [14, 16]]) ``` --- Output returned by `np.ix_` ``` >>> np.ix_(b, b) (array([[1], [3]]), array([[1, 3]])) ```
You could make use of a outer product of the b vector. The new dimesion you can obtain from the number of True values using a sum. ``` import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) # M = np.outer(b, b) new_dim = b.sum() new_shape = (new_dim, new_dim) selection = a[M].reshape(new_shape) ``` The result looks like ``` [[ 6 8] [14 16]] ```
71,484,131
I am trying to extract a sub-array using logical indexes as, ``` a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) a Out[45]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) a[b, b] Out[49]: array([ 6, 16]) ``` python evaluates the logical indexes in b per element of a. However in matlab you can do something like ``` >> a = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] a = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 >> b = [2 4] b = 2 4 >> a(b, b) ans = 6 8 14 16 ``` how can I achieve the same result in python without doing, ``` c = a[:, b] c[b,:] Out[51]: array([[ 6, 8], [14, 16]]) ```
2022/03/15
[ "https://Stackoverflow.com/questions/71484131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10976198/" ]
Numpy supports logical indexing, though it is a little different than what you are familiar in MATLAB. To get the results you want you can do the following: ``` a[b][:,b] # first brackets isolates the rows, second brackets isolate the columns Out[27]: array([[ 6, 8], [14, 16]]) ``` The more "numpy" method will be understood after you will understand what happend in your case. `b = np.array([False, True, False, True])` is similar to `b=np.array([1,3])` and will be easier for me to explain. When writing `a[[1,3],[1,3]]` what happens is that numpy crates a (2,1) shape array, and places `a[1,1]` in the `[0]` location and `a[3,3]` in the second location. To create an output of shape (2,2), the indexing must have the same dimensionality. Therefore, the following will get your result: ``` a[[[1,1],[3,3]],[[1,3],[1,3]]] Out[28]: array([[ 6, 8], [14, 16]]) ``` **Explanation**: The indexing arrays are: ``` temp_rows = np.array([[1,1], [3,3]]) temp_cols = np.array([[1,3], [1,3]) ``` both arrays have dimensions of (2,2) and therefore, numpy will create an output of shape (2,2). Then, it places `a[1,1]` in location [0,0], `a[1,3]` in [0,1], `a[3,1]` in location [1,0] and `a[3,3]` in location [1,1]. This can be expanded to any shape but for your purposes, you wanted a shape of (2,2) After figuring this out, you can make things even simpler by utilizing the fact you if you insert a (2,1) array in the 1st dimension and a (1,2) array in the 2nd dimension, numpy will perform the broadcasting, similar to the MATLAB operation. This means that by using: ``` temp_rows = np.array([[1],[3]]) temp_cols = np.array([1,3]) ``` you can do: ``` a[[[1],[3]], [1,3]) Out[29]: array([[ 6, 8], [14, 16]]) ```
You could make use of a outer product of the b vector. The new dimesion you can obtain from the number of True values using a sum. ``` import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) # M = np.outer(b, b) new_dim = b.sum() new_shape = (new_dim, new_dim) selection = a[M].reshape(new_shape) ``` The result looks like ``` [[ 6 8] [14 16]] ```
60,393,214
In django, I have attempted to switch from using an sqlite3 database to postgresql. `settings.py` has been switched to connect to postgres. Both `python manage.py makemigrations` and `python manage.py migrate` run without errors. `makemigrations` says that it creates the models for the database, however when running `migrate`, it says there is no changes to be made. The django server will run, however when clicking on a specfic table in the database in the `/admin` webpage, it throws the error: ``` ProgrammingError at /admin/app/tablename/ relation "app_tablename" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_tablename" ``` With the same code (other than `settings.py` database connection) this worked when using sqlite3.
2020/02/25
[ "https://Stackoverflow.com/questions/60393214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12959523/" ]
The datapoints on the old domain, i.e. ``` import numpy as np from scipy import interpolate from scipy import misc import matplotlib.pyplot as plt arr = misc.face(gray=True) x = np.linspace(0, 1, arr.shape[0]) y = np.linspace(0, 1, arr.shape[1]) f = interpolate.interp2d(y, x, arr, kind='cubic') x2 = np.linspace(0, 1, 1000) y2 = np.linspace(0, 1, 1600) arr2 = f(y2, x2) arr.shape # (768, 1024) arr2.shape # (1000, 1600) plt.figure() plt.imshow(arr) plt.figure() plt.imshow(arr2) ```
[skimage.transform.resize](https://scikit-image.org/docs/stable/api/skimage.transform.html#skimage.transform.resize) is a very convenient way to do this: ``` import numpy as np from skimage.transform import resize import matplotlib.pyplot as plt from scipy import misc arr = misc.face(gray=True) dim1, dim2 = 1000, 1600 arr2= resize(arr,(dim1,dim2),order=3) #order = 3 for cubic spline print(arr2.shape) plt.figure() plt.imshow(arr) plt.figure() plt.imshow(arr2) ```
26,093,807
I have installed thrift 0.8.0 in Ubuntu 12.04 I followed the all commands correctly with out any error but after installation it's working perfect **Now i want to use PHP by using thrift but in below code it only Shows YES for C++ and Python i need java and PHP but that two languages shows NO How can i use PHP and java in thrift, is there any library for java and php ?** ``` thrift 0.8.0 Building code generators ..... : Building C++ Library ......... : yes Building C (GLib) Library .... : no Building Java Library ........ : no Building C# Library .......... : no Building Python Library ...... : yes Building Ruby Library ........ : no Building Haskell Library ..... : no Building Perl Library ........ : no Building PHP Library ......... : no Building Erlang Library ...... : no Building Go Library .......... : no Building TZlibTransport ...... : yes Building TNonblockingServer .. : yes Using Python ................. : /usr/bin/python ```
2014/09/29
[ "https://Stackoverflow.com/questions/26093807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967915/" ]
First, download the source version of Thrift. I would strongly recommend using a newer version if possible. There are several ways to include the Thrift Java library (may have to change slightly for your Thrift version): If you are using maven, you can add the maven coordinates to your pom.xml: ``` <dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.1</version> </dependency> ``` Alternatively you can just download the JAR and add it your project: <http://central.maven.org/maven2/org/apache/thrift/libthrift/0.9.1/libthrift-0.9.1.jar> If you are using a version that has not been published to the central maven repositories, you can download the source tarball and navigate to the lib/java directory and build it with Apache Ant by typing: ``` ant ``` The library JAR will be in the lib/java/build directory. Optionally you can add the freshly built JAR to your local Maven repository: ``` mvn install:install-file -DartifactId=libthrift -DgroupId=org.apache.thrift -Dvers ``` For the PHP library, navigate to the `lib/php/src` directory and copy the PHP files into your project. You can then use the Thrift\ClassLoader\ThriftClassLoader class or the autoload.php script to include the Thrift PHP library. No build necessary unless you are trying to use the native PHP extension that implements the thrift protocol.
* for Java: you can download .jar library, javadoc here <http://repo1.maven.org/maven2/org/apache/thrift/libthrift/0.9.1/> * for PHP: copy [thrift-source]/lib/php/lib to your project and use it. This is a example to use: <https://thrift.apache.org/tutorial/php> P/s: i want to use .dll PHP extension rather than PHP source files. Anyone care it, we can discuss at here [How can write or find a PHP extension for Apache Thrift](https://stackoverflow.com/questions/26623610/how-can-write-or-find-a-php-extension-for-apache-thrift)
43,383,686
In one of my shell script I am using eval command like below to evaluate the environment path - ``` CONFIGFILE='config.txt' ###Read File Contents to Variables while IFS=\| read TEMP_DIR_NAME EXT do eval DIR_NAME=$TEMP_DIR_NAME echo $DIR_NAME done < "$CONFIGFILE" ``` Output: ``` /path/to/certain/location/folder1 /path/to/certain/location/folder2/another ``` In `config.txt` - ``` $MY_PATH/folder1|.txt $MY_PATH/folder2/another|.jpg ``` What is MY\_PATH? ``` export | grep MY_PATH declare -x MY_PATH="/path/to/certain/location" ``` So is there any way I can get the path from python code like I could get in shell with `eval`
2017/04/13
[ "https://Stackoverflow.com/questions/43383686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2350145/" ]
You can do it a couple of ways depending on where you want to set MY\_PATH. `os.path.expandvars()` expands shell-like templates using the current environment. So if MY\_PATH is set before calling, you do ``` td@mintyfresh ~/tmp $ export MY_PATH=/path/to/certain/location td@mintyfresh ~/tmp $ python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> with open('config.txt') as fp: ... for line in fp: ... cfg_path = os.path.expandvars(line.split('|')[0]) ... print(cfg_path) ... /path/to/certain/location/folder1 /path/to/certain/location/folder2/another ``` If MY\_PATH is defined in the python program, you can use `string.Template` to expand shell-like variables using a local `dict` or even keyword arguments. ``` >>> import string >>> with open('config.txt') as fp: ... for line in fp: ... cfg_path = string.Template(line.split('|')[0]).substitute( ... MY_PATH="/path/to/certain/location") ... print(cfg_path) ... /path/to/certain/location/folder1 /path/to/certain/location/folder2/another ```
You could use os.path.expandvars() (from [Expanding Environment variable in string using python](https://stackoverflow.com/questions/5258647/expanding-environment-variable-in-string-using-python)): ``` import os config_file = 'config.txt' with open(config_file) as f: for line in f: temp_dir_name, ext = line.split('|') dir_name = os.path.expandvars(temp_dir_name) print dir_name ```
69,442,782
At first I thought it was an error connecting with GitHub but this seems to not be the script since the first part of the script fires up normally Full output for context ``` ┌──(kali㉿kali)-[~/bhptrojan] └─$ python3 git_trojan.py 130 ⨯ [*] Attempting to retrieve dirlister [*] Attempting to retrieve environment Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 919, in _find_spec AttributeError: 'GitImporter' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/kali/bhptrojan/git_trojan.py", line 93, in <module> trojan.run() File "/home/kali/bhptrojan/git_trojan.py", line 59, in run config = self.get_config() File "/home/kali/bhptrojan/git_trojan.py", line 41, in get_config exec("import %s" % task['module']) File "<string>", line 1, in <module> File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 982, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 921, in _find_spec File "<frozen importlib._bootstrap>", line 895, in _find_spec_legacy File "/home/kali/bhptrojan/git_trojan.py", line 74, in find_module new_library = get_file_contents('modules', f'{name}.py', self.repo) File "/home/kali/bhptrojan/git_trojan.py", line 23, in get_file_contents return repo.file_contents(f'{dirname}/{module_name}').content File "/home/kali/.local/lib/python3.9/site-packages/github3/repos/repo.py", line 1672, in file_contents json = self._json(self._get(url, params={"ref": ref}), 200) File "/home/kali/.local/lib/python3.9/site-packages/github3/models.py", line 155, in _json raise exceptions.error_for(response) github3.exceptions.NotFoundError: 404 Not Found ``` I also get a few other errors as seen above but I think they are all coming from the one I mentioned but I am not sure. Full code here. ``` import base64 import github3 import importlib import json import random import sys import threading import time from datetime import datetime def github_connect(): with open ('mytoken.txt') as f: token = f.read() user = 'Sebthelad' sess = github3.login(token=token) return sess.repository(user, 'bhptrojan') def get_file_contents(dirname, module_name, repo): return repo.file_contents(f'{dirname}/{module_name}').content class Trojan: def __init__(self,id): self.id = id self.config_file = f'{id}.json' self.data_path = f'data/{id}/' self.repo = github_connect() def get_config(self): config_json = get_file_contents('config', self.config_file, self.repo) config = json.loads(base64.b64decode(config_json)) for task in config: if task['module'] not in sys.modules: exec("import %s" % task['module']) return config def module_runner(self, module): result = sys.modules[module].run() self.store_module_result(result) def store_module_result(self, data): message = datetime.now().isoformat() remote_path = f'data/{self.id}/{message}.data' bindata = bytes('%r' % data, 'utf-8') self.repo.create_file(remote_path,message,base64.b64decode(bindata)) def run(self): while True: config = self.get_config() for task in config: thread = threading.Thread(target=self.module_runner,args=(task['module'],)) thread.start() time.sleep(random.randint(1,10)) time.sleep(random.randint(30*60, 3*60*60)) class GitImporter: def __init__(self): self.current_module_code = "" def find_module(self, name, path=None): print("[*] Attempting to retrieve %s" % name) self.repo = github_connect() new_library = get_file_contents('modules', f'{name}.py', self.repo) if new_library is not None: self.current_module_code = base64.b64decode(new_library) return self def load_module(self,name): spec = importlib.util.spec_from_loader(name, loader=None, origin=self.repo.git_url) new_module = importlib.util.module_from_spec(spec) exec(self.current_module_code, new_module.__dict__) sys.modules[spec.name] = new_module return new_module if __name__ == '__main__': sys.meta_path.append(GitImporter()) trojan = Trojan('abc') trojan.run() ``` Thanks in advance. P.S: If you find any other issues in my code please let me know.
2021/10/04
[ "https://Stackoverflow.com/questions/69442782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16464360/" ]
Here is a possible method of doing this, which should be slightly faster than excessive use of loops. Method: 1. Split each review into its individual words. 2. Create a dictionary with the key being the review word and the value being the frequency. 3. Loop through every topic, then loop through every keyword in that topic. 4. If the keyword is in `reviewsDict`, get the number of occurrences and add it on to `count`'s occurrences. 5. Return dictionary result containing topics and their frequencies. Solution: ``` func countOccurance(topics: [String: [String]], reviews: [String]) -> [String : Int] { var reviewsDict: [String: Int] = [:] for review in reviews { let reviewWords = review.components(separatedBy: CharacterSet.letters.inverted) for word in reviewWords { guard !word.isEmpty else { continue } reviewsDict[word.lowercased(), default: 0] += 1 } } var count: [String: Int] = [:] for (topic, topicKeywords) in topics { for topicKeyword in topicKeywords { guard let occurrences = reviewsDict[topicKeyword] else { continue } count[topic, default: 0] += occurrences } } return count } ``` Result: > > > ``` > 0 : (key: "price", value: 2) > 1 : (key: "business", value: 1) > > ``` > >
I think your `countOccurance(topics:reviews:)` function is violating the single responsibility principle (it's not really counting occurrences, it's also filtering words). As a result, it's very specialized to your one use-case, and you won't find any built-in facilities to help you. On the other hand, if you broke down the problem into smaller, simpler, generic steps, you can leverage existing APIs. Here's how I would do this: I don't know how familiar you are with the Sequence APIs, so I added some comments. Of course, you should remove these from your real code. I've also added some intermediate variables. I think their names act as useful documentation (certainly better than using comments), but that's a matter of taste. ``` extension Sequence where Element: Hashable { typealias Histogram = [Element: Int] func histogram() -> Histogram { // I really with this was built-in :( reduce(into: [:]) { acc, word in acc[word, default: 0] += 1 } } } let topics = [ "price" : ["cheap", "expensive", "price"], "business" : ["small", "medium", "large"] ] // Invert the "topics" dictionary, to obtain a dictionary that can tell you what topic a keyword belongs to. let topicsByKeyword = Dictionary(uniqueKeysWithValues: topics.lazy.flatMap { topic, keywords in keywords.map { keyword in (key: keyword, value: topic) } } ) let reviews = ["large company with expensive items. Some are very cheap"] let reviewWords = reviews .flatMap { $0.components(separatedBy: CharacterSet.letters.inverted) } // Get a flat array of all words in all reviews .filter { !$0.isEmpty } // Filter out the empty words .map { $0.lowercased() } // Lowercase them all let reviewTopicKeywords = reviewWords .compactMap { word in topicsByKeyword[word] } // Map words to the topics they represent let reviewTopicKeywordCounts = reviewTopicKeywords.histogram() // Count the occurrences of the keywords, which is our final result. ``` Using a type might help organize some of these related behaviours: ``` import Foundation extension Sequence where Element: Hashable { typealias Histogram = [Element: Int] func histogram() -> Histogram { reduce(into: [:]) { acc, word in acc[word, default: 0] += 1 } } } struct TopicKeywordCounter { let topicsByKeyword: [String: String] init(keywordsByTopic: [String: [String]]) { // Invert the "topics" dictionary, to obtain a dictionary that can tell you what topic a keyword belongs to. self.topicsByKeyword = Dictionary(uniqueKeysWithValues: keywordsByTopic.lazy.flatMap { topic, keywords in keywords.map { keyword in (key: keyword, value: topic) } } ) } public func countOccurances(in reivews: [String]) -> [String: Int] { let allReviewTopicKeywords = reivews.flatMap { review -> [String] in let reviewWords = allSanitzedWords(in: review) let reviewKeywords = mapWordsToTopics(from: reviewWords) return reviewKeywords } return allReviewTopicKeywords.histogram() } private func allSanitzedWords(in review: String) -> [String] { review .components(separatedBy: CharacterSet.letters.inverted) .filter { !$0.isEmpty } .map { $0.lowercased() } } private func mapWordsToTopics(from words: [String]) -> [String] { words.compactMap { topicsByKeyword[$0] } } } // Make your TopicKeywordCounter let topicKeywordCounter = TopicKeywordCounter(keywordsByTopic: [ "price" : ["cheap", "expensive", "price"], "business" : ["small", "medium", "large"] ]) let reviews = ["large company with expensive items. Some are very cheap"] // ...then use it for any arrays of you reviews you want let reviewTopicKeywordCounts = topicKeywordCounter.countOccurances(in: reviews) print(reviewTopicKeywordCounts) ``` Let me know if you have any questions!
21,559,433
I have the following code in my client: ``` data = {"method": 2,"read": 3} s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(server_address) req = json.dumps(data) s.send(req) ``` and I am trying the following in my server: ``` # Threat the socket as a file stream. worker = self.conn.makefile(mode="rw") # Read the request in a serialized form (JSON). request = worker.readline() result = json.loads(request) print(result) ``` and I am getting the `No JSON object could be decoded` error. I am using python 3.3. I cannot understand where is my mistake, it seems that the send method does not send an json object. Any idea? `Edit`: I fixed the JSON format, the problem now is `<class 'TypeError'>: unsupported operand type(s) for +: 'NoneType' and 'str'` on the server and `s.send(req) TypeError: 'str' does not support the buffer interface` on the client
2014/02/04
[ "https://Stackoverflow.com/questions/21559433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2277094/" ]
I'm assuming you're using python 3, judging by the errors. You'll need to encode your data into bytes. Sockets cannot directly send python3 strings.
Your JSON isn't valid. Put it through JSON lint to find the error. <http://jsonlint.com/>
21,559,433
I have the following code in my client: ``` data = {"method": 2,"read": 3} s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(server_address) req = json.dumps(data) s.send(req) ``` and I am trying the following in my server: ``` # Threat the socket as a file stream. worker = self.conn.makefile(mode="rw") # Read the request in a serialized form (JSON). request = worker.readline() result = json.loads(request) print(result) ``` and I am getting the `No JSON object could be decoded` error. I am using python 3.3. I cannot understand where is my mistake, it seems that the send method does not send an json object. Any idea? `Edit`: I fixed the JSON format, the problem now is `<class 'TypeError'>: unsupported operand type(s) for +: 'NoneType' and 'str'` on the server and `s.send(req) TypeError: 'str' does not support the buffer interface` on the client
2014/02/04
[ "https://Stackoverflow.com/questions/21559433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2277094/" ]
I'm assuming you're using python 3, judging by the errors. You'll need to encode your data into bytes. Sockets cannot directly send python3 strings.
Because that's **not** valid JSON. You can look at [json.org](http://json.org) for the complete spec, and also always use [JSONlint](http://jsonlint.com/) to check your JSON. JSON is made up of key/value pairs. Keys are always strings and must be double quoted. Numeric values are not quoted. ``` {"method":2, "2":3} ``` **Edit due to OP changing question:** The above was merely showing the valid *JSON* ... you of course would need it to be a **string** in your program to do anything with it (like send it over a socket). ``` data = '{"method": 2,"read": 3}' ```
27,849,412
This is the error when I try to get anything with pip3 I'm not sure what to do ``` Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python3/dist-packages/pip/req.py", line 1435, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python3/dist-packages/pip/req.py", line 671, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/lib/python3/dist-packages/pip/req.py", line 901, in move_wheel_files pycompile=self.pycompile, File "/usr/lib/python3/dist-packages/pip/wheel.py", line 206, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 193, in clobber os.makedirs(destsubdir) File "/usr/lib/python3.4/os.py", line 237, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist- packages/Django-1.7.2.dist-info' Storing debug log for failure in /home/omega/.pip/pip.log ```
2015/01/08
[ "https://Stackoverflow.com/questions/27849412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358680/" ]
just install them using --user option which install the package only for the current user and not for all ``` pip install xxxxxx --user ```
You need to use `sudo` to install globally or have permissions to write to the folder. Or as @Alasdair commented using a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/) is a better option.
27,849,412
This is the error when I try to get anything with pip3 I'm not sure what to do ``` Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python3/dist-packages/pip/req.py", line 1435, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python3/dist-packages/pip/req.py", line 671, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/lib/python3/dist-packages/pip/req.py", line 901, in move_wheel_files pycompile=self.pycompile, File "/usr/lib/python3/dist-packages/pip/wheel.py", line 206, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 193, in clobber os.makedirs(destsubdir) File "/usr/lib/python3.4/os.py", line 237, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist- packages/Django-1.7.2.dist-info' Storing debug log for failure in /home/omega/.pip/pip.log ```
2015/01/08
[ "https://Stackoverflow.com/questions/27849412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358680/" ]
You need to use `sudo` to install globally or have permissions to write to the folder. Or as @Alasdair commented using a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/) is a better option.
``` pip3 install --user <package_name> ``` No need to write your username in place of --user.
27,849,412
This is the error when I try to get anything with pip3 I'm not sure what to do ``` Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python3/dist-packages/pip/req.py", line 1435, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python3/dist-packages/pip/req.py", line 671, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/lib/python3/dist-packages/pip/req.py", line 901, in move_wheel_files pycompile=self.pycompile, File "/usr/lib/python3/dist-packages/pip/wheel.py", line 206, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 193, in clobber os.makedirs(destsubdir) File "/usr/lib/python3.4/os.py", line 237, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist- packages/Django-1.7.2.dist-info' Storing debug log for failure in /home/omega/.pip/pip.log ```
2015/01/08
[ "https://Stackoverflow.com/questions/27849412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358680/" ]
just install them using --user option which install the package only for the current user and not for all ``` pip install xxxxxx --user ```
``` pip3 install --user <package_name> ``` No need to write your username in place of --user.
50,963,625
I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the `Python -V` command in cmd I got the following version description `Python 3.6.5 :: Anaconda, Inc.` Now when I run the command it just says `Python 3.6.5.` and the `pip list` is a whole lot shorter. When ever I open Spyder and find some package that I don't have... how would I go about installing said package? If I just open cmd and write `pip install ...` it will install in the "clean" python directory. How do I tell it to connect to Spyder?
2018/06/21
[ "https://Stackoverflow.com/questions/50963625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114229/" ]
I know it's a very late answer, but it may help other people. When you are working with anaconda you can use the basic environement or create a new one (it may be what's you call a "clean" python installation). To do that just do the following : * Open you anaconda navigator * Go to "Environments" * Click on the button create. Here by the way you can choose you python version Then to install your lib you can use your Anaconda GUI : * Double click on you environment * On the right side you have all you installed lib. In the list box select "Not installed" * Look for your lib, check it and click on "apply" on the bottom right You can also do it in your windows console (cmd), I prefer this way (more trust and you can see what's going on) : * Open you console * `conda activate yourEnvName` * `conda install -n yourEnvName yourLib` * *Only if* your conda install did not find your lib do `pip install yourLib` * At the end `conda deactivate` /!\ If you are using this way, close your Anaconda GUI while you are doing this If you want you can find your environement(s) in (on Windows) C:\Users\XxUserNamexX\AppData\Local\Continuum\anaconda3\envs. Each folder will contains the library for the named environement. Hope it will be helpfull PS : Note that it is important to launch spyder through the Anaconda GUI if you want Spyder to find your lib
There is a pip.exe included in the anaconda/Spyder package which can cleanly add mopdules to Spyder. It's not installed in the windows path by default, probably so it' won't interfere with the "normal" pip in my "normal" python package. Check "/c/Users/myname/Anaconda3/Scripts/pip.exe". It seems to depend on local DLLs - it did not work (just hung) until I cd'd into it's directory. Once there I used it to install pymongo in the usual way, and the pymongo package was picked up by Spyder. Hope that helps...
50,963,625
I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the `Python -V` command in cmd I got the following version description `Python 3.6.5 :: Anaconda, Inc.` Now when I run the command it just says `Python 3.6.5.` and the `pip list` is a whole lot shorter. When ever I open Spyder and find some package that I don't have... how would I go about installing said package? If I just open cmd and write `pip install ...` it will install in the "clean" python directory. How do I tell it to connect to Spyder?
2018/06/21
[ "https://Stackoverflow.com/questions/50963625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114229/" ]
If you are using Spyder IDE easiest procedure which i found to install PIP is -: Step 1- Check if Python is installed correctly. The simplest way to test for a Python installation on your Windows server is to open a command prompt (click on the Windows icon and type cmd, then click on the command prompt icon). Once a command prompt window opens, type python and press Enter. If Python is installed correctly, you should see output similar to what is shown below: Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Step 2-: Now in Step 2 Once you’ve confirmed that Python is correctly installed, you can proceed with installing Pip. Download get-pip.py <https://bootstrap.pypa.io/get-pip.py> to a folder on your computer. Open a command prompt and navigate to the folder containing get-pip.py. Run the following command: python get-pip.py Pip is now installed! You can verify that Pip was installed correctly by opening a command prompt and entering the following command: pip -V You should see output similar to the following: pip 18.0 from c:\users\administrator\appdata\local\programs\python\python37\lib\site-packages\pip (python 3.7)`enter code here`
There is a pip.exe included in the anaconda/Spyder package which can cleanly add mopdules to Spyder. It's not installed in the windows path by default, probably so it' won't interfere with the "normal" pip in my "normal" python package. Check "/c/Users/myname/Anaconda3/Scripts/pip.exe". It seems to depend on local DLLs - it did not work (just hung) until I cd'd into it's directory. Once there I used it to install pymongo in the usual way, and the pymongo package was picked up by Spyder. Hope that helps...
50,963,625
I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the `Python -V` command in cmd I got the following version description `Python 3.6.5 :: Anaconda, Inc.` Now when I run the command it just says `Python 3.6.5.` and the `pip list` is a whole lot shorter. When ever I open Spyder and find some package that I don't have... how would I go about installing said package? If I just open cmd and write `pip install ...` it will install in the "clean" python directory. How do I tell it to connect to Spyder?
2018/06/21
[ "https://Stackoverflow.com/questions/50963625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114229/" ]
I know it's a very late answer, but it may help other people. When you are working with anaconda you can use the basic environement or create a new one (it may be what's you call a "clean" python installation). To do that just do the following : * Open you anaconda navigator * Go to "Environments" * Click on the button create. Here by the way you can choose you python version Then to install your lib you can use your Anaconda GUI : * Double click on you environment * On the right side you have all you installed lib. In the list box select "Not installed" * Look for your lib, check it and click on "apply" on the bottom right You can also do it in your windows console (cmd), I prefer this way (more trust and you can see what's going on) : * Open you console * `conda activate yourEnvName` * `conda install -n yourEnvName yourLib` * *Only if* your conda install did not find your lib do `pip install yourLib` * At the end `conda deactivate` /!\ If you are using this way, close your Anaconda GUI while you are doing this If you want you can find your environement(s) in (on Windows) C:\Users\XxUserNamexX\AppData\Local\Continuum\anaconda3\envs. Each folder will contains the library for the named environement. Hope it will be helpfull PS : Note that it is important to launch spyder through the Anaconda GUI if you want Spyder to find your lib
If you are using Spyder IDE easiest procedure which i found to install PIP is -: Step 1- Check if Python is installed correctly. The simplest way to test for a Python installation on your Windows server is to open a command prompt (click on the Windows icon and type cmd, then click on the command prompt icon). Once a command prompt window opens, type python and press Enter. If Python is installed correctly, you should see output similar to what is shown below: Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Step 2-: Now in Step 2 Once you’ve confirmed that Python is correctly installed, you can proceed with installing Pip. Download get-pip.py <https://bootstrap.pypa.io/get-pip.py> to a folder on your computer. Open a command prompt and navigate to the folder containing get-pip.py. Run the following command: python get-pip.py Pip is now installed! You can verify that Pip was installed correctly by opening a command prompt and entering the following command: pip -V You should see output similar to the following: pip 18.0 from c:\users\administrator\appdata\local\programs\python\python37\lib\site-packages\pip (python 3.7)`enter code here`
50,963,625
I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the `Python -V` command in cmd I got the following version description `Python 3.6.5 :: Anaconda, Inc.` Now when I run the command it just says `Python 3.6.5.` and the `pip list` is a whole lot shorter. When ever I open Spyder and find some package that I don't have... how would I go about installing said package? If I just open cmd and write `pip install ...` it will install in the "clean" python directory. How do I tell it to connect to Spyder?
2018/06/21
[ "https://Stackoverflow.com/questions/50963625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114229/" ]
I know it's a very late answer, but it may help other people. When you are working with anaconda you can use the basic environement or create a new one (it may be what's you call a "clean" python installation). To do that just do the following : * Open you anaconda navigator * Go to "Environments" * Click on the button create. Here by the way you can choose you python version Then to install your lib you can use your Anaconda GUI : * Double click on you environment * On the right side you have all you installed lib. In the list box select "Not installed" * Look for your lib, check it and click on "apply" on the bottom right You can also do it in your windows console (cmd), I prefer this way (more trust and you can see what's going on) : * Open you console * `conda activate yourEnvName` * `conda install -n yourEnvName yourLib` * *Only if* your conda install did not find your lib do `pip install yourLib` * At the end `conda deactivate` /!\ If you are using this way, close your Anaconda GUI while you are doing this If you want you can find your environement(s) in (on Windows) C:\Users\XxUserNamexX\AppData\Local\Continuum\anaconda3\envs. Each folder will contains the library for the named environement. Hope it will be helpfull PS : Note that it is important to launch spyder through the Anaconda GUI if you want Spyder to find your lib
I installed spyder without anaconda on linux, and i was missing a module, all i did was installing pip on the linux terminal `sudo apt install python3-pip` and then `pip install "the library name "` and it worked in spyder without any other modification.
50,963,625
I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the `Python -V` command in cmd I got the following version description `Python 3.6.5 :: Anaconda, Inc.` Now when I run the command it just says `Python 3.6.5.` and the `pip list` is a whole lot shorter. When ever I open Spyder and find some package that I don't have... how would I go about installing said package? If I just open cmd and write `pip install ...` it will install in the "clean" python directory. How do I tell it to connect to Spyder?
2018/06/21
[ "https://Stackoverflow.com/questions/50963625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114229/" ]
If you are using Spyder IDE easiest procedure which i found to install PIP is -: Step 1- Check if Python is installed correctly. The simplest way to test for a Python installation on your Windows server is to open a command prompt (click on the Windows icon and type cmd, then click on the command prompt icon). Once a command prompt window opens, type python and press Enter. If Python is installed correctly, you should see output similar to what is shown below: Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Step 2-: Now in Step 2 Once you’ve confirmed that Python is correctly installed, you can proceed with installing Pip. Download get-pip.py <https://bootstrap.pypa.io/get-pip.py> to a folder on your computer. Open a command prompt and navigate to the folder containing get-pip.py. Run the following command: python get-pip.py Pip is now installed! You can verify that Pip was installed correctly by opening a command prompt and entering the following command: pip -V You should see output similar to the following: pip 18.0 from c:\users\administrator\appdata\local\programs\python\python37\lib\site-packages\pip (python 3.7)`enter code here`
I installed spyder without anaconda on linux, and i was missing a module, all i did was installing pip on the linux terminal `sudo apt install python3-pip` and then `pip install "the library name "` and it worked in spyder without any other modification.
30,856,274
I am new to python development using virtualenv. I have installed python 2.7, pip, virtualenv, virtualenvwrapper in windows and I am using windows PS. I have referred lots of tutorials for setting this up. Most of them contained the same steps and almost all of them stopped short of explaining what to do *after* the virtualenv was created. 1. How do I actually work in a virtualenv? suppose I want to create a new flask application after installing that package in my new env virtualenv (eg; testenv). 2. If I already have an existing project and I want to put it inside a newly created virtual env, how do I do that? How should the folder structure be like? 3. My understanding of virtual env is that it provides a sandbox for your application by isolating it and keeping all its dependencies to itself in that particular env (and not sharing and it with others). Have I understood it wrong? Please help me clear this.
2015/06/15
[ "https://Stackoverflow.com/questions/30856274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4051896/" ]
> > How do I actually work in a virtualenv? suppose I want to create a new flask application after installing that package in my new env virtualenv (eg; testenv). > > > You open up Command Prompt and activate the virtualenv: ``` > \path\to\env\Scripts\activate ``` When you run `python` and `pip`, they run in the virtualenv. You have to do this for every Command Prompt window, since working in a virtualenv is really just running `C:\path\to\env\bin\python` instead of just `python` and `C:\path\to\env\bin\pip` instead of `pip`. > > If I already have an existing project and I want to put it inside a newly created virtual env, how do I do that? How should the folder structure be like? > > > It doesn't matter. When you install Python packages, they get installed globally into `C:\Python27\site-packages`. With virtualenv, you can create isolated Python environments that have their own packages, so if you're working on two projects that require different versions of a package, they can coexist without any issues. Some people make a folder for their virtualenvs (like `C:\Users\you\Virtualenvs\my_website`). You can also store it with your project (like `C:\Users\you\Projects\my_website\venv`). Once you activate it, the location doesn't matter. I use the latter. > > My understanding of virtual env is that it provides a sandbox for your application by isolating it and keeping all its dependencies to itself in that particular env (and not sharing and it with others). Have I understood it wrong? > > > Nope. The only point that I would clarify is that the "sandbox" is only for Python's packages, it doesn't affect your application in any way.
1. testenv/bin/pip and testenv/bin/python 2. I'd check it in a local repository and check it out in the virtualenv. 3. No, you have not.
34,093,247
On Windows 8, I've created a sample project in Django (1.6.5) and I'm getting errors when I run a custom command I wrote (runtcpserver). This is how my project structure looks like: c:/django/entitetracker: ``` manage.py tcpserver/ forms.py views.py models.py urls.py management __init__.py command __init__.py runtcpserver.py settings/ __init__.py base.py local.py ``` My manage.py file is as follows: ``` #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "entitetracker.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ``` My path (python 2.7): ``` >>> import sys >>> for path in sys.path: print path C:\django\entitetracker (...other paths) ``` When I run the python manage.py runtcpserver settings=settings.local command, I am getting the following error: ``` Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 261, in fetch_command commands = get_commands() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 107, in get_commands apps = settings.INSTALLED_APPS File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 54, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 49, in _setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 132, in __init__ % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'entitetracker.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named settings ``` In python shell, I tried to import the settings module and I'm getting no error: ``` >>> from settings import local >>> ``` Could someone suggest what I am missing?
2015/12/04
[ "https://Stackoverflow.com/questions/34093247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563130/" ]
Your `PYTHONPATH` is `C:\django\entitetracker`. You can load `entitetracker.settings`. In finish, Python try to find `C:\django\entitetracker\entitetracker\settings` package. Use ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") ```
My God, I'm so stupid. The error was I was missing the two dashes before settings=settings.local! Thanks for your help Tomasz.
48,506,093
I have a REST API backend with python/flask and want to stream the response in an event stream. Everything is running inside a docker container with nginx/uwsgi (<https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/>). The API works fine until it comes to the event-stream. It seems like something (probably nginx) is buffering the "yields" because nothing is received by any kind of client until the server finished the calculation and everything is sent together. I tried to adapt the nginx settings (according to the docker image instructions) with an additional config (nginx\_streaming.conf) file saying: ``` server { location / { include uwsgi_params; uwsgi_request_buffering off; } } ``` dockerfile: =========== ``` FROM tiangolo/uwsgi-nginx-flask:python3.6 COPY ./app /app COPY ./nginx_streaming.conf /etc/nginx/conf.d/nginx_streaming.conf ``` But I am not really familiar with nginx settings and sure what I am doing here^^ This at least does not work.. any suggestions? My server side implementation: ``` from flask import Flask from flask import stream_with_context, request, Response from werkzeug.contrib.cache import SimpleCache cache = SimpleCache() app = Flask(__name__) from multiprocessing import Pool, Process @app.route("/my-app") def myFunc(): global cache arg = request.args.get(<my-arg>) cachekey = str(arg) print(cachekey) result = cache.get(cachekey) if result is not None: print('Result from cache') return result else: print('object not in Cache...calculate...') def calcResult(): yield 'worker thread started\n' with Pool(processes=cores) as parallel_pool: [...] yield 'Somewhere in the processing' temp_result = doSomethingWith( savetocache = cache.set(cachekey, temp_result, timeout=60*60*24) #timeout in seconds yield 'saved to cache with key:' + cachekey +'\n' print(savetocache, flush=True) yield temp_result return Response(calcResult(), content_type="text/event-stream") if __name__ == "__main__": # Only for debugging while developing app.run(host='0.0.0.0', debug=True, port=80) ```
2018/01/29
[ "https://Stackoverflow.com/questions/48506093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5623899/" ]
I ran into the same problem. Try changing ``` return Response(calcResult(), content_type="text/event-stream") ``` to ``` return Response(calcResult(), content_type="text/event-stream", headers={'X-Accel-Buffering': 'no'}) ```
Following [the answer from @u-rizwan here](https://stackoverflow.com/a/48746083/236195), I added this to the `/etc/nginx/conf.d/mysite.conf` and it resolved the problem: ``` add_header X-Accel-Buffering no; ``` I have added it under `location /`, but it is probably a good idea to put it under the specific location of the event stream (I have a low traffic intranet use case here). Note: Looks like nginx could be stripping this header by default if it comes from the application: <https://serverfault.com/questions/937665/does-nginx-show-x-accel-headers-in-response>
4,982,138
I am on exercise 43 doing some self-directed work in [Learn Python The Hard Way](http://learnpythonthehardway.org/). And I have designed the framework of a game spread out over two python files. The point of the exercise is that each "room" in the game has a different class. I have tried a number of things, but I cannot figure out how to use the returned value from their initial choice to advance the user to the proper "room", which is contained within a class. Any hints or help would be greatly appreciated. Apologies for the poor code, I'm just starting out in python, but at my wit's end on this. Here is the ex43\_engine.py code which I run to start the game. --- ``` from ex43_map import * import ex43_map import inspect #Not sure if this part is neccessary, generated list of all the classes (rooms) I imported from ex43_map.py, as I thought they might be needed to form a "map" class_list = [] for name, obj in inspect.getmembers(ex43_map): if inspect.isclass(obj): class_list.append(name) class Engine(object): def __init__(self, room): self.room = room def play(self): # starts the process, this might need to go inside the loop below next = self.room start.transportation_choice() while True: print "\n-------------" # I have tried numerous things here to make it work...nothing has start = StartRoom() car = CarRoom() bus = BusRoom() train = TrainRoom() airplane = AirplaneRoom() terminal = TerminalRoom() a_game = Engine("transportation_choice") a_game.play() ``` --- And here is the ex43\_map.py code --- ``` from sys import exit from random import randint class StartRoom(object): def __init__(self): pass def transportation_choice(self): print "\nIt's 6 pm and you have just found out that you need to get to Chicago by tomorrow morning for a meeting" print "How will you choose to get there?\n" print "Choices: car, bus, train, airplane" choice = raw_input("> ") if choice == "car": return 'CarRoom' elif choice == "bus": return 'BusRoom' elif choice == "train": return 'TrainRoom' elif choice == "airplane": return 'AirplaneRoom' else: print "Sorry but '%s' wasn't a choice." % choice return 'StartRoom' class CarRoom(object): def __init__(self): print "Welcome to the CarRoom" class BusRoom(object): def __init__(self): print "Welcome to the BusRoom" class TrainRoom(object): def __init__(self): print "Welcome to the TrainRoom" class AirplaneRoom(object): def __init__(self): print "Welcome to the AirplaneRoom" class TerminalRoom(object): def __init__(self): self.quips = [ "Oh so sorry you died, you are pretty bad at this.", "Too bad, you're dead buddy.", "The end is here.", "No more playing for you, you're dead." ] def death(self): print self.quips[randint(0, len(self.quips)-1)] # randomly selects one of the quips from 0 to # of items in the list and prints it exit(1) ``` ---
2011/02/13
[ "https://Stackoverflow.com/questions/4982138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614742/" ]
Instead of returning a string try returning an object, ie ``` if choice == "car": return CarRoom() ```
1. It might be a good idea to make a Room class, and derive your other rooms from it. 2. The Room base class can then have a class variable which automatically keeps track of all instantiated rooms. I haven't thoroughly tested the following, but hopefully it will give you some ideas: ``` # getters.py try: getStr = raw_input # Python 2.x except NameError: getStr = input # Python 3.x getStr.type = str def typeGetter(dataType): def getter(msg): while True: try: return dataType(getStr(msg)) except ValueError: pass getter.type = dataType return getter getInt = typeGetter(int) getFloat = typeGetter(float) getBool = typeGetter(bool) def getOneOf(*args, **kwargs): """Get input until it matches an item in args, then return the item @param *args: items to match against @param getter: function, input-getter of desired type (defaults to getStr) @param prompt: string, input prompt (defaults to '> ') Type of items should match type of getter """ argSet = set(args) getter = kwargs.get('getter', getStr) prompt = kwargs.get('prompt', '> ') print('[{0}]'.format(', '.join(args))) while True: res = getter(prompt) if res in argset: return res ``` . ``` # ex43_rooms.py import textwrap import random import getters class Room(object): # list of instantiated rooms by name ROOMS = {} @classmethod def getroom(cls, name): """Return room instance If named room does not exist, throws KeyError """ return cls.ROOMS[name] def __init__(self, name): super(Room,self).__init__() self.name = name Room.ROOMS[name] = self def run(self): """Enter the room - what happens? Abstract base method (subclasses must override) @retval Room instance to continue or None to quit """ raise NotImplementedError() def __str__(self): return self.name def __repr__(self): return '{0}({1})'.format(self.__class__.__name__, self.name) class StartRoom(Room): def __init__(self, name): super(StartRoom,self).__init__(name) def run(self): print textwrap.dedent(""" It's 6 pm and you have just found out that you need to get to Chicago by tomorrow morning for a meeting! How will you get there? """) inp = getters.getOneOf('car','bus','train','airplane') return Room.getroom(inp) class CarRoom(Room): def __init__(self,name): super(CarRoom,self).__init__(name) class BusRoom(Room): def __init__(self,name): super(BusRoom,self).__init__(name) class TrainRoom(Room): def __init__(self,name): super(TrainRoom,self).__init__(name) class PlaneRoom(Room): def __init__(self,name): super(PlaneRoom,self).__init__(name) class TerminalRoom(Room): def __init__(self,name): super(TerminalRoom,self).__init__(name) def run(self): print(random.choice(( "Oh so sorry you died, you are pretty bad at this.", "Too bad, you're dead buddy.", "The end is here.", "No more playing for you, you're dead." ))) return None # create rooms (which registers them with Room) StartRoom('start') CarRoom('car') BusRoom('bus') TrainRoom('train') PlaneRoom('airplane') TerminalRoom('terminal') ``` . ``` # ex43.py from ex43_rooms import Room def main(): here = Room.getroom('start') while here: here = here.run() if __name__=="__main__": main() ```
13,822,823
Currently, it is possible to **mark** tests and then run them (or not run them) using `-m` argument. However, all tests are still collected first and only then are **deselected** In the below example all 8 are still collected, and then 4 are run and 4 are deselected. ``` ============================= test session starts ============================== platform win32 -- Python 2.7.3 -- pytest-2.3.2 -- C:\Python27\python.exe collecting ... collected 8 items test_0001_login_logout.py:24: TestLoginLogout.test_login_page_ui PASSED test_0001_login_logout.py:36: TestLoginLogout.test_login PASSED test_0001_login_logout.py:45: TestLoginLogout.test_default_admin_has_users_folder_page_loaded_by_default PASSED test_0001_login_logout.py:49: TestLoginLogout.test_logout PASSED ==================== 4 tests deselected by "-m 'undertest'" ==================== ================== 4 passed, 4 deselected in 1199.28 seconds =================== ``` QUESTION: Is it possible to **not collect** marked/unmarked tests at all? The problems are: 1) I'm using some test when the database already has some items in it (like my *device*) and the code it have: ``` @pytest.mark.device class Test1_Device_UI_UnSelected(SetupUser): #get device from the database device = Devices.get_device('t400-alex-win7') @classmethod @pytest.fixture(scope = "class", autouse = True) def setup(self): ... ``` I run the test explicitly excluding and *device* tests: `py.test -m "not device"` however, during collection I get the errors, because `device = Devices.get_device('t400-alex-win7')` is still being executed. 2) Some of the tests are marked `time_demanding` because there are around 400 generated tests. To generate those tests is also takes time. I exclude those tests from the *general* tests, however they are generated and collected and then deselected <- just a wait of time. I know there is a solution for (1) problem - to use pytest.fixtures and pass them to the tests, however I really like *autocompletion* that PyDev provides. `timedemanding` class is: ``` import pytest #... other imports def admin_rights_combinations(admin, containing = ["right"]): ''' Generate all possible combinations of admin rights settings depending on "containing" restriction ''' rights = [right for right in admin.__dict__.iterkeys() if any(psbl_match in right for psbl_match in containing)] total_list = [] l = [] for right in rights: #@UnusedVariable l.append([True, False]) for st_of_values in itertools.product(*l): total_list.append(dict(zip(rights, st_of_values))) return total_list @pytest.mark.timedemanding class Test1_Admin_Rights_Access(SetupUser): user = UserFactory.get_user("Admin Rights Test") user.password = "RightsTest" folder = GroupFolderFactory.get_folder("Folders->Admin Rights Test Folder") group = GroupFolderFactory.get_group("Folders->Admin Rights Test Group") admin = UserFactory.get_admin("Admin Rights Test") @classmethod @pytest.fixture(scope = "class", autouse = True) def setup(self): ... @pytest.mark.parametrize("settings", admin_rights_combinations(admin, containing=['right_read', 'right_manage_folders', 'right_manage_groups'])) def test_admin_rights_menus(self, base_url,settings): ''' test combination of admin rights and pages that are displayed with this rights. Also verify that menu's that are available can be opened ''' ``` As you can see, by the time pytest hits `@pytest.mark.parametrize` it should be already aware that it's in Class with `@pytest.mark.timedemanding`. However, collection still occurs.
2012/12/11
[ "https://Stackoverflow.com/questions/13822823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167879/" ]
The problem is not `py.test`, but the fact that the class code is executed when the file is imported, so you get the error **before** the decorator is even called. The only way(without modifying the logic of the code) to avoid this is to completely ignore the whole file. Anyway, I do not understand why you set the `device` class attribute there. Use the class-level `setup`! If you put that code in the setup your problem should be solved, because, since the test is not run, the setup is not called either and you do not get the error. The same goes for the `time_demanding` tests. Set them up in the class level setup, so that `py.test` does the class creation does not take so much time(even though, without a sample code, I can't say much about this). If you want to keep things like this, and have PyDev autocompletion, then, as I said, just ignore the whole file with some regex(and eventually you'll have to split up the tests).
Deselecting tests only after collection is complete happens for two reasons: * to always get a correct number of overall tests * collection hooks might dynamically add or remove marks Regarding auto-completion, i believe putting heavy setup into fixtures is more important. I am not sure if Pydev could learn to still auto-complete. You must have this issue also for regular python functions which take in an argument where Pydev cannot really know what type it is. FWIW i am living well with the dumb vim-completion which simply looks through all strings/names in all the buffers and completes on that. It gives more false positives but no false negatives.
60,932,166
I'm setting up a image data pipeline on Tensorflow 2.1. I'm using a dataset with RGB images of variable shapes (h, w, 3) and I can't find a way to make it work. I get the following error when I call `tf.data.Dataset.batch()` : `tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot batch tensors with different shapes in component 0. First element had shape [256,384,3] and element 3 had shape [160,240,3]` I found the `padded_batch` method but I don't want my images to be padded to the same shape. **EDIT:** I think that I found a little workaround to this by using the function `tf.data.experimental.dense_to_ragged_batch` (which convert the dense tensor representation to a ragged one). > > Unlike `tf.data.Dataset.batch`, the input elements to be batched may have different shapes, and each batch will be encoded as a `tf.RaggedTensor` > > > But then I have another problem. My dataset contains images and their corresponding labels. When I use the function like this: ``` ds = ds.map( lambda x: tf.data.experimental.dense_to_ragged_batch(batch_size) ) ``` I get the following error because it tries to map the function to the entire dataset (thus to images and labels), which is not possible because it can only be applied to a 1 single tensor (not 2). `TypeError: <lambda>() takes 1 positional argument but 2 were given` Is there a way to specify which element of the two I want the transformation to be applied to ?
2020/03/30
[ "https://Stackoverflow.com/questions/60932166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9727793/" ]
I just hit the same problem. The solution turned out to be loading the data as 2 datasets and then using dataet.zip() to merge them. ``` images = dataset.map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE) images = dataset_images.apply( tf.data.experimental.dense_to_ragged_batch(batch_size=batch_size, drop_remainder=True)) dataset_total_cost = dataset.map(get_total_cost) dataset_total_cost = dataset_total_cost.batch(batch_size, drop_remainder=True) dataset = dataset.zip((dataset_images, dataset_total_cost)) ```
If you do not want to resize your images, you can only use a batch size of `1` and not bigger than that. Thus you can train your model one image at at time. The error you reported clearly says that you are using a batch size bigger than 1 and trying to put two images of different shape/size in a batch. You could either resize your images to a fixed shape (or pad your images), or use batch size of 1 as follows: ``` my_data = tf.data.Dataset(....) # with whatever arguments you use here my_data = my_data.batch(1) ```
23,526,592
I am trying to extract the stem of the words `taller` and `shorter` from a string in python. I did the following: ``` >>> from nltk.stem.porter import * >>> print(stemmer.stem('shorter')) shorter >>> print(stemmer.stem('taller')) taller ``` And for some reason, I don't get the words `tall` and `short`. Anyone knows how to possibly fix this, or possibly guide to an alternative solution?
2014/05/07
[ "https://Stackoverflow.com/questions/23526592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2816349/" ]
There are a few stemmers. Here's one: ``` >>> from nltk.stem.lancaster import LancasterStemmer >>> stemmer = LancasterStemmer() >>> stemmer.stem('shorter') 'short' ```
``` >>> from nltk import stem >>> s = 'short'; t = 'tall' >>> porter = stem.porter.PorterStemmer() >>> lancaster = stem.lancaster.LancasterStemmer() >>> snowball = stem.snowball.EnglishStemmer() >>> porter.stem(s) u'short' >>> porter.stem(t) u'tall' >>> lancaster.stem(s) 'short' >>> lancaster.stem(t) 'tal' >>> snowball.stem(s) u'short' >>> snowball.stem(t) u'tall' ```
69,103,209
I have a [dataset](https://drive.google.com/file/d/1EariymtHoBJEflDPkJTg-jKxMfVhll59/view?usp=sharing) containing nested json object. I wish to extract information from this nested json and put it in a DataFrame in python. I have used json\_normalize method but i am unable to parse after a certain level. Kindly help. Thank you.
2021/09/08
[ "https://Stackoverflow.com/questions/69103209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7054640/" ]
Have been working on a function that will expand all embedded lists and dictionaries. ``` from pathlib import Path with open(Path.home().joinpath("Downloads").joinpath("Sample Json.txt")) as f: js = f.read() def normalize(js, expand_all=False): df = pd.json_normalize(json.loads(js) if type(js) == str else js) # get first column that contains lists col = df.applymap(type).astype(str).eq("<class 'list'>").all().idxmax() # explode list and expand embedded dictionaries df = df.explode(col).reset_index(drop=True) df = df.drop(columns=[col]).join(df[col].apply(pd.Series), rsuffix=f".{col}") # any dictionary to expand? if df.applymap(type).astype(str).eq("<class 'dict'>").any().any(): col = df.applymap(type).astype(str).eq("<class 'dict'>").all().idxmax() df = df.drop(columns=[col]).join(df[col].apply(pd.Series), rsuffix=f".{col}") # any lists left? while expand_all and df.applymap(type).astype(str).eq("<class 'list'>").any().any(): df = normalize(df.to_dict("records")) return df df = normalize(js, expand_all=True) ``` | | cfs | ctin | fldtr1 | cfs3b | flprdr1 | dtcancel | val | inv\_typ | pos | idt | rchrg | inum | chksum | num | csamt | samt | rt | txval | camt | iamt | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 0 | Y | 03AZX | 10-Aug-20 | Y | Jul-20 | nan | 2390 | R | 03 | 27-07-2020 | N | TI/20-21/111 | 24ea1a46933dd7c6f130cc7ddce3ad89f42194d84e358746f66716d0f1b8aef0 | 101 | 0 | 182.25 | 18 | 2025 | 182.25 | 0 | | 1 | Y | 03AZY | 02-Sep-20 | Y | Jul-20 | nan | 10756 | R | 03 | 20-07-2020 | N | 70 | 164777293c8ce80595cd4803c3d0287bc544772fb9e5331602ed3d7d0534e82f | 1801 | 0 | 820.35 | 18 | 9115 | 820.35 | nan | | 2 | Y | 03A00P1Z7 | 10-Aug-20 | Y | Jul-20 | nan | 411.82 | R | 03 | 01-07-2020 | N | 18IPB06013580804 | 0560d2b220de53f458ac65594f50bfa5ba736f95061c88201d91371fbeccabf8 | 1 | 0 | 31.41 | 18 | 349 | 31.41 | nan | | 3 | Y | 03A00P1Z7 | 10-Aug-20 | Y | Jul-20 | nan | 411.82 | R | 03 | 01-07-2020 | N | 18IPB06013580805 | 08ae71bcb591723318796e797da586ef9b8e5b6b920e9877be6afc9223486760 | 1 | 0 | 31.41 | 18 | 349 | 31.41 | nan | | 4 | Y | 03A00P1Z7 | 10-Aug-20 | Y | Jul-20 | nan | 383.5 | R | 03 | 01-07-2020 | N | 18IPB06013580806 | 4d22ddd1d05d22cc4707a89dd80e76a271b99a7ba2610e3b111489fd4f7950fc | 1 | 0 | 29.25 | 18 | 325 | 29.25 | nan | | 5 | Y | 03A00P1Z7 | 10-Aug-20 | Y | Jul-20 | nan | 496.78 | R | 03 | 01-07-2020 | N | 18IPB06013580807 | 73e6e787493276151783d5ab1107bd0bac53780a5840964f7953bf3ba8a4efb0 | 1 | 0 | 37.89 | 18 | 421 | 37.89 | nan | | 6 | Y | 03A00P1Z7 | 10-Aug-20 | Y | Jul-20 | nan | 411.82 | R | 03 | 21-07-2020 | N | 18IPB07013893564 | 52ef0e7269de052c0353580cad5092ff1cc7a3c454318b2df1041a62a32f033f | 1 | 0 | 31.41 | 18 | 349 | 31.41 | nan | | 7 | Y | 03A00P1Z7 | 10-Aug-20 | Y | Jul-20 | nan | 411.82 | R | 03 | 21-07-2020 | N | 18IPB07013893565 | ab44c119f3db614dccfd3bc63c036eaca22a41c99e3e5090904e38aee056f4ac | 1 | 0 | 31.41 | 18 | 349 | 31.41 | nan | | 8 | Y | 03CAZD | 10-Aug-20 | Y | Jul-20 | nan | 162840 | R | 03 | 13-07-2020 | N | T/20-21/56 | 92e52e48e812bb0bb2e34d9e400248730fdc40363459d05c4e9d6ebb7fe6165d | 101 | 0 | 12420 | 18 | 138000 | 12420 | 0 | | 9 | Y | 03AAE | 22-Aug-20 | Y | Jul-20 | nan | 46556 | R | 03 | 30-07-2020 | N | S20/21-359 | 8138e35895114ae412e8256f3ce8382cdd8ae771f2780781085134618bb033c9 | 1801 | 0 | 3550.87 | 18 | 39454.2 | 3550.87 | 0 | | 10 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 8417.98 | R | 03 | 02-07-2020 | N | 0000030301011976 | 70d17e281b22541b3d41eb3269d057b73140c203771365a892dd496ffc756adb | 1 | 0 | 0 | 0 | 1024.84 | 0 | nan | | 11 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 8417.98 | R | 03 | 02-07-2020 | N | 0000030301011976 | 70d17e281b22541b3d41eb3269d057b73140c203771365a892dd496ffc756adb | 2 | 0 | 233.58 | 18 | 2595.37 | 233.58 | nan | | 12 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 8417.98 | R | 03 | 02-07-2020 | N | 0000030301011976 | 70d17e281b22541b3d41eb3269d057b73140c203771365a892dd496ffc756adb | 3 | 0 | 89.34 | 5 | 3573.99 | 89.34 | nan | | 13 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 8417.98 | R | 03 | 02-07-2020 | N | 0000030301011976 | 70d17e281b22541b3d41eb3269d057b73140c203771365a892dd496ffc756adb | 4 | 0 | 30.96 | 12 | 516.02 | 30.96 | nan | | 14 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 2824.88 | R | 03 | 06-07-2020 | N | 0000030301012348 | 2e7978264e42a74a70aa35d39ca6856f4dfb333e76935667a8de2733f888a1f1 | 1 | 0 | 116.46 | 18 | 1293.94 | 116.46 | nan | | 15 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 2824.88 | R | 03 | 06-07-2020 | N | 0000030301012348 | 2e7978264e42a74a70aa35d39ca6856f4dfb333e76935667a8de2733f888a1f1 | 2 | 0 | 37.27 | 12 | 621.18 | 37.27 | nan | | 16 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 2824.88 | R | 03 | 06-07-2020 | N | 0000030301012348 | 2e7978264e42a74a70aa35d39ca6856f4dfb333e76935667a8de2733f888a1f1 | 3 | 0 | 0 | 0 | 85.26 | 0 | nan | | 17 | Y | 03AAD1ZA | 11-Aug-20 | Y | Jul-20 | nan | 2824.88 | R | 03 | 06-07-2020 | N | 0000030301012348 | 2e7978264e42a74a70aa35d39ca6856f4dfb333e76935667a8de2733f888a1f1 | 4 | 0 | 12.31 | 5 | 492.42 | 12.31 | nan | | 18 | Y | 03AA1ZQ | 17-Aug-20 | Y | Jul-20 | nan | 39294 | R | 03 | 02-07-2020 | N | TI/20-21/43 | 69f7931986ad9274d9595ca5221e3ce82aa389d659e83376ff1ec34571057670 | 101 | 0 | 2997 | 18 | 33300 | 2997 | 0 | | 19 | Y | 03AGG3Z5 | 18-Aug-20 | Y | Jul-20 | 22-Jan-20 | 593583 | R | 03 | 31-07-2020 | N | 25 | 623dcb5b65e34be4d0453c1783915bb8e66684a2e33a3c8a547e38754c4f1af9 | 1 | 0 | 45273.3 | 18 | 503036 | 45273.3 | nan | | 20 | Y | 03AGG3Z5 | 18-Aug-20 | Y | Jul-20 | 22-Jan-20 | 601409 | R | 03 | 31-07-2020 | N | 26 | ef8b99f99fe090f0a2374d8d6c0b15c265740e6c6487ff68d510382ec21d8ce4 | 1 | 0 | 45870.2 | 18 | 509668 | 45870.2 | nan | | 21 | Y | 03AGG3Z5 | 18-Aug-20 | Y | Jul-20 | 22-Jan-20 | 767358 | R | 03 | 31-07-2020 | N | 27 | 9c1257eddeb8cdc7e6a832a3646969b71e49eeeb7d6742b26cfc6e0e3630438a | 1 | 0 | 58527.3 | 18 | 650303 | 58527.3 | nan | | 22 | Y | 03AGG3Z5 | 18-Aug-20 | Y | Jul-20 | 22-Jan-20 | 597886 | R | 03 | 31-07-2020 | N | 28 | 29fc1b28aedd1545e7ea0fd8b67b8332a83f1ac3f62af9398af2dfa26c9f1d90 | 1 | 0 | 45601.4 | 18 | 506683 | 45601.4 | nan | | 23 | Y | 03AA9 | 18-Aug-20 | Y | Jul-20 | nan | 41914 | R | 03 | 29-07-2020 | N | 2020-21/K-916 | d112ad384eb291d49509bdf4a005d509424fefee4caf3443bc9726cf41665295 | 1801 | 0 | 3196.8 | 18 | 35520 | 3196.8 | nan | | 24 | Y | 03A1Z8 | 12-Aug-20 | Y | Jul-20 | nan | 274893 | R | 03 | 20-07-2020 | N | T/20-21/10 | e5851fcc6b370714d7523080582a678a212f5dde90f5c2618880376018221f38 | 101 | 0 | 20966.4 | 18 | 232960 | 20966.4 | 0 | | 25 | Y | 03AD1ZL | 11-Aug-20 | Y | Jul-20 | nan | 125375 | R | 03 | 03-07-2020 | N | T/20-21/155 | 2bb398c7a0fedf11f1f1c1d196c43ad79910be52e6892f88915671025528eb2b | 101 | 0 | 9562.5 | 18 | 106250 | 9562.5 | 0 | | 26 | Y | 03AA3Z9 | 14-Aug-20 | Y | Jul-20 | nan | 529.99 | R | 03 | 31-07-2020 | N | 0301072000000650 | ad1e1d1572c9058fabd6d23fb5dc4b68f1a2a10d3dd3d7e73d73d3c502d92151 | 1 | nan | 40.42 | 18 | 449.15 | 40.42 | nan | | 27 | Y | 03AA3Z9 | 14-Aug-20 | Y | Jul-20 | nan | 1201 | R | 03 | 31-07-2020 | N | 0303072000000025 | 5a69229d907957c1d95eb464684891c202102b8589f5603b8ae14b07607f1655 | 1 | nan | 91.5 | 18 | 1018 | 91.5 | nan | | 28 | Y | 03AB1ZV | 11-Aug-20 | Y | Jul-20 | nan | 30976 | R | 03 | 10-07-2020 | N | 70 | 69bbeb088634a88b30c6e6046b63b1977f5534b2f676b984ef78f2c3bad8ca35 | 1800 | nan | 2362.5 | 18 | 26250 | 2362.5 | nan | | 29 | Y | 03AD1Z1 | 13-Aug-20 | Y | Jul-20 | nan | 8968 | R | 03 | 01-07-2020 | N | B25 | 5b98b819ca14a377c9304e7eab21957152c4819e82e37f2619fb2c547fb84ba6 | 1801 | 0 | 684 | 18 | 7600 | 684 | nan | | 30 | Y | 03AAO | 10-Aug-20 | Y | Jul-20 | nan | 38940 | R | 03 | 13-07-2020 | N | TI/20-21/30 | bae339e580c2ab9ffee90533650e4e2acdc47310230ed54aabbb96f89d3fc7c4 | 101 | 0 | 2970 | 18 | 33000 | 2970 | 0 | | 31 | Y | 07AH1ZU | 11-Aug-20 | Y | Jul-20 | nan | 13836.5 | R | 03 | 31-07-2020 | N | DELR/EXP/12176 | cb34f329adcd88c9e8794db9892fe47bd0a7afc0373a20860de046934f7923fa | 1 | 0 | nan | 18 | 11725.9 | nan | 2110.65 | | 32 | Y | 03A1ZT | 18-Aug-20 | Y | Jul-20 | nan | 41820 | R | 03 | 07-07-2020 | N | TI/20-21/68 | ad61c4dd8227b214dbe4bba24b57a2c976ce8438e53cf15b3530480116ca64da | 101 | 0 | 3189.69 | 18 | 35441 | 3189.69 | 0 | | 33 | Y | 03A1ZT | 18-Aug-20 | Y | Jul-20 | nan | 69773 | R | 03 | 10-07-2020 | N | TI/20-21/71 | 1deca4741b91716bfabc8b2ab826be76342b0fd3e698b128c927f4b426c064d0 | 101 | 0 | 5321.7 | 18 | 59130 | 5321.7 | 0 |
To "flat" a nested json file, you can use the following function: ``` def flatten_json(nested_json): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(nested_json) return out ``` Assuming your json is called `myjson`: ``` df = pd.Series(flatten_json(myjson)).to_frame() ```
17,369,212
I would like to know if there's a function similar to `map` but working for methods of an instance. To make it clear, I know that `map` works as: ``` map( function_name , elements ) # is the same thing as: [ function_name( element ) for element in elements ] ``` and now I'm looking for some kind of `map2` that does: ``` map2( elements , method_name ) # doing the same as: [ element.method_name() for element in elements ] ``` which I tried to create by myself doing: ``` def map2( elements , method_name ): return [ element.method_name() for element in elements ] ``` but it doesn't work, python says: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'method_name' is not defined ``` even though I'm sure the classes of the elements I'm working with have this method defined. Does anyone knows how could I proceed?
2013/06/28
[ "https://Stackoverflow.com/questions/17369212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2014276/" ]
[`operator.methodcaller()`](http://docs.python.org/2/library/operator.html#operator.methodcaller) will give you a function that you can use for this. ``` map(operator.methodcaller('method_name'), sequence) ```
You can use `lambda` expression. For example ``` a = ["Abc", "ddEEf", "gHI"] print map(lambda x:x.lower(), a) ``` You will find that all elements of `a` have been turned into lower case.
9,007,174
What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: ``` import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reader(infile) Data = namedtuple("Data", ", ".join(i for i in reader[0])) next(reader) for row in reader: data = Data(*row) ``` The reader object is not subscriptable, so the above code throws a `TypeError`. What is the pythonic way to reader a file header into a namedtuple?
2012/01/25
[ "https://Stackoverflow.com/questions/9007174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636493/" ]
Use: ``` Data = namedtuple("Data", next(reader)) ``` and omit the line: ``` next(reader) ``` Combining this with an iterative version based on martineau's comment below, the example becomes for Python 2 ``` import csv from collections import namedtuple from itertools import imap with open("data_file.txt", mode="rb") as infile: reader = csv.reader(infile) Data = namedtuple("Data", next(reader)) # get names from column headers for data in imap(Data._make, reader): print data.foo # ...further processing of a line... ``` and for Python 3 ``` import csv from collections import namedtuple with open("data_file.txt", newline="") as infile: reader = csv.reader(infile) Data = namedtuple("Data", next(reader)) # get names from column headers for data in map(Data._make, reader): print(data.foo) # ...further processing of a line... ```
Please have a look at [`csv.DictReader`](http://docs.python.org/library/csv.html#csv.DictReader). Basically, it provides the ability to get the column names from the first row as you're looking for and, after that, lets you access to each column in a row by name using a dictionary. If for some reason you still need to access the rows as a `collections.namedtuple`, it should be easy to transform the dictionaries to named tuples as follows: ``` with open('data_file.txt') as infile: reader = csv.DictReader(infile) Data = collections.namedtuple('Data', reader.fieldnames) tuples = [Data(**row) for row in reader] ```
9,007,174
What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: ``` import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reader(infile) Data = namedtuple("Data", ", ".join(i for i in reader[0])) next(reader) for row in reader: data = Data(*row) ``` The reader object is not subscriptable, so the above code throws a `TypeError`. What is the pythonic way to reader a file header into a namedtuple?
2012/01/25
[ "https://Stackoverflow.com/questions/9007174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636493/" ]
Use: ``` Data = namedtuple("Data", next(reader)) ``` and omit the line: ``` next(reader) ``` Combining this with an iterative version based on martineau's comment below, the example becomes for Python 2 ``` import csv from collections import namedtuple from itertools import imap with open("data_file.txt", mode="rb") as infile: reader = csv.reader(infile) Data = namedtuple("Data", next(reader)) # get names from column headers for data in imap(Data._make, reader): print data.foo # ...further processing of a line... ``` and for Python 3 ``` import csv from collections import namedtuple with open("data_file.txt", newline="") as infile: reader = csv.reader(infile) Data = namedtuple("Data", next(reader)) # get names from column headers for data in map(Data._make, reader): print(data.foo) # ...further processing of a line... ```
I'd suggest this approach: ``` import csv from collections import namedtuple with open("data.csv", 'r') as f: reader = csv.reader(f, delimiter=',') Row = namedtuple('Row', next(reader)) rows = [Row(*line) for line in reader] ``` If you work with Pandas, the solution becomes even more elegant: ``` import pandas as pd from collections import namedtuple data = pd.read_csv("data.csv") Row = namedtuple('Row', data.columns) rows = [Row(*row) for index, row in data.iterrows()] ``` In both cases you can interact with the records by field names: ``` for row in rows: print(row.foo) ```
9,007,174
What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: ``` import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reader(infile) Data = namedtuple("Data", ", ".join(i for i in reader[0])) next(reader) for row in reader: data = Data(*row) ``` The reader object is not subscriptable, so the above code throws a `TypeError`. What is the pythonic way to reader a file header into a namedtuple?
2012/01/25
[ "https://Stackoverflow.com/questions/9007174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636493/" ]
Please have a look at [`csv.DictReader`](http://docs.python.org/library/csv.html#csv.DictReader). Basically, it provides the ability to get the column names from the first row as you're looking for and, after that, lets you access to each column in a row by name using a dictionary. If for some reason you still need to access the rows as a `collections.namedtuple`, it should be easy to transform the dictionaries to named tuples as follows: ``` with open('data_file.txt') as infile: reader = csv.DictReader(infile) Data = collections.namedtuple('Data', reader.fieldnames) tuples = [Data(**row) for row in reader] ```
I'd suggest this approach: ``` import csv from collections import namedtuple with open("data.csv", 'r') as f: reader = csv.reader(f, delimiter=',') Row = namedtuple('Row', next(reader)) rows = [Row(*line) for line in reader] ``` If you work with Pandas, the solution becomes even more elegant: ``` import pandas as pd from collections import namedtuple data = pd.read_csv("data.csv") Row = namedtuple('Row', data.columns) rows = [Row(*row) for index, row in data.iterrows()] ``` In both cases you can interact with the records by field names: ``` for row in rows: print(row.foo) ```
31,813,457
I am trying to run a blat search from within my python code. Right now it's written as... ``` os.system('blat database.fa fastafile pslfile') ``` When I run the code, I specify file names for "fastafile" and "pslfile"... ``` python my_code.py -f new.fasta -p test.psl ``` This doesn't work as "fastafile" and "pslfile" are variables for files created and named when I run the code, but if I were to use the actual file names I would have to go back and change my code each time I run it. I'd like to use the command line arguments above to specify the files. How would I change this so that "fastafile" and "pslfile" will be replaced with my arguments (new.fasta and test.psl) each time?
2015/08/04
[ "https://Stackoverflow.com/questions/31813457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5025033/" ]
As it applies to agent-based releases: *Tools* are intended to provide a custom resource (executable, PowerShell script, batch file, and so on) with a command line to execute said custom resource, and a default set of command line parameters. Using an example from the built-in resources: IIS Manager. The IIS Manager is a tool that can perform a variety of different IIS actions, depending on how it is called. *Actions* are granular, release-specific actions. They may be built on top of a tool to provide a specific action that uses the tool. *Create Web Site* is an action built on top of the IIS Manager tool. Actions appear in the release template toolbox. *Components* are deployable chunks of software. You specify the relative source of the binaries from your build drop, and choose a tool to execute to install the software. Most common is the "XCopy Deployer" tool, which just copies the binaries from the build drop to a location on the target machine. Components can be added to the release template by right-clicking on "Components" and choosing the "Add" option. You can use actions or components directly within a release template, but not tools. So the relationship is this: ``` /-> Action -> Target server Tool -| \-> Component -> Build drop and target server ``` vNext releases do not have the concepts of actions or tools, only components. Components are reduced to serve only as pointers to the path relative to your build drop root where the binaries come from. There are some other distinctions, but those are the main ones.
I'm not sure that there is a universal definition that doesn't have exceptions, but I see it as: **Actions** - functionality that doesn't interact with a build eg starting or stopping a service (except for the Deploy using Chef or PS/DSC actions). Only used in Agent-based templates. **Tools** - functionality that interacts with a build and / or has a complex command line, eg deploying a website. Only used by **Components - Agent-based**. **Components - Agent-based** - users of tools and also the place where the location of the build is specified and where any token replacement is defined. When the component is used in a template the tool typically does something to the build eg the XCopy Deployer will copy the contents of 'Path to package' to the specified installation path. **Components - vNext** - only allow for specifying the location of the build and any token replacement since any work is done via a script. The component is 'consumed' by the **Deploy using Chef or PS/DSC** actions and is the way to tell these actions where to get the build. Now I've tried to explain this I can see what a muddle it is. At some point you will be able to bypass all this confusion since an all-new web-based version of Release Management will be available with TFS 2015 Update 1 (and earlier with Visual Studio Online). It might pay to hold off for this version if you can but it may be late this year or early next since TFS 2015 RTM isn't out yet. If you can't wait and need to get going now then go down the vNext PowerShell route to make for an easier transition to the web version.
28,314,742
Using the regex in python, I want to compile a string that gets the pattern "\1" up to "\9". I've tried ``` regex= re.compile("\\(\d)") #sre_constants.error: unbalanced parenthesis regex= re.compile("\\\(\d)") #gets \\4 but not \4 ``` but to no avail.. Any thoughts?
2015/02/04
[ "https://Stackoverflow.com/questions/28314742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383952/" ]
One more: `re.compile("\\\\(\\d)")`. Or, a better option, a raw string: `re.compile(r"\\(\d)")`. The reason is the fact that backslash has meaning in both a string and in a regexp. For example, in regexp, `\d` is "a digit"; so you can't just use `\` for a backslash, and backslash is thus `\\`. But in a normal string, `\"` is a quote, so a backslash needs to be `\\`. When you combine the two, the string `"\\\\(\\d)"` actually contains `\\(\d)`, which is a regexp that matches `\` and a digit. Raw strings avoid the problem up to a point by giving backslashes a different and much more restricted semantics.
You should use a [raw-string](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) (which does not process escape sequences): ``` regex= re.compile(r"\\(\d)") ```
28,314,742
Using the regex in python, I want to compile a string that gets the pattern "\1" up to "\9". I've tried ``` regex= re.compile("\\(\d)") #sre_constants.error: unbalanced parenthesis regex= re.compile("\\\(\d)") #gets \\4 but not \4 ``` but to no avail.. Any thoughts?
2015/02/04
[ "https://Stackoverflow.com/questions/28314742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383952/" ]
You should use a [raw-string](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) (which does not process escape sequences): ``` regex= re.compile(r"\\(\d)") ```
Use raw string: ``` regex= re.compile(r"\\(\d)") ```
28,314,742
Using the regex in python, I want to compile a string that gets the pattern "\1" up to "\9". I've tried ``` regex= re.compile("\\(\d)") #sre_constants.error: unbalanced parenthesis regex= re.compile("\\\(\d)") #gets \\4 but not \4 ``` but to no avail.. Any thoughts?
2015/02/04
[ "https://Stackoverflow.com/questions/28314742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383952/" ]
One more: `re.compile("\\\\(\\d)")`. Or, a better option, a raw string: `re.compile(r"\\(\d)")`. The reason is the fact that backslash has meaning in both a string and in a regexp. For example, in regexp, `\d` is "a digit"; so you can't just use `\` for a backslash, and backslash is thus `\\`. But in a normal string, `\"` is a quote, so a backslash needs to be `\\`. When you combine the two, the string `"\\\\(\\d)"` actually contains `\\(\d)`, which is a regexp that matches `\` and a digit. Raw strings avoid the problem up to a point by giving backslashes a different and much more restricted semantics.
Use raw string: ``` regex= re.compile(r"\\(\d)") ```
70,854,703
I have a bunch of .json files that I am trying to access. I need to calculate the growing season of a particular crop based on the planting and harvest dates. Problem: With the following code, I get this error: AttributeError: Can only use .dt accessor with datetimelike values Code: ``` import os import copy import json import math import numpy as np import pandas as pd import altair as alt def get_data_single(exp_file_name): # Read exp with open(exp_file_name) as f: data = json.load(f) n = len(data['RotationComponents']) out_vars = ['crop', 'plant_date', 'harv_date', 'CWAD_obs'] out = pd.DataFrame({'location': [exp_file_name.split('-')[0]] * n, 'crop': [np.nan] * n, 'plant_date': [np.nan] * n, 'harv_date': [np.nan] * n, 'ppop': [np.nan] * n, 'rowsp': [np.nan] * n}) for i in range(n): crop_id = data['RotationComponents'][i]['Planting']['Crop']['SpeciesID'] if crop_id == "CL": harvest_data = data['RotationComponents'][i]['Harvest'] out.loc[i, 'crop'] = crop_id out.loc[i, 'plant_date'] = pd.to_datetime(data['RotationComponents'][i]['Planting']['Date'],errors = 'coerce',format = '%Y-%m-%d') out.loc[i, 'ppop'] = data['RotationComponents'][i]['Planting']['Ppop'] out.loc[i, 'rowsp'] = data['RotationComponents'][i]['Planting']['RowSpc'] out.loc[i, 'harv_date'] = pd.to_datetime(harvest_data['EventDate']['Date'],errors = 'coerce',format = '%Y-%m-%d') return out ``` > > ``` data_files = ['IA_1.json', 'IA_2.json', 'IA_3.json', 'IA_4.json'] > obs_df = pd.concat([get_data_single(j) for j in data_files]).dropna() obs_df['plant_date'] = > pd.to_datetime(obs_df['plant_date']) obs_df['harv_date'] = > pd.to_datetime(obs_df['harv_date']) obs_df['plant_year'] = > obs_df['plant_date'].dt.strftime('%Y') > obs_df['harv_year'] = obs_df['harv_date'].dt.strftime('%Y') > obs_df['season'] = obs_df.apply(lambda x: x['plant_year'] + '_' + x['harv_year'], axis=1) > obs_df ``` I am trying to get the obs\_df to give the following based on the above code: ``` location crop plant_date harv_date ppop rowsp plant_year harv_year season ``` Traceback error: ``` AttributeError Traceback (most recent call last) /var/folders/ld/b6cy4j0d6pjb0t8d97rrgvbm0000gs/T/ipykernel_80477/757702288.py in <module> 1 data_files = ['IA_1.json', 'IA_2.json', 'IA_3.json', 'IA_4.json'] 2 obs_df = pd.concat([get_data_single(j) for j in data_files]).dropna() ----> 3 obs_df['plant_year'] = obs_df['plant_date'].dt.strftime('%Y') 4 obs_df['harv_year'] = obs_df['harv_date'].dt.strftime('%Y') 5 obs_df['season'] = obs_df.apply(lambda x: x['plant_year'] + '_' + x['harv_year'], axis=1) ~/miniconda3/lib/python3.9/site-packages/pandas/core/generic.py in __getattr__(self, name) 5485 ): 5486 return self[name] -> 5487 return object.__getattribute__(self, name) 5488 5489 def __setattr__(self, name: str, value) -> None: ~/miniconda3/lib/python3.9/site-packages/pandas/core/accessor.py in __get__(self, obj, cls) 179 # we're accessing the attribute of the class, i.e., Dataset.geo 180 return self._accessor --> 181 accessor_obj = self._accessor(obj) 182 # Replace the property with the accessor object. Inspired by: 183 # https://www.pydanny.com/cached-property.html ~/miniconda3/lib/python3.9/site-packages/pandas/core/indexes/accessors.py in __new__(cls, data) 504 return PeriodProperties(data, orig) 505 --> 506 raise AttributeError("Can only use .dt accessor with datetimelike values") AttributeError: Can only use .dt accessor with datetimelike values ``` Example json file > > Blockquote > > > ``` "SDate": "1999-05-26", "NYrs": 22, "SimControl": "N", "RotationComponents": [ { "Planting": { "Ppop": 250.00886969940453, "RowSpc": 25.0, "SDepth": 4.0, "Crop": { "SpeciesID": "RY", "CropParams": { "Name": "Rye", "RootC": 40.0, "RootN": 4.0, "RootP": 0.4, "RootSloC": 30.0, "RootIntC": 30.0, "RootSloN": 10.0, "VegC": 40.0, "VegSloC": 30.0, "VegIntC": 30.0, "VegSloN": 10.0, "KnDnFrac": 0.5, "VegN": 4.0, "VegP": 0.4, "Code": null }, "version": { "id": "global/crops/RY", "version": 1, "updateTime": "2020-09-29T00:00:00Z", "derivedFromId": null, "derivedFromVersion": null, "modelVersion": 1 }, "Name": null, "cultivarId": null, "CHeight": 1.0, "PhotoSyn": { "PhotSynID": "C3", "Points": [ { "CO2": 0.0, "Multiplier": 0.0 }, { "CO2": 220.0, "Multiplier": 0.71 }, { "CO2": 330.0, "Multiplier": 1.0 }, { "CO2": 440.0, "Multiplier": 1.08 }, { "CO2": 550.0, "Multiplier": 1.17 }, { "CO2": 660.0, "Multiplier": 1.25 }, { "CO2": 770.0, "Multiplier": 1.32 }, { "CO2": 880.0, "Multiplier": 1.38 }, { "CO2": 990.0, "Multiplier": 1.43 }, { "CO2": 9999.0, "Multiplier": 1.5 } ] }, "NitrogenFixing": null, "relTT_P1": 0.35, "relTT_P2": 0.62, "relTT_Fl": null, "relTT_Sn": 0.8, "relLAI_P1": 0.02, "relLAI_P2": 0.6, "PlntN_Em": 0.03616, "PlntN_Hf": 0.0288, "PlntN_Mt": 0.014, "GrnN_Mt": 0.023, "PlntP_Em": 0.004, "PlntP_Hf": 0.003, "PlntP_Mt": 0.0024, "GrnP_Mt": 0.0037, "LAImax": 3.0, "RUEmax": 1.5, "SnParLAI": 0.61, "SnParRUE": 1.0, "TbaseDev": 0.0, "ToptDev": 15.0, "TTtoGerm": 20.0, "TTtoMatr": 1200.0, "EmgInter": 15.0, "EmgSlope": 6.0, "HrvIndex": 0.03, "Kf2": null, "MaturityGroup": null, "Source": "ALMANAC (ABRVCROP.DAT) modified through calibration", "LT50C": -28.0 }, "Date": "1999-11-23", "VariableRateSeeding": false, "Area": null }, ```
2022/01/25
[ "https://Stackoverflow.com/questions/70854703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10609402/" ]
``` >>> df plant_date 0 NaN 1 2021-11-12 >>> df.loc[1, 'plant_date'] = pd.to_datetime(df.loc[1, 'plant_date'], errors='coerce', format='%Y-%m-%d') >>> df plant_date 0 NaN 1 2021-11-12 00:00:00 ``` Due to how you're creating your dataframe - it being prepopulated with `np.nan` and converting individial "rows" to datetime - the "type" of the column will be `object` (because `nan` is of type float - so the column contains "mixed types") ``` >>> df.dtypes plant_date object --------------^^^^^^ dtype: object >>> df['plant_date'].dt AttributeError: Can only use .dt accessor with datetimelike values ``` In order to use `.dt` you need the column to be of type datetime ``` >>> df plant_date 0 NaN 1 2021-11-12 >>> df.dtypes plant_date object dtype: object ``` The simplest way is probably just to call `to_datetime()` on the whole column at once - either on `out` in your function - or on `obs_df` after you create it. ``` >>> df['plant_date'] = pd.to_datetime(df['plant_date']) >>> df plant_date 0 NaT 1 2021-11-12 >>> df.dtypes plant_date datetime64[ns] dtype: object ``` Now you can use `.dt` without error ``` >>> df['plant_date'].dt <pandas.core.indexes.accessors.DatetimeProperties object at 0x1210fe160> ``` The `harv_date` column should have the same issue.
I was able to make it work. Here is the updated code. Right after pd.concat, the following code helped: ``` obs_df['plant_date'] = pd.to_datetime(obs_df['plant_date']) obs_df['harvest_date'] = pd.to_datetime(obs_df['harvest_date']) ```
33,579,522
I am a new python user and I am quite interesting on understanding in depth how works the NumPy module. I am writing on a function able to use both masked and unmasked arrays as data input. I have noticed that there are several [numpy masked operations](http://docs.scipy.org/doc/numpy/reference/routines.ma.html) that look similar (and even work?) to its normal (unmasked) counterpart. One of such functions is `numpy.zeros` and `numpy.ma.zeros`. Could someone else tell me the advantage of, say, creating an array using `numpy.ma.zeros` vs. `numpy.zeros`? It makes an actual difference when you are using masked arrays? I have noticed that when I use `numpy.zeros_like` it works fine for both creating a masked or unmasked array.
2015/11/07
[ "https://Stackoverflow.com/questions/33579522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5373784/" ]
`np.ma.zeros` creates a masked array rather than a normal array which could be useful if some later operation on this array creates invalid values. An example from the manual: > > Arrays sometimes contain invalid or missing data. When doing > operations on such arrays, we wish to suppress invalid values, which > is the purpose masked arrays fulfill (an example of typical use is > given below). > > > For example, examine the following array: > > > > ``` > >>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan]) > > ``` > > When we try to calculate the mean of the data, the result is > undetermined: > > > > ``` > >>> np.mean(x) nan > > ``` > > The mean is calculated using roughly `np.sum(x)/len(x)`, but since > any number added to `NaN` produces `NaN`, this doesn't work. > Enter masked arrays: > > > > ``` > >>> m = np.ma.masked_array(x, np.isnan(x)) > >>> m > masked_array(data = [2.0 1.0 3.0 -- 5.0 2.0 3.0 --], > mask = [False False False True False False False True], > fill_value=1e+20) > > ``` > > Here, we construct a masked array that suppress all `NaN` values. > We may now proceed to calculate the mean of the other values: > > > > ``` > >>> np.mean(m) > 2.6666666666666665 > > ``` > >
As a beginner don't get too bogged down with masked arrays. It's a subclass of `np.ndarray`, that is useful when dealing with data that has some bad values that you'd like to ignored when calculating things like the mean. But otherwise you should focus on creation and indexing (and calculations) with the base numpy class. Not only is `ma` array a subclass, it contains 2 regular arrays. One has the data, including any 'bad' values. That is a regular numpy array. The other is a boolean array, the mask. The developers of the masked class tried to make it behave in the same ways as the regular arrays, but with this added masking. Most, if not all, of the added features of masked arrays are implemented in Python code. It is hard to understand the underlying C code for `numpy`, but it is instructive to look at the functions and methods that are implemented in Python. I often look at those in an `ipython` session, but they can also be studied on the numpy github repository.
17,497,860
I am trying to download an entire play list for Android development tutorial from Youtube. So I used [savefrom](http://en.savefrom.net/) for generating playlist for download. But the problem is that I have so many videos in that playlist. So, I decided to write a python script for making this work simpler. But the problem is it uses Java Script to generate the link so I cant able to fetch generated link using javascript() Example: <http://ssyoutube.com/watch?v=AfleuRtrJoA> It takes 5 sec to generate download links. I want to get page source only after 5 sec **from the browse**. For this kind of work I found a good package named [selenium](https://pypi.python.org/pypi/selenium). ``` import time from selenium import webdriver def savefromnotnet(url): browser = webdriver.Firefox() # Get local session of firefox browser.get(url) # Load page time.sleep(5) # Let the page load, will be added to the API return browser.page_source() source = savefromnotnet("http://ssyoutube.com/watch?v=AfleuRtrJoA") ``` The `savefromnotnet` function open's Firefox and it will request the url, up to this every thing works fine. But when I want to get page source `browser.page_source()` it shows the following error. ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 523, in runfile execfile(filename, namespace) File "C:\Users\BK\Desktop\Working Folder\Python Temp\temp.py", line 10, in <module> source = savefromnotnet("http://ssyoutube.com/watch?v=AfleuRtrJoA") File "C:\Users\BK\Desktop\Working Folder\Python Temp\temp.py", line 8, in savefromnotnet return browser.page_source() TypeError: 'unicode' object is not callable ```
2013/07/05
[ "https://Stackoverflow.com/questions/17497860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1464519/" ]
Error occured on following line. ``` return browser.page_source() ``` I think brackets did not need. ``` return browser.page_source ```
I think not ! ``` pcode = wdriver.page_source() ``` is absoluteley right call. By auto-complete in python ide. I have the same problem. Looks like we need to encode page-sourse text variable in somethind like classic ANSI
73,099,677
Could you help me? I'm trying to close my main window and then create a new window. I'm using withdraw() instead of destroy() since I'm planning to use that widget later. Here is my code, but I just get: `tkinter.TclError: image "pyimage10" doesn't exist` I separated the codes of the main window and a new window into two python file, which are "Page1" and "Page2". Sorry for my rough English. Any help to fix this would be much appreciated:) `tkinter.TclError: image "pyimage10" doesn't exist`seems to occur at `image_2 = canvas.create_image(` Page1 ``` from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage    OUTPUT_PATH = Path(__file__).parent    ASSETS_PATH = OUTPUT_PATH / Path("./assets")    def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path)    window = Tk()    window.geometry("703x981")    window.configure(bg = "#FFFFFF") button_image_6 = PhotoImage( file=relative_to_assets("button_6.png")) button_6 = Button( image=button_image_6, borderwidth=0, highlightthickness=0, command=lambda: ("WM_DELETE_WINDOW", nextPage()), relief="flat" ) button_6.place( x=415.0, y=793.0, width=86.0, height=78.0 ) def nextPage(): window.withdraw() import Page2 ``` Page2 ``` from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage window = Tk() def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path) window.geometry("545x470") window.configure(bg = "#FFFFFF") window.title('PythonGuides') canvas = Canvas( window, bg = "#FFFFFF", height = 470, width = 545, bd = 0, highlightthickness = 0, relief = "ridge" ) canvas.place(x = 0, y = 0) image_image_2 = PhotoImage( file=relative_to_assets("image_2.png")) image_2 = canvas.create_image( 272.0, 175.0, image=image_image_2 ) ```
2022/07/24
[ "https://Stackoverflow.com/questions/73099677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14257622/" ]
::with('trans') returns completely new query and forgets everything about your ::find($id)
What happens is, `House::find($id)` is a method that returns the element by its primary key. Then, the `::with('trans')` gets the result, sees the House class and starts creating a new query builder for the Model. Finally, the `->get()` runs this new query and the end result is what is return for the `$house` value. You have two options that will result to what you want to do. First one is, to find the house entry and then load its relation ``` $house = House::find($id); $house->load('trans'); ``` The second option is this: ``` $house = House::where('id',$id)->with('trans')->first(); ``` The second one is a query builder that results to the first element with id = $id, and load its relation with translations. You can check for more details in the [laravel documentation](https://laravel.com/docs/9.x/eloquent#collections). They have a very well-written documentation and the examples help a lot.
73,099,677
Could you help me? I'm trying to close my main window and then create a new window. I'm using withdraw() instead of destroy() since I'm planning to use that widget later. Here is my code, but I just get: `tkinter.TclError: image "pyimage10" doesn't exist` I separated the codes of the main window and a new window into two python file, which are "Page1" and "Page2". Sorry for my rough English. Any help to fix this would be much appreciated:) `tkinter.TclError: image "pyimage10" doesn't exist`seems to occur at `image_2 = canvas.create_image(` Page1 ``` from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage    OUTPUT_PATH = Path(__file__).parent    ASSETS_PATH = OUTPUT_PATH / Path("./assets")    def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path)    window = Tk()    window.geometry("703x981")    window.configure(bg = "#FFFFFF") button_image_6 = PhotoImage( file=relative_to_assets("button_6.png")) button_6 = Button( image=button_image_6, borderwidth=0, highlightthickness=0, command=lambda: ("WM_DELETE_WINDOW", nextPage()), relief="flat" ) button_6.place( x=415.0, y=793.0, width=86.0, height=78.0 ) def nextPage(): window.withdraw() import Page2 ``` Page2 ``` from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage window = Tk() def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path) window.geometry("545x470") window.configure(bg = "#FFFFFF") window.title('PythonGuides') canvas = Canvas( window, bg = "#FFFFFF", height = 470, width = 545, bd = 0, highlightthickness = 0, relief = "ridge" ) canvas.place(x = 0, y = 0) image_image_2 = PhotoImage( file=relative_to_assets("image_2.png")) image_2 = canvas.create_image( 272.0, 175.0, image=image_image_2 ) ```
2022/07/24
[ "https://Stackoverflow.com/questions/73099677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14257622/" ]
you need to use load method. ``` $house = House::find($id); $house->load('trans'); ```
What happens is, `House::find($id)` is a method that returns the element by its primary key. Then, the `::with('trans')` gets the result, sees the House class and starts creating a new query builder for the Model. Finally, the `->get()` runs this new query and the end result is what is return for the `$house` value. You have two options that will result to what you want to do. First one is, to find the house entry and then load its relation ``` $house = House::find($id); $house->load('trans'); ``` The second option is this: ``` $house = House::where('id',$id)->with('trans')->first(); ``` The second one is a query builder that results to the first element with id = $id, and load its relation with translations. You can check for more details in the [laravel documentation](https://laravel.com/docs/9.x/eloquent#collections). They have a very well-written documentation and the examples help a lot.
67,353,503
i'm new to python and i'm trying to parse a list in `["+",1,3,3]` and then identify it's string operator `"+" "-" "x" "/"` and convert it into a question `{"qns": "1 + 3 + 3", "ans": 7}` and answer into a dictionary with just two key "qns and "ans" So the question is there is a nested list as an input to the function. I'm supposed to convert each of the list to a dictionary output. The lists are identified by it's first string index "+" "-" "x" "/" and based on these strings, i'm to output a dictionary based on its input with two keys, first is "qns" which is formatted according to its operator "+" -> 1 + 3 + 3 and "ans" -> 7 hence combining both into a dictionary which shows {"qns": "1 + 3 + 3", "ans": 7} So far i'm only able to come up with this and i'm getting an error when i'm trying to parse in a smaller list `["x",3,2]` instead of `["+",1,3,3]` Is there a better way to do this instead of an if-else statement? ``` def math_qns(input): new_list = [] for x in input: if x[0] == "+": if x[3]: math = x[1] + x[2] + x[3] str_math = "{1} {0} {2} {0} {3}".format(x[0], x[1], x[2], x[3]) else: math = x[1] + x[2] str_math = "{1} {0} {2}".format(x[0], x[1], x[2]) if x[0] == "-": if x[3]: math = x[1] - x[2] - x[3] str_math = "{1} {0} {2} {0} {3}".format(x[0], x[1], x[2], x[3]) else: math = x[1] - x[2] str_math = "{1} {0} {2}".format(x[0], x[1], x[2]) if x[0] == "x": if x[3]: math = x[1] * x[2] * x[3] str_math = "{1} {0} {2} {0} {3}".format(x[0], x[1], x[2], x[3]) else: math = x[1] * x[2] str_math = "{1} {0} {2}".format(x[0], x[1], x[2]) if x[0] == "/": if x[3]: math = x[1] / x[2] / x[3] str_math = "{1} {0} {2} {0} {3}".format(x[0], x[1], x[2], x[3]) else: math = x[1] / x[2] str_math = "{1} {0} {2}".format(x[0], x[1], x[2]) qnsans = { "qns" : str_math, "ans" : math } new_list.append(qnsans) return print(new_list) def main(): input_list = [["+",1,3,3], ["-",2,5,-1], ["x",3,2],["/",12,3,2],["x",0,23],["+",1,2,3,4]] math_qns(input_list) ``` Ideally the outcome would be : ``` [{"qns": "1 + 3 + 3", "ans": 7}, {"qns": "2 - 5 - -1", "ans": -2}, {"qns": "3 x 2", "ans": 6}, {"qns": "12 / 3 / 2", "ans": 2}, {"qns": "0 x 23", "ans": 0}, {"qns": "1 + 2 + 3 + 4", "ans": 10}] ``` So far i've been getting an error ``` if x[3]: IndexError: list index out of range ``` Would be thankful for any advice as i've been stuck for quite some time over this trying to come up with a new way to make it more efficient and at the same time accomplish its objective.
2021/05/02
[ "https://Stackoverflow.com/questions/67353503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12929490/" ]
A variable of type `dynamic` would be similar to javascript where it can change type during runtime. For example store an integer then change to a string. `var` is not the same as dynamic. `var` is an easy way to initialise variables as you don't have to explicitly state the type. Dart just infers the type to make it easier for you. If you write `int number = 5` it would be the same as `var number = 5` as dart would infer that this variable is an integer. The reason the tutorial might have said that `var` is better than `int` may be convention to make the code more readable but I believe it doesn't have any impact on your code. You can use either and it won't make a difference.
the reason I think var is better is that it is slightly more convenience, for example ```dart var n = 1; int m = 1; ``` both `n` and `m` are integer if some day you changed your mind and want to reinitialize them with new decimal number instead ```dart var n = 9.9; double m = 9.9; ``` in this case, var requires less typing and still able to infer the type correctly
57,948,794
I have made a Python application which uses GTK. I want to send the user a dialog asking for confirmation for an action, however after creating the dialog based on [this](https://python-gtk-3-tutorial.readthedocs.io/en/latest/dialogs.html) tutorial, I noticed that there is no apparent way to center-align the 'Cancel' and 'OK' buttons. The relavent code from that tutorial is as follows: ```py class DialogExample(Gtk.Dialog): def __init__(self, parent): Gtk.Dialog.__init__(self, "My Dialog", parent, 0, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) self.set_default_size(150, 100) label = Gtk.Label("This is a dialog to display additional information") box = self.get_content_area() box.add(label) self.show_all() ``` In the example above, the buttons are aligned to the right. Is there any way to center align the buttons using this method of creating dialogs?
2019/09/15
[ "https://Stackoverflow.com/questions/57948794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116713/" ]
> > **Question**: Aligning dialog buttons to center > > > --- * [Gtk.Dialog.get\_action\_area](http://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Dialog.html#Gtk.Dialog.get_action_area) * [Gtk.Widget.props.parent](http://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Widget.html#Gtk.Widget.props.parent) * [Gtk.Box.set\_child\_packing](http://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Box.html#Gtk.Box.set_child_packing) * [Gtk.Box.set\_center\_widget](http://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Box.html#Gtk.Box.set_center_widget) --- 1. You want to *center* the `action_area` of a `Gtk.Dialog`, which is of type `Gtk.ButtonBox`. Get the `action_area` > > **Note**: Deprecated since version 3.12: Direct access to the action area is discouraged > > > ``` a_area = self.get_action_area() ``` 2. You need the `parent` of the `action_area`, which is of type `Gtk.Box` Get the `parent` box. ``` box = a_area.props.parent ``` 3. To *center* a `Gtk.Widget` you have to reset the default `packing` `expand=False` to `True`. To all other `packing` options no change. ``` box.set_child_packing(a_area, True, False, 0, Gtk.PackType.END) ``` 4. Now, you can *center* the `action_area` ``` a_area.set_center_widget(None) ``` --- > > **Output**: > > > [![enter image description here](https://i.stack.imgur.com/aEkC7.png)](https://i.stack.imgur.com/aEkC7.png) ***Tested with Python: 3.5 - gi.\_\_version\_\_: 3.22.0***
I don't know if this is a cheaty way of doing it but it seems to work. ``` action_area= self.get_action_area() action_area.set_halign(3) ```
25,849,850
In python 3.4.0, using `json.dumps()` throws me a TypeError in one case but works like a charm in other case (which I think is equivalent to the first one). I have a dict where keys are strings and values are numbers and other dicts (i.e. something like `{'x': 1.234, 'y': -5.678, 'z': {'a': 4, 'b': 0, 'c': -6}}`). This fails (the stacktrace is not from this particular code snippet but from my larger script which I won't paste here but it is essentialy the same): ``` >>> x = dict(foo()) # obtain the data and make a new dict of it to really be sure >>> import json >>> json.dumps(x) Traceback (most recent call last): File "/mnt/data/gandalv/progs/pycharm-3.4/helpers/pydev/pydevd.py", line 1733, in <module> debugger.run(setup['file'], None, None) File "/mnt/data/gandalv/progs/pycharm-3.4/helpers/pydev/pydevd.py", line 1226, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/mnt/data/gandalv/progs/pycharm-3.4/helpers/pydev/_pydev_execfile.py", line 38, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script File "/mnt/data/gandalv/School/PhD/Other work/Krachy/code/recalculate.py", line 54, in <module> ls[1] = json.dumps(f) File "/usr/lib/python3.4/json/__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "/usr/lib/python3.4/json/encoder.py", line 192, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.4/json/encoder.py", line 173, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: 306 is not JSON serializable ``` The `306` is one of the values in one of ther inner dicts in `x`. It is not always the same number, sometimes it is a different number contained in the dict, apparently because of the unorderedness of a dict. However, this works like a charm: ``` >>> x = foo() # obtain the data and make a new dict of it to really be sure >>> import ast >>> import json >>> x2 = ast.literal_eval(repr(x)) >>> x == x2 True >>> json.dumps(x2) "{...}" # the json representation of dict as it should be ``` Could anyone, please, tell me why does this happen or what could be the cause? The most confusing part is that those two dicts (the original one and the one obtained through evaluation of the representation of the original one) are equal but the `dumps()` function behaves differently for each of them.
2014/09/15
[ "https://Stackoverflow.com/questions/25849850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/461202/" ]
The cause was that the numbers inside the `dict` were not ordinary python `int`s but `numpy.in64`s which are apparently not supported by the json encoder.
As you have seen, numpy int64 data types are not serializable into json directly: ``` >>> import numpy as np >>> import json >>> a=np.zeros(3, dtype=np.int64) >>> a[0]=-9223372036854775808 >>> a[2]=9223372036854775807 >>> jstr=json.dumps(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 192, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 250, in iterencode return _iterencode(o, 0) File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 173, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: array([-9223372036854775808, 0, 9223372036854775807]) is not JSON serializable ``` However, Python integers -- including longer integers -- can be serialized and deserialized: ``` >>> json.loads(json.dumps(2**123))==2**123 True ``` So with numpy, you can convert directly to Python data structures then serialize: ``` >>> jstr=json.dumps(a.tolist()) >>> b=np.array(json.loads(jstr)) >>> np.array_equal(a,b) True ```
24,690,298
Python matplotlib gives very nice figures. How to call python matplotlib in Qt C++ project? I'd like to put those figures in Qt dialogs and data are transferred via memory.
2014/07/11
[ "https://Stackoverflow.com/questions/24690298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1899020/" ]
You can create a python script with function calls to matplotlib and add them as callback functions in your C++ code. [This tutorial](http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I) explains how this can be done. I also recommend reading the documentation on [Python.h](https://docs.python.org/2/extending/extending.html).
I would try using [matplotlib-cpp](https://github.com/lava/matplotlib-cpp). It is built to resemble the plotting API used by Matlab and matplotlib. Basically it is a C++ wrapper around matplotlib and it's header only. Keep in mind though that it does not provide all the matplotlib features from python. Here is the initial example from GitHub: ``` #include "matplotlibcpp.h" namespace plt = matplotlibcpp; int main() { plt::plot({1,3,2,4}); plt::show(); } ``` Compile ``` g++ minimal.cpp -std=c++11 -I/usr/include/python2.7 -lpython2.7 ``` [![Plot of the minimal example](https://i.stack.imgur.com/d5NqD.png)](https://i.stack.imgur.com/d5NqD.png)
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import json data = json.loads(...) ``` My question is: How can I check *at runtime* that `data` has the correct type to be used as an argument to `myfun()` before using it as an argument for `myfun()`? ``` if not isCorrectType(data, ArgType): raise TypeError("data is not correct type") else: myfun(data) ```
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
It's awkward that there's no built-in function for this but [`typeguard`](https://pypi.org/project/typeguard/) comes with a convenient `check_type()` function: ``` >>> from typeguard import check_type >>> from typing import List >>> check_type("foo", [1,2,"3"], List[int]) Traceback (most recent call last): ... TypeError: type of foo[2] must be int; got str instead type of foo[2] must be int; got str instead ``` For more see: <https://typeguard.readthedocs.io/en/latest/api.html#typeguard.check_type>
The common way to handle this is by making use of the fact that if whatever object you pass to `myfun` doesn't have the required functionality a corresponding exception will be raised (usually `TypeError` or `AttributeError`). So you would do the following: ``` try: myfun(data) except (TypeError, AttributeError) as err: # Fallback for invalid types here. ``` You indicate in your question that you would raise a `TypeError` if the passed object does not have the appropriate structure but Python does this already for you. The critical question is how you would handle this case. You could also move the `try / except` block into `myfun`, if appropriate. When it comes to typing in Python you usually rely on [duck typing](https://en.wikipedia.org/wiki/Duck_typing): if the object has the required functionality then you don't care much about what type it is, as long as it serves the purpose. Consider the following example. We just pass the data into the function and then get the `AttributeError` for free (which we can then except); no need for manual type checking: ``` >>> def myfun(data): ... for x in data: ... print(x.items()) ... >>> data = json.loads('[[["a", 1], ["b", 2]], [["c", 3], ["d", 4]]]') >>> myfun(data) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in myfun AttributeError: 'list' object has no attribute 'items' ``` In case you are concerned about the usefulness of the resulting error, you could still except and then re-raise a custom exception (or even change the exception's message): ``` try: myfun(data) except (TypeError, AttributeError) as err: raise TypeError('Data has incorrect structure') from err try: myfun(data) except (TypeError, AttributeError) as err: err.args = ('Data has incorrect structure',) raise ``` When using third-party code one should always check the documentation for exceptions that will be raised. For example [`numpy.inner`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.inner.html) reports that it will raise a `ValueError` under certain circumstances. When using that function we don't need to perform any checks ourselves but rely on the fact that it will raise the error if needed. When using third-party code for which it is not clear how it will behave in some corner-cases, i.m.o. it is easier and clearer to just hardcode a corresponding type checker (see below) instead of using a generic solution that works for any type. These cases should be rare anyway and leaving a corresponding comment makes your fellow developers aware of the situation. The `typing` library is for type-hinting and as such it won't be checking the types at runtime. Sure you could do this manually but it is rather cumbersome: ``` def type_checker(data): return ( isinstance(data, list) and all(isinstance(x, dict) for x in list) and all(isinstance(k, str) and isinstance(v, int) for x in list for k, v in x.items()) ) ``` This together with an appropriate comment is still an acceptable solution and it is reusable where a similar data structure is expected. The intent is clear and the code is easily verifiable.