text
stringlengths
226
34.5k
Python get JSON object by index Question: I have a JSON file that looks something like this: { data: { 123: { 212: { 343: In python I load the JSON using json.loads(r.text). The strings inside the data object are not guaranteed to be those but can be any number. What I want to be able to do is to be able to get those numbers so I can store then in an array. In this example I want the array to look like [123,212,343]. Is there anyway to do this since they are nested objects and not a JSON array? Thanks Answer: Very briefly: #!/usr/bin/env python import json foo = json.loads('{"123": null, "234": null, "456": null}') print map(int, foo.keys()) The list `foo.keys()` will not be in the same order as presented in the JSON object (or its string representation). If you need to preserve ordering, you might try the following modification: #!/usr/bin/env python import json, collections foo = json.loads('{"123": null, "234": null, "456": null}', object_pairs_hook=collections.OrderedDict) print map(int, foo.keys()) As you iterate over the list of keys, you can do a reverse lookup on an individual key in the usual way. Note that you will likely want to convert the integer-key back to a Python string with `str()`, in order to retrieve its associated value. If you just want the list of keys for lookups, however, and you don't really need the actual integer values, you can skip the initial `map` call and just preserve the keys as strings.
PyOpenCL | Fail to launch a Kernel Question: When I'm using PyOpenCL to run the kernel "SIMPLE_JOIN" it fails. **HEADER OF THE KERNEL IN .CL FILE** void SIMPLE_JOIN(__global const int* a, int a_col, __global const int* a_valuesPic, __global const int* b, int b_col, __global const int* b_valuesPic, __global const int* join_valuesPic, __global int* current, const int maxVars, __global int* buffer, int joinVar) **THE EXECUTION IN PyOpenCL** program.SIMPLE_JOIN(context, (a_col, b_col), None, \ buffer_a, np.int32(a_col), buffer_a_valPic, \ buffer_b, np.int32(b_col), buffer_b_valPic, \ buffer_join_valPic, buffer_current, np.int32(maxVars), \ buffer_result, np.int32(joinList[0])) **THE ERROR IN THE COMMAND LINE** Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.2\helpers\pydev\pydevd.py", line 2199, in <module> globals = debugger.run(setup['file'], None, None) File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.2\helpers\pydev\pydevd.py", line 1638, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:/Users/��/Documents/��������/GAP+/gapQueryTree.py", line 213, in <module> res1_array, res1_ValsPic = gpu.gpu_join(p[0], p1_ValsPic, friend[0], friend1_ValsPic) File "C:/Users/��/Documents/��������/GAP+\gapPyOpenCl.py", line 107, in gpu_join buffer_result, np.int32(joinList[0])) File "C:\Python27\lib\site-packages\pyopencl\__init__.py", line 515, in kernel_call global_offset, wait_for, g_times_l=g_times_l) Boost.Python.ArgumentError: Python argument types in pyopencl._cl.enqueue_nd_range_kernel(Context, Kernel, tuple, NoneType, NoneType, NoneType) did not match C++ signature: enqueue_nd_range_kernel(class pyopencl::command_queue {lvalue} queue, class pyopencl::kernel {lvalue} kernel, class boost::python::api::object global_work_size, class boost::python::api::object local_work_size, class boost::python::api::object global_work_offset=None, class boost::python::api::object wait_for=None, bool g_times_l=False) Process finished with exit code -1 Answer: The first argument to your kernel invocation should be the command queue, not the context: `program.SIMPLE_JOIN(`**`queue`**`, (a_col, b_col), None, \...`
Why isn't the file lock released on close() if I launch a process while the file is locked? Question: If I open a file, acquire a lock, then close the file: import fcntl file = open("some_file", "w") fcntl.flock(file.fileno(), fcntl.LOCK_EX) file.close() The file lock is released immediately when the file is closed, which is what I would expect. However, if I launch a background process while the file is locked: import fcntl import subprocess file = open("some_file", "w") fcntl.flock(file.fileno(), fcntl.LOCK_EX) subprocess.Popen(["python", "-c", "import time; time.sleep(10.0)"]) file.close() The above code exits immediately, but the file lock is not released until the background process has finished. If I run the above code and then immediately run it a second time, the second instance blocks for ten seconds. Why isn't the lock released? I know I can explicitly release the lock by calling flock() with LOCK_UN, but that's not what I'm asking. My question is, why does launching a background process prevent close() from releasing the file lock? Answer: The child process inherits file descriptors from the parent. And the "locking" might be shared for the same file between different OS processes (that is the point of the locking). You could specify `close_fds=True` to close the file in the child too. `close_fds=True` is the default on POSIX systems in Python 3. Newly created file descriptors are non-inheritable by default since Python 3.4. See [PEP 446](https://docs.python.org/3/whatsnew/3.4.html#whatsnew- pep-446).
Python Dataframe new column based on conditional statement Question: I have a dataframe consisting of a few columns of custom calculations for a trading strategy. I want to add a new column called 'Signals' to this dataframe, consisting of 0s and 1s (long only strategy). The signals will be generated on the following code, each item in this code is a separate column in the dataframe: if: open_price > low_sigma.shift(1) and high_price > high_sigma.shift(1): signal = 1 else: signal = 0 From my understanding, if statements are not efficient for dataframes. In addition, I haven't been able to get this to output as desired. How do you recommend I generate the signal and add it to the dataframe? Answer: You could assign `df['Signals']` to the boolean condition itself, then use `astype` to convert the booleans to 0s and 1s: df['Signals'] = (((df['open_price'] > df['low_sigma'].shift(1)) & (df['high_price'] > df['high_sigma'].shift(1))) .astype('int')) for example, import pandas as pd df = pd.DataFrame({ 'open_price': [1,2,3,4], 'low_sigma': [1,3,2,4], 'high_price': [10,20,30,40], 'high_sigma': [10,40,20,30]}) # high_price high_sigma low_sigma open_price # 0 10 10 1 1 # 1 20 40 3 2 # 2 30 20 2 3 # 3 40 30 4 4 mask = ((df['open_price'] > df['low_sigma'].shift(1)) & (df['high_price'] > df['high_sigma'].shift(1))) # 0 False # 1 True # 2 False # 3 True # dtype: bool df['Signals'] = mask.astype('int') print(df) yields high_price high_sigma low_sigma open_price Signals 0 10 10 1 1 0 1 20 40 3 2 1 2 30 20 2 3 0 3 40 30 4 4 1
how to make a variable take a html link without formatting in python? Question: I need to take a url input and use it in subprocess.call().how is it possible? I wanted to write a loop so that it keeps on downloading images until required by doing this for i in range(1,tot): subprocess.call(["wget","http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_%02d.jpg"%num]) to automate this further. is there any way so that the user gives input like `http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_%02d.jpg` and I can directly insert the variable into subprocess.call(). I Tried the following urlin=raw_input("input the url: ") for i in range(1,tot): subprocess.call(["wget",urlin\"%num"]) but it is not working.how to make it work.Hope you understood my problem.. Answer: You are declaring `i` as the iterator for your loop but you use an undeclared `num`. Here is what I came up with (working on my computer): import subprocess numberImages = 3 urlin=raw_input("input the url: ") for i in range(1,numberImages+1): print urlin%i subprocess.call(["wget",urlin%i]) used `http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_%02d.jpg`as raw_input here is my output: input the url: http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_%02d.jpg http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_01.jpg #Some wget download debug http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_02.jpg #Some wget download debug http://z.mfcdn.net/store/manga/10543/01-003.0/compressed/beelzebub_3.beelzebub_ch003_03.jpg #Some wget download debug
Splitting an integer in python Question: I'm new to python and trying to build a 10k running calculator from the exercises in "Think Python" what I'm trying to do is break down the input time ie:43.12 into 2 separate numbers ... then perform (43x60)- which gives the seconds and then add the remaining seconds +12 .. to give the accurate number to work from .. below is running it if i hardcode 4312 in as a whole number - but what id like to to accept it dynamically ... can somebody help point me in the right direction #python 10k calculator import time distance = 6.211180124223602 time = float(input("what was your time?")) tenK = 10 mile = 1.61 minute = 60 sph = 0 def convertToMiles(): global distance distance = tenK / mile convertToMiles() print("Distance equal to :",distance) def splitInput(): test = [int(char) for char in str(4312)] print(test) splitInput() Answer: It's easier if you don't immediately call convert the user input to a `float`. Strings provide a `split` function, floats don't. >>> time = input("what was your time? ") what was your time? 42.12 >>> time= time.split('.') >>> time ['42', '12'] >>> time= int(time[0])*60+int(time[1]) >>> time 2532
Python numpy ValueError: setting an array element with a sequence Question: hi im trying to rotate an image 90 degree's but i keeep getting this error "ValueError: setting an array element with a sequence" and im not sure whats the problem. when i try and run the function with an array it works, but when i try it with an image i get that error. def rotate_by_90_deg(im): new_mat=np.zeros((im.shape[1],im.shape[0]), dtype=np.uint8) n = im.shape[0] for x in range(im.shape[0]): for y in range(im.shape[1]): new_mat[y,n-1-x]=im[x,y] return new_mat pass Answer: I can reproduce the error message with this code: import numpy as np def rotate_by_90_deg(im): new_mat=np.zeros((im.shape[1],im.shape[0]), dtype=np.uint8) n = im.shape[0] for x in range(im.shape[0]): for y in range(im.shape[1]): new_mat[y,n-1-x]=im[x,y] return new_mat im = np.arange(27).reshape(3,3,3) rotate_by_90_deg(im) The problem here is that `im` is 3-dimensional, not 2-dimensional. That might happen if your image is in RGB format, for example. So `im[x,y]` is an array of shape (3,). `new_mat[y, n-1-x]` expects a `np.uint8` value, but instead is getting assigned to an array. * * * To fix `rotate_by_90_deg`, make `new_mat` have the same number of axes as `im`: import numpy as np import matplotlib.pyplot as plt np.random.seed(1) def rotate_by_90_deg(im): H, W, V = im.shape[0], im.shape[1], im.shape[2:] new_mat = np.empty((W, H)+V, dtype=im.dtype) n = im.shape[0] for x in range(im.shape[0]): for y in range(im.shape[1]): new_mat[y,n-1-x]=im[x,y] return new_mat im = np.random.random((3,3,3)) arr = rotate_by_90_deg(im) fig, ax = plt.subplots(ncols=2) ax[0].imshow(10*im, interpolation='nearest') ax[0].set_title('orig') ax[1].imshow(10*arr, interpolation='nearest') ax[1].set_title('rot90') plt.show() ## ![enter image description here](http://i.stack.imgur.com/fYy8I.png) Or, you could use [`np.rot90`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rot90.html): import numpy as np import matplotlib.pyplot as plt np.random.seed(1) im = np.random.random((3,3,3)) arr = np.rot90(im, 3) fig, ax = plt.subplots(ncols=2) ax[0].imshow(10*im, interpolation='nearest') ax[0].set_title('orig') ax[1].imshow(10*arr, interpolation='nearest') ax[1].set_title('rot90') plt.show()
cython build via setup.py does wrong thing (putting all .so files in extra src dir) Question: I'm trying to convert from using pyximport to building via distutils, and I'm being stumped by the weird choices its making on where to put the .so files. So, I decided to build the tutorial out of the cython doc, only to find it prints a message saying its building, but does nothng. I'm in a virtualenv, and cython, python2.7, etc are all installed therein. First the basics: $ cython --version Cython version 0.21.2 $ cat setup.py from distutils.core import setup from Cython.Build import cythonize print "hello build" setup( ext_modules = cythonize("helloworld.pyx") ) $ cat helloworld.pyx print "hello world" Now When I build it everything looks ok except for the extra src/src stuff in the output: $ python setup.py build_ext --inplace hello build Compiling helloworld.pyx because it changed. Cythonizing helloworld.pyx running build_ext building 'src.helloworld' extension x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c helloworld.c -o build/temp.linux-x86_64-2.7/helloworld.o creating /home/henry/Projects/eyeserver/dserver/src/src x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/helloworld.o -o /home/henry/Projects/eyeserver/dserver/src/src/helloworld.so And when I run it, it of course fails: $ echo "import helloworld" | python Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named helloworld Until I move the .so file out of its extra src directory: $ mv src/helloworld.so . $ echo "import helloworld" | python Hello world What am I doing wrong? Obviously I could make the build process move all of the .so files, but that seems really hacky. Answer: Whenever I use cython I use the `Extension` command. I would write the setup.py file as follows: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize extensions = [ Extension("helloworld", ["helloworld.pyx"]) ] setup( ext_modules = cythonize(extensions) ) Hopefully this will then put the .so file in the current directory.
iPython notebook on Mac OSX Yosemite: no module named jinja2, even if it's installed Question: I am trying to run iPython notebook on OSX Yosemite. I have installed everything via pip install ipython[all] and I see mattia:~ mattiaspeziali$ pip freeze backports.ssl-match-hostname==3.4.0.2 certifi==14.5.14 docutils==0.12 gnureadline==6.3.3 ipython==2.3.1 Jinja2==2.7.3 MarkupSafe==0.23 nose==1.3.4 numpy==1.8.2 numpydoc==0.5 pandas==0.14.1 Pygments==2.0.1 pyzmq==14.4.1 Sphinx==1.2.3 tornado==4.0.2 vboxapi==1.0 However, jinja2 seems not installed properly: mattia:~ mattiaspeziali$ ipython notebook Traceback (most recent call last): File "/usr/local/bin/ipython", line 11, in <module> sys.exit(start_ipython()) File "/Library/Python/2.7/site-packages/IPython/__init__.py", line 120, in start_ipython return launch_new_instance(argv=argv, **kwargs) File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 563, in launch_instance app.initialize(argv) File "<string>", line 2, in initialize File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 92, in catch_config_error return method(app, *args, **kwargs) File "/Library/Python/2.7/site-packages/IPython/terminal/ipapp.py", line 321, in initialize super(TerminalIPythonApp, self).initialize(argv) File "<string>", line 2, in initialize File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 92, in catch_config_error return method(app, *args, **kwargs) File "/Library/Python/2.7/site-packages/IPython/core/application.py", line 381, in initialize self.parse_command_line(argv) File "/Library/Python/2.7/site-packages/IPython/terminal/ipapp.py", line 316, in parse_command_line return super(TerminalIPythonApp, self).parse_command_line(argv) File "<string>", line 2, in parse_command_line File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 92, in catch_config_error return method(app, *args, **kwargs) File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 475, in parse_command_line return self.initialize_subcommand(subc, subargv) File "<string>", line 2, in initialize_subcommand File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 92, in catch_config_error return method(app, *args, **kwargs) File "/Library/Python/2.7/site-packages/IPython/config/application.py", line 406, in initialize_subcommand subapp = import_item(subapp) File "/Library/Python/2.7/site-packages/IPython/utils/importstring.py", line 42, in import_item module = __import__(package, fromlist=[obj]) File "/Library/Python/2.7/site-packages/IPython/html/notebookapp.py", line 42, in <module> from jinja2 import Environment, FileSystemLoader ImportError: No module named jinja2 I tried also to uninstall and re-install jinja2, but nothing changes. Any suggestion? In addition: `mattia:~ mattiaspeziali$ which python /usr/local/bin/python` `mattia:~ mattiaspeziali$ which ipython /usr/local/bin/ipython` `mattia:~ mattiaspeziali$ which pip /usr/local/bin/pip` Answer: Re-installing iPython solved the issue.
Tweepy to access Twitter streaming API using python 3.4 Question: I'm unable to use tweepy to access Twitter streaming API using the following example code using python 3.4. This code was running using python 2.4. What is wrong ? from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener ckey = '' csecret = '' atoken = '' asecret = '' class listener(StreamListener): def on_data(self, data): print (data) return True def on_error(self, status): print (status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=["obama"]) Answer: Your code is exactly correct. But on Windows Vista/7, with UAC, administrator accounts run programs in unprivileged mode by default. Or it might be possible that you are trying to run on a port the current user account does not have permission to bind to. Run the following code to detect your script has admin access or not. import ctypes print ctypes.windll.shell32.IsUserAnAdmin() If it prints 1 then its ok. If 0 then your script doesn't have admin access.
Python Mathematical Formula computation Question: I'm writing a python program to calculate formula. I read in a list of strings which hold the values, operators and functions. The code shown below receives a string for example: ['not', 1.0, 2.0, '=', 'power', 2.0, 3.0, '+'] The code above is a postfix version of the mathematical problem: power(2,3)+not(2=1) The program should calculate not(2=1) first, resulting in 1 and then calculate power(2,3) giving 9 and then 8+0 resulting in a return of 8. So far my code to calculate the answers stack = [] def calculate(inputs): if (inputs[0] == "sum"): inputs.remove("sum") for a in inputs: if (a) == "not": inputs.remove(a) op1, op2 = inputs[0], inputs[1] inputs.remove(op1) inputs.remove(op2) if op1 != op2: stack.append('0') else: stack.append('1') continue if (a) == 'power': inputs.remove(a) continue if type(a) is float: stack.append(a) continue op1, op2 = stack.pop(), stack.pop() #if a == 'power': if a == '+': stack.append(op2 + op1) elif a == '-': stack.append(op1 - op2) elif a == '*': stack.append(op2 * op1) elif a == '/': stack.append(op1 / op2) elif a == '=': if op1 != op2: stack.append('0') else: stack.append('1') if (len(stack) > 1): lenStack = len(stack)-1 for x in range(0, lenStack): stack.append('+') stack.append(_calcSum(stack)) return stack.pop() def _calcSum(stack): newStack = [] for a in stack: if type(a) is float: newStack.append(a) continue op1, op2 = newStack.pop(), newStack.pop() if a == '+': newStack.append(op2 + op1) elif a == '-': newStack.append(op1 - op2) elif a == '*': newStack.append(op2 * op1) elif a == '/': newStack.append(op1 / op2) return newStack.pop() However I'm having trouble with the NOT and POWER statement; I can't figure out how to automatically check for these. Could anyone possibly point me in the right direction or assist with my code? When I try to check for 'power' it simply skips the rest of my code and attempts to print stack - which is empty causing an error. Answer: I think that the following code might be what you want: import math test_input = ['2', '1', '=', 'not', '2', '3', 'power', '+'] def calculate(input): newStack = [] for a in input: print newStack if a == '+': op1, op2 = newStack.pop(), newStack.pop() newStack.append(op2 + op1) elif a == '-': op1, op2 = newStack.pop(), newStack.pop() newStack.append(op1 - op2) elif a == '*': op1, op2 = newStack.pop(), newStack.pop() newStack.append(op2 * op1) elif a == '/': op1, op2 = newStack.pop(), newStack.pop() newStack.append(op1 / op2) elif a == '=': op1, op2 = newStack.pop(), newStack.pop() if op1 == op2: newStack.append(1) else: newStack.append(0) elif a == 'not': op = newStack.pop() if op > 0: newStack.append(0) else: newStack.append(1) elif a == 'power': op1, op2 = newStack.pop(), newStack.pop() newStack.append(math.pow(op1, op2)) else: newStack.append(float(a)) return newStack.pop() As PeterE pointed out in his comment your postfix code is wrong. I assume that your wanted postfix code probably is `2 1 = not 2 3 power +`. Also note that the end value then would be `9+1 = 10` and not `8+0 = 8`. Wikipedia has a nice page on postfix code: <http://en.wikipedia.org/wiki/Reverse_Polish_notation>. In the python code one function actually should be enough to push and pop all the needed stuff onto a stack. To achieve a basic implementation you can then simply check all your different operator cases and perform any needed operations. If none of the provided operators matches the current element, you can assume that the element is a numeric value and simply push the parsed float value. Note that this is a very quick and dirty implementation, but it might lead you on the right track.
Change string in file in python Question: I have a problem changing a file in python. I need to change a string. The file is not a text file but can be edited with a text editor. Here is my code: with open(esp,"r") as f: content=f.readlines() with open(esp_carsat,"w") as f: for line in content: f.write(line.replace("201","202"))) Problem is that content is in byte I think. '\xff\xfe<\x00I\x00n\x00s\x00t\x00a\x00n\x00c\x00e\x00N\x00a\x00m\x00e\x00s\x00>\x00\r\x00\n' So my replace is not working. I tried to play with encoding but the file is not readable afterwards. Furthermore, I have accents in the file (é,è...) Is there a way to do what I want? Answer: You have _UTF-16 encoded_ data. Decode to Unicode text, replace, and then encode back to UTF-16 again: >>> data = '\xff\xfe<\x00I\x00n\x00s\x00t\x00a\x00n\x00c\x00e\x00N\x00a\x00m\x00e\x00s\x00>\x00\r\x00\n\x00' >>> data.decode('utf16') u'<InstanceNames>\r\n' I had to append an extra `\x00` to decode that; by reading the file without decoding Python split the line on the `\n` and left the `\x00` for the _next_ line. Unicode data can handle accents just fine, no further work required there. This is easiest done with [`io.open()`](https://docs.python.org/2/library/io.html#io.open) to open file objects that do the decoding and encoding for you: import io with io.open(esp, "r", encoding='utf16') as f: content=f.readlines() with open(esp_carsat, "w", encoding='utf16') as f: for line in content: f.write(line.replace("201", "202")))
Incorporate an icon to python .exe using py2exe Question: I have this **setup.py** script for incorporating icon for my .exe file, but the icon isnt appearing after the setup. the icon is 361 KB in size. from distutils.core import setup import py2exe setup( console = [ { "script": "wykoRas_parser.py", ### Main Python script "icon_resources": [(0, "bw-gears.ico")] ### Icon to embed into the PE file. } ], ) Am i missing something from the setup? Answer: from distutils.core import setup setup( options = {'py2exe': {'bundle_files': 1}}, zipfile = None, windows = [{ "script":"myprogram.pyw", "icon_resources": [(1, "myicon.ico")], "dest_base":"myprogram" }], ) Could you try this one please, I had some problem before these codes solved.
How to recompile Python2.7 with 4-byte unicode enabled? Question: I have tried `./configure --enable-unicode` and `./configure --enable- unicode=ucs4` but the command `import sys; print sys.maxunicode` is still 65535. How should I fix this and compile Python with 4-byte unicode enabled? Answer: From the output of ./configure --help the correct option is given as --enable-unicode=ucs4
Python 2.7.6 dictionaries Question: I'm having a bit of trouble with Python 2.7.6, getting information from a dictionary and doing something useful with it. I have attached my entire code below, as I'm not sure what specifically is wrong, it might not be something I'm expecting. I am trying to generate some test data; a bunch of randomly distributed sources (1's) across an image that move a small amount from their correct positions. I track each source individually using dictionaries, and use dictionaries within a dictionary for each image containing shifted sources. My problem is when I want to take the average motion of the sources within an image. I have made the spot I believe the problem to be in clear (about halfway down). I have left in a few different techniques I have tried, they are commented out. Currently I am only using 3 images, but I intend to increase this number significantly. If I was sticking to only 3, I would have gone with a different method and written a lot of this out the long way. I've had a look for other questions like this but have not found anything specific to my issue, which could be because I don't know the lingo for what it is I am trying to do. Apologies if this has been asked before and solved. # Source position-offset tracker import math import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import copy import random from pylab import boxplot #FUNCTIONS def random_movement(source_positions): source_positions_changed={} for n in range(len(source_positions)): # n = [0,1] key = source_positions.keys()[n] del_x = source_positions[key][0]+random.randint(0,1) del_y = source_positions[key][1]+random.randint(0,1) source_positions_changed[key] = (del_x,del_y) return source_positions_changed #OTHER CODE # put in original positions # -> randomly distributed # -> of values 0 or 1 only original_positions = np.random.randint(2,size=(10,10)) # Tag each source within the image to keep track of them source_positions = {} source_count=0 for x in range(len(original_positions)): for y in range(len(original_positions[0])): if original_positions[x,y] == 1: # finding all sources source_count += 1 index = 'S'+str(source_count) source_positions[index] = (x,y) # attach a source name to its position source_numbers = len(source_positions) number_timesteps = 2 # how many images were taken NOT including the original # create a dictionary for the timesteps of shifted sources # timesteps are the images where the sources have moves from the correct position dictionary = {} for x in range(1,number_timesteps+1): #exec('dictionary%s = copy.copy(random_movement(source_positions))'%x) dictionary['position_changed{0}'.format(x)] = copy.copy(random_movement(source_positions)) # finding the distances from the sources original positions #source_distance_sum = {} ################################################# ### THIS IS WHERE I THINK I'M HAVING PROBLEMS ### ################################################# # this should take make the motion of any sources that appear outside the range of the image -1 # and for sources that remain in range should find the motion from the correct position # using equation: a^2 = b^2 + c^2 # should end up with source_distance_sum1 and source_distance_sum2 that have the motions from the correct positions of each source for the images, whose positional information was stored in dictionary['position_changed1'] and dictionary['position_changed2'] respectively #source_distance_sum=[] #distance_moved=[] for source in range(1,source_numbers+1): #source_distance_sum['S{0}'.format(source)]=0 for tstep in range(1,number_timesteps+1): exec('source_distance_sum%s=[]'%tstep) if dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][0]>=len(original_positions) or dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][1]>=len(original_positions[0]): #if 'dictionary%s[S%s][0]>=len(original_positions) or dictionary%s[S%s][1]>=len(original_positions[0])'%(tstep,source,tstep,source) #source_distance_sum['S{0}'.format(source)]=-1 exec('source_distance_sum%s.append(-1)'%tstep) #print 'if 1: '+str(source_distance_sum1) #print 'if 2: '+str(source_distance_sum2) # dealing with sources moved out of range else: distance_moved=np.sqrt((source_positions['S{0}'.format(source)][0]-dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][0])**2+(source_positions['S{0}'.format(source)][1]-dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][1])**2) # I have tried changing distance_moved as well, in similar ways to source_distance_sum, but I have as yet had no luck. #source_distance_sum['S{0}'.format(source)]=distance_moved exec('source_distance_sum%s.append(distance_moved)'%tstep) # why does this not work!!!!????? I really feel like it should... # for movement that stays in range #print 'else 1: '+str(source_distance_sum1) #print 'else 2: '+str(source_distance_sum2) # then I want to use the information from the source_distance_sum1 & 2 and find the averages. I realise the following code will not work, but I cannot get the previous paragraph to work, so have not moved on to fixing the following. # average distance: source_distance = [] for source in range(1,len(source_distance_sum)+1): if source_distance_sum['S{0}'.format(source)] > -1: source_distance.append(source_distance_sum['S{0}'.format(source)]) average = sum(source_distance)/float(len(source_distance)) # set range of graph #axx_max = np.ceil(max(distance_travelled)) #axy_max = np.ceil(max(number_of_sources)) # plot graph fig = plt.figure() #plt.axis([-1,axx_max+1,-1,axy_max+1]) plt.xlabel('Data set') plt.ylabel('Average distance travelled') plt.title('There are %s source(s) with %s valid' % (source_count,len(source_distance))) ax1 = fig.add_subplot(111) ax1.scatter(1, average, s=10, c='b', marker="+", label='First timestep') #ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second') plt.legend(loc='upper left'); plt.show() # NOTES AND REMOVED CODE # Move sources around over time # -> keep within a fixed range of motion # -> randomly generate motion # Calculate motion of sources from images # -> ignore direction # -> all that move by same magnitude get stored together # -> Number of sources against magnitude of motion # Make dictionary of number of sources that have moved a certain amount. #source_motion_count = {} # make length of sources, values all 0 #for elem in range(len(source_distance)): # if type(source_distance[elem])!=str and source_distance[elem]>-1: # source_motion_count[source_distance[elem]] = 0 #for elem in range(len(source_distance)): # if type(source_distance[elem])!=str and source_distance[elem]>-1: # source_motion_count[source_distance[elem]] += 1 # Compile count of sources based on movement into graph #number_of_sources = [] #distance_travelled = [] #for n in range(len(source_motion_count)): # key=source_motion_count.keys()[n] # number_of_sources.append(source_motion_count[key]) # distance_travelled.append(key) Answer: I fixed it by turning that section into its own function. I also changed my mind on some of what I wanted it to do, so there is a little variation from the original idea to what is below. import math import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import copy import random from pylab import boxplot #------------------------------------------------------------------------# #--------------------------FUNCTIONS-------------------------------------# #------------------------------------------------------------------------# def original_image(): # create image original_positions = np.random.randint(2,size=(11,11)) # make sure image has uneven lengths - will be useful later y = original_positions.shape[0] x = original_positions.shape[1] if y%2 == 0: y-=1 if x%2 == 0: x-=1 original_positions = original_positions[0:y,0:x] return original_positions def random_movement(source_positions): source_positions_changed={} # create some random movement in x and y axis, within a certain range for n in range(len(source_positions)): key = source_positions.keys()[n] # original source positions del_x = source_positions[key][0]+random.randint(-1,1) del_y = source_positions[key][1]+random.randint(-1,1) source_positions_changed[key] = (del_x,del_y) return source_positions_changed def tag_sources(original_positions): source_positions = {} source_count=0 # keeping track of all the sources (1's) from original image for x in range(len(original_positions)): for y in range(len(original_positions[0])): if original_positions[x,y] == 1: # finding all sources source_count += 1 index = 'S'+str(source_count) source_positions[index] = (x,y) return source_positions def calc_motion(position_dict_changed, position_dict_original,xaxis_len,yaxis_len): position_dict_motion = {} for source_num in range(1,len(position_dict_original)+1): # make sources that go outside the image range -1 if position_dict_changed['S{0}'.format(source_num)][1]>=yaxis_len or position_dict_changed['S{0}'.format(source_num)][0]>=xaxis_len: position_dict_motion['S{0}'.format(source_num)] = -1 else: # determine x and y motion from original position # this is the main difference from the original idea as do not want to average the motion x_motion = position_dict_original['S{0}'.format(source_num)][1] - position_dict_changed['S{0}'.format(source_num)][1] y_motion = position_dict_original['S{0}'.format(source_num)][0] - position_dict_changed['S{0}'.format(source_num)][0] position_dict_motion['S{0}'.format(source_num)] = (y_motion,x_motion) return position_dict_motion #------------------------------------------------------------------------# #--------------------------OTHER CODE------------------------------------# #------------------------------------------------------------------------# # creating random distribution of sources original_positions = original_image() orig_xaxis_len = len(original_positions[0]) orig_yaxis_len = len(original_positions) # tag sources in original_positions source_positions = tag_sources(original_positions) source_numbers = len(source_positions) # how many images were taken NOT including the original number_timesteps = 2 # create a dictionary for the timesteps of shifted sources positions_dict = {} for x in range(1,number_timesteps+1): positions_dict['position_changed{0}'.format(x)] = copy.copy(random_movement(source_positions)) # create a dictionary of the motion from the original position for each image for x in range(1,number_timesteps+1): motion_dict['position_changed{0}'.format(x)] = copy.copy(calc_motion(positions_dict['position_changed{0}'.format(x)],source_positions,orig_xaxis_len,orig_yaxis_len)) print motion_dict
referenced before assignment error Question: i have the following code to create a pygame of snake ( very basic ), to increase my snakes length i added a statement saying `snakeLength += 1 in line 142` it comes up with an error saying Traceback (most recent call last): File "C:/Python27/sjewgou.py", line 142, in <module> gameLoop() File "C:/Python27/sjewgou.py", line 118, in gameLoop if len(snakeList) > snakeLength: UnboundLocalError: local variable 'snakeLength' referenced before assignment what do i do ? my code is as follows import pygame pygame.init() import time import random white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,155,0) display_width = 800 display_height = 600 block_size = 10 FPS = 30 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("Ssssrikar") gameExit = False lead_x = display_width/2 lead_y = display_height/2 lead_x_change = 0 lead_y_change = 0 snakeList = [] snakeLength = 1 font = pygame.font.SysFont(None,25) clock = pygame.time.Clock() font = pygame.font.SysFont(None,25) def snake(block_size,snakelist): for elements in snakelist: pygame.draw.rect(gameDisplay, green, [elements[0], elements[1],block_size,block_size]) def message_to_screen(msg,color): screen_text = font.render(msg, True, color) gameDisplay.blit(screen_text, [display_width/2, display_height/2]) def gameLoop(): gameExit = False gameOver = False lead_x = display_width/2 lead_y = display_height/2 lead_x_change = 0 lead_y_change = 0 randAppleX = round(random.randrange(0,display_width-block_size)/10.0)*10.0 randAppleY = round(random.randrange(0,display_height-block_size)/10.0)*10.0 while not gameExit: while gameOver == True: gameDisplay.fill(white) message_to_screen("Gamer over, press C to play again or Q to quit",red) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_x_change = -block_size lead_y_change = 0 elif event.key == pygame.K_RIGHT: lead_x_change = block_size lead_y_change = 0 elif event.key == pygame.K_UP: lead_y_change = -block_size lead_x_change = 0 elif event.key == pygame.K_DOWN: lead_y_change = block_size lead_x_change = 0 if lead_x >= display_width: gameOver = True elif lead_x < 0: gameOver = True elif lead_y >= display_height: gameOver = True elif lead_y < 0: gameOver = True lead_x += lead_x_change lead_y += lead_y_change gameDisplay.fill(white) pygame.draw.rect(gameDisplay, red, [randAppleX,randAppleY,block_size,block_size]) snakeHead = [] snakeHead.append(lead_x) snakeHead.append(lead_y) snakeList.append(snakeHead) if len(snakeList) > snakeLength: del snakeList[0] snake(block_size, snakeList) pygame.display.update() if lead_x == randAppleX and lead_y == randAppleY: randAppleX = round(random.randrange(0,display_width-block_size)/10.0)*10 randAppleY = round(random.randrange(0,display_height-block_size)/10.0)*10 snakeLength += 1 clock.tick(FPS) pygame.quit() quit() gameLoop() Answer: UnboundLocalError, means your variable is not defined in scope of function. in you game loop add global snakeLength example: >>> x = 10 >>> def foo(): ... x += 1 #here x is local to foo ... >>> foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'x' referenced before assignment >>> def foo(): ... global x # now x is global variable ... x += 1 ... >>> foo() >>> x 11
Why is serial.tools available within os.system but not without? Question: I am working up to getting Python to read from a microcontroller which sends a short status string every second over COM port. As the μC (better not say which) has a fairly dodgy serial over USB implementation, I need to regularly check if the COM port exists. I can use `os.system('python -m serial.tools.list_ports')` to return the ports in Eclipse's Console. All good so far. I now want to go the next step and pass its output into a variable and process further - this is where I get unstuck. I would have thought I could assign using eg: `s = serial.tools.list_ports` but `tools` is not available within `serial` in this context. Why is this? Answer: If you're only importing `serial`, you can't access `serial.tools` directly because `tools` is another module (actually, a sub-package) within the `serial` package. The `serial` package doesn't import it for you. Some packages automatically import some or all of the modules and subpackages they contain, but that behavior needs to be specifically coded by the package developers, it's not done by Python unless you import the inner module yourself. Try explicitly importing the module you want to use: import serial.tools.list_ports as s serial.tools.list_ports.main() The `main` function implements the behavior you see when you run `python -m serial.tools.list_ports`. I found its name by looking in the [PySerial subversion repository](http://svn.code.sf.net/p/pyserial/code/trunk/pyserial/) on Sourceforge.
Number of levels (depth) of index and columns in a Pandas DataFrame Question: Python Pandas `DataFrame` can have hierarchical index (`MultiIndex`) or hierarchical columns. I'm looking for a way to know number of levels (depth) of index and columns. len(df.index.levels) seems to only work with MultiIndex but it doesn't work with normal index. Is there an attribute for this (which will works for `MultiIndex` but also simple `Index`) ? df.index.depth or df.columns.depth will be great. One example of MultiIndex columns and index: import pandas as pd import numpy as np def mklbl(prefix,n): return ["%s%s" % (prefix,i) for i in range(n)] def mi_sample(): miindex = pd.MultiIndex.from_product([mklbl('A',4), mklbl('B',2), mklbl('C',4), mklbl('D',2)]) micolumns = pd.MultiIndex.from_tuples([('a','foo'),('a','bar'), ('b','foo'),('b','bah')], names=['lvl0', 'lvl1']) dfmi = pd.DataFrame(np.arange(len(miindex)*len(micolumns)).reshape((len(miindex),len(micolumns))), index=miindex, columns=micolumns).sortlevel().sortlevel(axis=1) return(dfmi) df = mi_sample() So df looks like: lvl0 a b lvl1 bar foo bah foo A0 B0 C0 D0 1 0 3 2 D1 5 4 7 6 C1 D0 9 8 11 10 D1 13 12 15 14 C2 D0 17 16 19 18 D1 21 20 23 22 C3 D0 25 24 27 26 D1 29 28 31 30 B1 C0 D0 33 32 35 34 D1 37 36 39 38 C1 D0 41 40 43 42 D1 45 44 47 46 C2 D0 49 48 51 50 D1 53 52 55 54 C3 D0 57 56 59 58 D1 61 60 63 62 A1 B0 C0 D0 65 64 67 66 D1 69 68 71 70 C1 D0 73 72 75 74 D1 77 76 79 78 C2 D0 81 80 83 82 D1 85 84 87 86 C3 D0 89 88 91 90 D1 93 92 95 94 B1 C0 D0 97 96 99 98 D1 101 100 103 102 C1 D0 105 104 107 106 D1 109 108 111 110 C2 D0 113 112 115 114 D1 117 116 119 118 ... ... ... ... ... A2 B0 C1 D0 137 136 139 138 D1 141 140 143 142 C2 D0 145 144 147 146 D1 149 148 151 150 C3 D0 153 152 155 154 D1 157 156 159 158 B1 C0 D0 161 160 163 162 D1 165 164 167 166 C1 D0 169 168 171 170 D1 173 172 175 174 C2 D0 177 176 179 178 D1 181 180 183 182 C3 D0 185 184 187 186 D1 189 188 191 190 A3 B0 C0 D0 193 192 195 194 D1 197 196 199 198 C1 D0 201 200 203 202 D1 205 204 207 206 C2 D0 209 208 211 210 D1 213 212 215 214 C3 D0 217 216 219 218 D1 221 220 223 222 B1 C0 D0 225 224 227 226 D1 229 228 231 230 C1 D0 233 232 235 234 D1 237 236 239 238 C2 D0 241 240 243 242 D1 245 244 247 246 C3 D0 249 248 251 250 D1 253 252 255 254 [64 rows x 4 columns] Answer: To make summarized version of comments above: You can use `.nlevels` attribute which gives the number of levels for an index and columns: df = pd.DataFrame(np.random.rand(2,2), index=[['A','A'],['B','C']], columns=['a','b']) df a b A B 0.558 0.336 C 0.148 0.436 df.index.nlevels 2 df.columns.nlevels 1 As @joris mentioned above `len(df.columns.levels)` will not work in the example above as `columns` is not `MultiIndex`, giving: AttributeError: 'Index' object has no attribute 'levels' But it will work fine for `index` in the example above: len(df.index.levels) 2
Creating a comma delimited list in python Question: I have a need for a list of numbers, they need to be hex numbers. The list needs to be separated by commas (or anything really, just as long as they are separate) so that I can use the list as input to another program. I want to start at 0xffffffffff and go to 0xffffffffffffffffffff, printing each number to a text file, then a comma (separator), and then the next number, etc. The code I have currently counts, creates a file, and inputs the numbers. Tthe problem is it is decimal notation, not hex and it has no seperators. here is what i have: #!/usr/bin/python #count in hex from 10 f's to 20 f's and write to comma #delimited file to create a dictionary def count_hex(): x = 0xffffffffff while x <= 0xffffffffffffffffffff: x += 0x1 s = str(x) s.upper() with open("dictionary.txt", "a") as diction: diction.write(s) count_hex() I have played around with it by putting in separators, and even found a place that said i had to use import CSV, but that is something that I do not understand and would have to change everything. It seems that since it is mostly working, a few tweaks would be better than rewriting something that I do not understand. Answer: First, you reopen the file every time you want to write a number into it. It's slow. Then, you forget to format the number as hex, and forget to put the actual comma! def writeHex(start, stop, filename): with open(filename, "w") as output: for number in xrange(start, stop): output.write("%x, " % number) # writes smth like "ffffff," writeHex(0xfffff, 0x100000000000000000000000, "dictionary.txt") Note that all the numbers are written in one line, and there's a comma after the last number. Adding "\n" if/where needed and adding a variable like `is_first_number` to avoid the comma placement at the very end are left as an exercise.
BMI calculator always return 0. (Python) Question: i was just writing this very simple script to calculate bmi in kg and cm. But it always prints 0. Any ideas why? code: weight = int(raw_input("Weight in kg: ")) length = int(raw_input("Length in cm: ")) def bmi(): bmi = (weight) / (length * length) return bmi print bmi() Answer: Type cast it to `float`. `/` will do integer division always. That is bmi = float(weight) / float(length * length) It will print Weight in kg: 10 Length in cm: 20 0.025 Or do from __future__ import division
Trouble with converting regex to python Question: I have this regex [^\\]["'&<>] in order to match some unescaped characters. However trying to convert it into a python string is giving me grief. I've tried r'[^\\][\"\'&<>]' but I end up with this error. raise error, v # invalid expression sre_constants.error: bad group name Any help would be appreciated! Answer: Maybe you doing something wrong? import re print(bool(re.match(r'[^\\]["\'&<>]', 'a\"a'))) # True print(bool(re.match(r'[^\\]["\'&<>]', 'asd'))) # False
AttributeError when using validatecommand on a Spinbox Question: I am doing a test writing a script that validate a spinbox to implement it on a larger system, but I am struggling with python because it is warning that there is no spinbox attribute on my `Window` class. Check my code: from Tkinter import * class Window: def __init__(self, toplevel): self.spinbox = Spinbox(toplevel, from_ = 0, to = 10, validate = 'all', validatecommand = self.validate) self.spinbox.pack() def validate(self): print self.spinbox.get() root = Tk() Window(root) root.mainloop() This is the error it is giving: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__ return self.func(*args) File "D:\DOCS\FILIPE\PROGRAMMING\PYTHON\Tkinter sandbox\01 - spinbox validate. py", line 13, in validate print self.spinbox.get() AttributeError: Window instance has no attribute 'spinbox' Anyone could help me with this one? Answer: If you add some `print` statements to your code: class Window: def __init__(self, toplevel): print "A start", self, self.__dict__ self.spinbox = Spinbox(toplevel, from_ = 0, to = 10, validate = 'all', validatecommand = self.validate) self.spinbox.pack() print "A end", self, self.__dict__ def validate(self): print "B", self, self.__dict__ print self.spinbox.get() #... You get the output: A start <__main__.Window instance at 0x7fe4f8deec20> {} B <__main__.Window instance at 0x7fe4f8deec20> {} Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__ return self.func(*args) File "t.py", line 14, in validate print self.spinbox.get() AttributeError: Window instance has no attribute 'spinbox' A end <__main__.Window instance at 0x7fe4f8deec20> {'spinbox': <Tkinter.Spinbox instance at 0x7fe4f8e0da28>} This means that the validate function is called inside the constructor to validate the initial value, and at that point `self.spinbox` has not yet been set. You will need to either check if you are still constructing or delay setting `validatecommand` like this: self.spinbox = Spinbox(toplevel, from_ = 0, to = 10, validate = 'all') self.spinbox["validatecommand"] = self.validate self.spinbox.pack()
Python - find out how much of an image is black Question: I am downloading satellite pictures like this ![satellite_image](http://home.chpc.utah.edu/~u0553130/NASA_SPoRT_VIIRS_Images/VIIRS_11um_20150104_1834_UTC.gif) Since some images are mostly black, like this one, I don't want to save it. How can I use python to check if the image is more than 50% black? Answer: You're dealing with gifs which are mostly grayscale by the look of your example image, so you might expect most of the RGB components to be equal. Using PIL: from PIL import Image im = Image.open('im.gif') pixels = im.getdata() # get the pixels as a flattened sequence black_thresh = 50 nblack = 0 for pixel in pixels: if pixel < black_thresh: nblack += 1 n = len(pixels) if (nblack / float(n)) > 0.5: print("mostly black") Adjust your threshold for "black" between 0 (pitch black) and 255 (bright white) as appropriate).
plus/minus operator for python ± Question: I am looking for a way to do a plus/minus operation in python 2 or 3. I do not know the command or operator, and I cannot find a command or operator to do this. Am I missing something? Answer: Another possibility: [uncertainties](http://pythonhosted.org/uncertainties/) is a module for doing calculations with error tolerances, ie (2.1 +/- 0.05) + (0.6 +/- 0.05) # => (2.7 +/- 0.1) which would be written as from uncertainties import ufloat ufloat(2.1, 0.05) + ufloat(0.6, 0.05) **Edit:** I was getting some odd results, and after a bit more playing with this I figured out why: the specified error is not a tolerance (hard additive limits as in engineering blueprints) but a standard-deviation value - which is why the above calculation results in ufloat(2.7, 0.07071) # not 0.1 as I expected!
Python: How does one use variables defined in main(), and/or use a lists with two classes without errors? Question: Objective: I have tried using variables in main() and creating a random list of messages in my code, which have partially worked, but are still coming up with multiple errors that I don't know how to fix. Question: Could someone fix my code so the errors are gone, and the program at least works as intended? In the main() section of my code I define several buttons, which I think messes up the GUI of the timer section of my program after the first break timer. The objective box is supposed to reappear in the window, but it doesn't. This also may have something to do with the .destroy() command. How would I fix it so the label and entry widget reappear in the initial window? How this question is different: I am aware that there is a large number of questions regarding some of these common errors, but my code is unique, and thus requires a different post. Code: (This should be all formatted correctly, pull it into your favorite IDE and run it to debug) from Tkinter import * import time import random class PopUp(): def __init__(self): top = self.top = Toplevel() self.inp = StringVar() self.nth = 0 top.geometry("240x135+25+300") Label(top, text="Suggestion:").pack(side=TOP) self.message() Label(top, textvariable=self.inp) def message(self): self.inp.set(random.choice(self.mess)) mess = ['Nice Job! Go take a walk outside!', 'Nice Job! Wiggle your toes, and get back on it!', 'Nice Job! Get up and walk around!', 'Nice Job! Go get a drink of water!', 'Good Work! Go take a walk outside!', 'Good Work! Wiggle your toes, and get back on it!', 'Good Work! Get up and walk around!', 'Good Work! Go get a drink of water!'] class Timer(Frame): def __init__(self, stb, st, rb, qb, parent=None, **kw): Frame.__init__(self, parent, background="white") self.parent = parent self.initUI() self.inp = None self.stb = stb self.st = st self.rb = rb self.qb = qb self.timer1 = 9 self.checkTimer1 = 1 self.timer1Run = 0 self.tempObj = 0 self.entdat = StringVar() self.timestr = StringVar() self.makeTimer() self.makeWidgets() def initUI(self): self.parent.title("Timer") def makeWidgets(self): minutes = int(self.timer1/60) seconds = int(self.timer1 - minutes*60.0) self.timestr.set('%02d:%02d' % (minutes, seconds)) self.ol = Label(text="Objective:") self.ol.pack(fill=X, expand=NO, pady=2, padx=2, side=TOP) self.ew = Entry(textvariable=self.entdat) self.ew.pack(fill=X, expand=NO, pady=2, padx=2, side=TOP) self.b = Button(text="OK", command=self.clicked) self.b.pack(side=TOP) def makeTimer(self): self.l = Label(self, textvariable=self.timestr) self.l.pack(fill=X, expand=NO, pady=2, padx=2) def makeButtons(self, st, stb, rb, qb): self.destroy() def updateTime(self): self.elapsed = time.time() - self.startTime self.curtim1 = self.timer1 - self.elapsed if self.curtim1 <= 0: self.stop() self.checkValue() else: minutes = int(self.curtim1/60) seconds = int(self.curtim1 - minutes*60.0) self.timestr.set('%02d:%02d' % (minutes, seconds)) self.timer = self.after(1, self.updateTime) def checkValue(self): if self.checkTimer1 == 1: self.distroy_Widget() self.timer1 = 3 self.checkTimer1 -= 1 self.start() else: self.dat.destroy() self.makeWidgets() self.timer1 = 9 self.checkTimer1 += 1 pu = PopUp() pu.message() self.start() def start(self): if not self.timer1Run: self.startTime = time.time() self.updateTime() self.timer1Run = 1 def stop(self): if self.timer1Run: self.after_cancel(self.timer) self.timer1Run = 0 self.timer1 = self.curtim1 def reset(self): self.timer1 = 900 minutes = int(self.timer1/60) seconds = int(self.timer1 - minutes*60.0) self.timestr.set('%02d:%02d' % (minutes, seconds)) def clicked(self): self.distroy_Widget() self.dat = Label(self, textvariable=self.entdat) self.dat.pack(side=TOP) def distroy_Widget(self): self.ew.destroy() self.ol.destroy() self.b.destroy() def main(): root = Tk() root.geometry("240x235+25+50") tm = Timer(root, stb, sb, rb, qb) tm.pack(side=TOP) sb = Button(root, text='Start', command=tm.start).pack(side=LEFT) stb = Button(root, text='Pause', command=tm.stop).pack(side=LEFT) rb = Button(root, text='Reset', command=tm.reset).pack(side=LEFT) qb = Button(root, text='Quit', command=root.quit).pack(side=LEFT) mainloop() if __name__ == '__main__': main() Answer: Sorry, but the code indenting in your question isn't quite right. However-- ignoring that relatively minor issue and the fact that the following modified version of it doesn't address all your questions--you may still find it useful because it does get rid of the errors about using variables in`main()`by making them all attributes of the`Timer`class, the only place they're referenced, and initializing them in its`__init__()` method--essentialy what @Mike Housky suggested in [his comment](http://stackoverflow.com/questions/27872410/python-how-does-one-use- variables-defined-in-main-and-or-use-a-lists-with- tw#comment44147355_27872410). I also renamed a few things to be more consistent. This should get the GUI running well enough to allow you can deal with the remaining problems yourself. from Tkinter import * import time import random class PopUp(): def __init__(self): top = self.top = Toplevel() self.inp = StringVar() self.nth = 0 top.geometry("240x135+25+300") Label(top, text="Suggestion:").pack(side=TOP) self.message() Label(top, textvariable=self.inp) def message(self): self.inp.set(random.choice(self.mess)) mess = ['Nice Job! Go take a walk outside!', 'Nice Job! Wiggle your toes, and get back on it!', 'Nice Job! Get up and walk around!', 'Nice Job! Go get a drink of water!', 'Good Work! Go take a walk outside!', 'Good Work! Wiggle your toes, and get back on it!', 'Good Work! Get up and walk around!', 'Good Work! Go get a drink of water!'] class Timer(Frame): def __init__(self, parent=None, **kw): Frame.__init__(self, parent, background="white") self.initUI(parent) self.inp = None self.timer1 = 9 self.checkTimer1 = 1 self.timer1Run = 0 self.tempObj = 0 self.entdat = StringVar() self.timestr = StringVar() self.makeTimer() self.makeWidgets() def initUI(self, parent): self.parent = parent self.parent.title("Timer") self.sb = Button(self.parent, text='Start', command=self.start).pack(side=LEFT) self.stb = Button(self.parent, text='Pause', command=self.stop).pack(side=LEFT) self.rb = Button(self.parent, text='Reset', command=self.reset).pack(side=LEFT) self.qb = Button(self.parent, text='Quit', command=parent.quit).pack(side=LEFT) def makeWidgets(self): minutes = int(self.timer1/60) seconds = int(self.timer1 - minutes*60.0) self.timestr.set('%02d:%02d' % (minutes, seconds)) self.ol = Label(text="Objective:") self.ol.pack(fill=X, expand=NO, pady=2, padx=2, side=TOP) self.ew = Entry(textvariable=self.entdat) self.ew.pack(fill=X, expand=NO, pady=2, padx=2, side=TOP) self.b = Button(text="OK", command=self.clicked) self.b.pack(side=TOP) def makeTimer(self): self.l = Label(self, textvariable=self.timestr) self.l.pack(fill=X, expand=NO, pady=2, padx=2) def updateTime(self): self.elapsed = time.time() - self.startTime self.curtim1 = self.timer1 - self.elapsed if self.curtim1 <= 0: self.stop() self.checkValue() else: minutes = int(self.curtim1/60) seconds = int(self.curtim1 - minutes*60.0) self.timestr.set('%02d:%02d' % (minutes, seconds)) self.timer = self.after(1, self.updateTime) def checkValue(self): if self.checkTimer1 == 1: self.destroyWidgets() self.timer1 = 3 self.checkTimer1 -= 1 self.start() else: self.dat.destroy() self.makeWidgets() self.timer1 = 9 self.checkTimer1 += 1 pu = PopUp() pu.message() self.start() def start(self): if not self.timer1Run: self.startTime = time.time() self.updateTime() self.timer1Run = 1 def stop(self): if self.timer1Run: self.after_cancel(self.timer) self.timer1Run = 0 self.timer1 = self.curtim1 def reset(self): self.timer1 = 900 minutes = int(self.timer1/60) seconds = int(self.timer1 - minutes*60.0) self.timestr.set('%02d:%02d' % (minutes, seconds)) def clicked(self): self.destroyWidgets() self.dat = Label(self, textvariable=self.entdat) self.dat.pack(side=TOP) def destroyWidgets(self): self.ew.destroy() self.ol.destroy() self.b.destroy() def main(): root = Tk() root.geometry("240x235+25+50") tm = Timer(root) tm.pack(side=TOP) mainloop() if __name__ == '__main__': main()
Django 1.7 python manage.py makemigrations polls SyntaxError Question: I am following the official Django documentation and trying to make the polls app. But when I run the command python manage.py makemigrations polls I get the console error. anupam@Anupam-HP:~/Python/django/mysite$ python manage.py makemigrations polls Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.7.2-py2.7.egg/django/ core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/Django-1.7.2-py2.7.egg/django/core/management/__init__.py", line 354, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/Django-1.7.2-py2.7.egg/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/Django-1.7.2-py2.7.egg/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/dist-packages/Django-1.7.2-py2.7.egg/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/anupam/Python/django/mysite/polls/models.py", line 13 ^ SyntaxError: invalid syntax The code I am using for the models is: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default= It would be great if you could point out the error. Answer: The error line is the last line of your `models.py`: votes = models.IntegerField(default= It should be: votes = models.IntegerField(default=0)
Python program is outputting a strange value to my 16x2 Character LCD Question: I've built a small program with a Tkinter GUI to let me enter 2 lines of text and make it display it on the character screen. It all works pretty neatly until I press apply text, because then I just seem to get a weird value on both lines of the LCD. e.g. Wanted line 1: "`Test`" Wanted line 2: "`Please work`" Actual result Line 1: `.3047332040L.304` Line 2: `7332320L` This is my code: __author__ = 'David' from Tkinter import * from Adafruit_CharLCD import Adafruit_CharLCD from time import sleep import psutil chargui = Tk() lcd = Adafruit_CharLCD() lcd.begin(16, 1) class FrameWork: def __init__(self, master): frame = Frame(master) frame.pack() # Creation self.lbl_enter1 = Label(frame, text="Enter the first line:") self.lbl_enter2 = Label(frame, text="Enter the second line:") self.ent_line1 = Entry(frame) self.ent_line2 = Entry(frame) self.btn_apply = Button(frame, text="Apply Text", command=self.applymessage) self.btn_cpum = Button(frame, text="CPUMem", command=self.CPUMem) self.btn_quit = Button(frame, text="Quit", command=frame.master.destroy) # Griding self.lbl_enter1.grid(row=0, column=0, sticky=E, padx=2) self.lbl_enter2.grid(row=1, column=0, sticky=E, padx=2) self.ent_line1.grid(row=0, column=1, sticky=W) self.ent_line2.grid(row=1, column=1, sticky=W) self.btn_apply.grid(row=2, column=1, sticky=W, padx=24) self.btn_cpum.grid(row=2, column=0, columnspan=2, sticky=W, padx=85) self.btn_quit.grid(row=2, column=1, sticky=E) def applymessage(self): lcd.clear() lcd.message(str(self.ent_line1)) lcd.message(str(self.ent_line2)) def CPUMem(self): while 1: lcd.clear() lcd.message("CPU: " + str(psutil.cpu_percent()) + "%\n") lcd.message("MEM: " + str(psutil.virtual_memory().percent) + "%") sleep(1) g = FrameWork(chargui) chargui.mainloop() Don't mind the `CPUMem` function. This function works nicely. It's just `applymessage(self):` that gives me trouble. I get no error at all. If I remove `srt()` from the 2 lcd.message functions though, it says it can't concatenate a string with an int. Any solutions? Edit: I tried to just print the value to the console instead of putting it onto the LCD, and it still gives me the weird values (are they memory locations? wild guess) for both lines Line 1: `.3047815368L.3047815608L` Line 2: `.3047815368L.3047815648L` Answer: As you found, the LCD has nothing to do with it. The problem is trying to convert a Tkinter `Entry` object into a `str`: str(self.ent_line1) calls a [special method](http://www.rafekettler.com/magicmethods.html#representations), `self.ent_line1.__str__()` to get the string representation of the object (as does `print`). There is no expectation that `__str__` is defined to do something useful. Actually, investigating using the interactive shell, you can find that this special method is defined in a parent class, and it's docstring is "Return the window path name of this widget." That's what you're seeing. What you actually want, the text typed into the widget as a string, is given by [`get()`](http://effbot.org/tkinterbook/entry.htm#Tkinter.Entry.get- method): print self.ent_line1.get()
Django - Dictionary update sequence element #0 has length 1; 2 is required Question: After i created new URLs, i got this error **ValueError at /blog/ dictionary update sequence element #0 has length 1; 2 is required** Traceback Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 1.7.2 Python Version: 3.4.1 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'modeltranslation', 'blog') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response 98. resolver_match = resolver.resolve(request.path_info) File "C:\Python34\lib\site-packages\django\core\urlresolvers.py" in resolve 345. sub_match = pattern.resolve(new_path) File "C:\Python34\lib\site-packages\django\core\urlresolvers.py" in resolve 345. sub_match = pattern.resolve(new_path) File "C:\Python34\lib\site-packages\django\core\urlresolvers.py" in resolve 222. kwargs.update(self.default_args) Exception Type: ValueError at /blog/ Exception Value: dictionary update sequence element #0 has length 1; 2 is required I use this urls # /project/urls.py from blog.urls import urlpatterns as blog_urls urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include(blog_urls, 'blog')), ) # /blog/urls.py urlpatterns = patterns('blog.views', url(r'^$', 'index', 'index'), url(r'^category/(?P<category_id>\d+)/$', 'category', 'category'), ) # /blog/views.py def index(request): render(request, 'blog/index.html') def category(request, category_id): render(request, 'blog/index.html') Why i got this error? Never saw it before and i don't know why i getting this error... Answer: **The problem is this line:** url(r'^category/(?P<category_id>\d+)/$', 'category', 'category') **The _third_ positional parameter is the extra context dict. If you want to pass the name instead, you need to use a keyword arg:** url(r'^category/(?P<category_id>\d+)/$', 'category', name='category')
python: sending a mail, fails when inside a "with" block Question: I am wondering why this code test = smtplib.SMTP('smtp.gmail.com', 587) test.ehlo() test.starttls() test.ehlo() test.login('address','passw') test.sendmail(sender, recipients, composed) test.close() works, but when written like this with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.ehlo() s.login('address','passw') s.sendmail(sender, recipients, composed) s.close() it fails with the message Unable to send the email. Error: <class 'AttributeError'> Traceback (most recent call last): File "py_script.py", line 100, in <module> with smtplib.SMTP('smtp.gmail.com', 587) as s: AttributeError: __exit__ Why is this happening? (python3 on a raspberry pi) Thx Answer: You are not using Python 3.3 or up. In your version of Python, `smtplib.SMTP()` is not a context manager and cannot be using in a `with` statement. The traceback is directly caused because there is no [`__exit__` method](https://docs.python.org/2/library/stdtypes.html#contextmanager.__exit__), a requirement for context managers. From the [`smptlib.SMTP()` documentation](https://docs.python.org/3/library/smtplib.html#smtplib.SMTP): > _Changed in version 3.3_ : Support for the `with` statement was added. You can wrap the object in a context manager with [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager): from contextlib import contextmanager from smtplib import SMTPResponseException, SMTPServerDisconnected @contextmanager def quitting_smtp_cm(smtp): try: yield smtp finally: try: code, message = smtp.docmd("QUIT") if code != 221: raise SMTPResponseException(code, message) except SMTPServerDisconnected: pass finally: smtp.close() This uses the same exit behaviour as was added in Python 3.3. Use it like this: with quitting_smtp_cm(smtplib.SMTP('smtp.gmail.com', 587)) as s: s.ehlo() s.starttls() s.ehlo() s.login('address','passw') s.sendmail(sender, recipients, composed) Note that it'll close the connection for you.
How do I create a list, then len() it, then make an entry for every 'section' in that list in Python? Question: So, I'm working on a project, which requires me to find how many 'objects' are in a list, which I accomplished via `len()`, however, now I need to make it where there is a choice (in easygui's `choicebox()`) for every entry in that list, without raising an 'out of range' exception. Basically, if there are 3 entries in the list, then I need `choicebox(msg="",title="",choices=[e[1])` to become `choicebox(msg="",title="",choices=[e[1],e[2],e[3]])`, and if there are 5 choices, I need it to become `choicebox(msg="",title="",choices=[e[1],e[2],e[3],e[4],e[5]])`and so on. Notes: I need `e[0]` to be skipped, that being either `.DS_Store`, `desktop.ini`, or `thumbs.db`. I'm listing directories just before that, so if you could tell me how to only make the directories end up on the list, or even how to limit the entries to 22, that'd be greatly appreciated as well!! Sorry for the noobish question! I couldn't think of how to search for something like this, or a suiting title even..... EDIT: Here's my script due to request. It is almost bugless, but very incomplete and broken; #imports from easygui import * import os #variables storyname = None #get user action def selectaction(): d = str(buttonbox(msg="What would you to do?",title="Please Select an Action.",choices=["View Program Info","Start Reading!","Exit"])) if d == "View Program Info": msgbox(msg="This program was made solely by Thecheater887. Program Version 1.0.0. Many thanks to the following Story Authors; Thecheater887 (Cheet)",title="About",ok_button="Oh.") selectaction() elif d == "Exit": exit else: enterage() #get reader age def enterage(): c = os.getcwd() # print c b = str(enterbox(msg="Please enter your age",title="Please enter your age",default="Age",strip=True)) # print str(b) if b == "None": exit() elif b == "Age": msgbox(msg="No. Enter your age. Not 'Age'...",title="Let's try that again...",ok_button="Fine...") enterage() elif b == "13": # print "13" choosetk() elif b >= "100": msgbox(msg="Please enter a valid age between 0 and 100.",title="Invalid Age!") enterage() elif b >= "14": # print ">12" choosema() elif b <= "12": # print "<12" choosek() else: fatalerror() #choose a kids' story def choosek(): os.chdir("./Desktop/Stories/Kid") f = str(os.getlogin()) g = "/Users/" h = "/Desktop/Stories/Kid" i = g+f+h e = os.listdir(i) names = [name for name in e if name not in ('.DS_Store', 'desktop.ini', 'thumbs.db')] limit = 22 # maximum entries in the choicebox --> e[1] until e[22] for i in xrange(1, len(e)): # starting from 1 because you don't want e[0] in there if(i > limit): break # so if you have 100 files, it will only list the first 22 else: names.append(e[i]) #names = e[1:23] choicebox(msg="Please select a story.",title="Please Select a Story",choices=names) #choose a mature story def choosema(): os.chdir("./Desktop/Stories/Mature") #choose a teen's story def choosetk(): os.chdir("./Desktop/Stories/Teen") def fatalerror(): msgbox(msg="A fatal error has occured. The program must now exit.",title="Fatal Error!",ok_button="Terminate Program") #select a kids' story def noneavailable(): msgbox(msg="No stories are available at this time. Please check back later!",title="No Stories Available",ok_button="Return to Menu") enterage() selectaction() Answer: So here is my solution (now that I have the code): def choosek(): os.chdir("./Desktop/Stories/Kid") f = str(os.getlogin()) g = "/Users/" h = "/Desktop/Stories/Kid" i = g+f+h e = os.listdir(i) names = [] # the list with the file names limit = 22 # maximum entries in the choicebox --> e[1] until e[22] for i in xrange(1, len(e)): # starting from 1 because you don't want e[0] in there if(i > limit): break # so if you have 100 files, it will only list the first 22 else: names.append(e[i]) choicebox(msg="Please select a story.",title="Please Select a Story",choices=names) I hope this is what you were looking for.
Python Not Removing Char From String Question: Iv tried multiple times and ways for removing the extra punctuation from the string. import string class NLP: def __init__(self,sentence): self.sentence = sentence.lower() self.tokenList = [] #problem were the punct is still included in word def tokenize(self, sentence): for word in sentence.split(): self.tokenList.append(word) for i in string.punctuation: if(i in word): word.strip(i) self.tokenList.append(i) quick explanation of the code... What it is suppose to do is to split each word and punctuation and store them in a list. But when i have punctuation next to a word it stays with the word. Below is an example where a comma remains grouped with the word 'hello' ['hello,' , ',' , 'my' , 'name' , 'is' , 'freddy'] #^ #there's the problem Answer: A Python string is immutable. Therefore, `word.strip(i)` does **not** "change `word` in place" as you seem to assume; rather, it returns a **copy** of `word`, modified by the `.strip(i)` operation -- which removes only from the **ends** of the string, so that's not what you want either (unless you know the punctuation occurs in the word in a peculiar order). def tokenize(self, sentence): for word in sentence.split(): punc = [] for i in string.punctuation: howmany = word.count(i) if not howmany: continue word = word.replace(i, '') punc.extend(howmany*[i]) self.tokenList.append(word) self.tokenList.extend(punc) This assumes it's OK to have all the punctuation, one per item, **after** the cleaned-up word, independently of where within the word the punctuation appeared. For example, should the `sentence` be `(here)`, the list would be `['here', '(', ')']`. If there are stricter constraints on the ordering of things in the list, please edit your Q to express them clearly -- ideally with examples of desired input and output, too!
Django Migrate issue Question: A django model created as follows from django.db import models class Vender(models.Model): id =models.IntegerField(primary_key=True) name = models.CharField(max_length=30) class Meta: db_table="vendor" class car(models.Model): id =models.IntegerField(primary_key=True) Vender=models.ForeignKey(Vender) carmodel =models.CharField(max_length=30) class Meta: db_table="car" Initially `makemigration` and `migrate` worked fine. Then I changed some model fields and options. After that getting the below error. I am new to Django. This kind of issues is happen in production how we can solve with out effecting live transaction data. F:\Workspace\virtspace\demosrc>python manage.py migrate Operations to perform: Apply all migrations: admin, contenttypes, base, auth, sessions Running migrations: Applying base.0003_auto_20150110_2004...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\Python27\lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line utility.execute() File "D:\Python27\lib\site-packages\django\core\management\__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python27\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) File "D:\Python27\lib\site-packages\django\core\management\base.py", line 338, in execute output = self.handle(*args, **options) File "D:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 160, in handle executor.migrate(targets, plan, fake=options.get("fake", False)) File "D:\Python27\lib\site-packages\django\db\migrations\executor.py", line 63, in migrate self.apply_migration(migration, fake=fake) File "D:\Python27\lib\site-packages\django\db\migrations\executor.py", line 97, in apply_migration migration.apply(project_state, schema_editor) File "D:\Python27\lib\site-packages\django\db\migrations\migration.py", line 107, in apply operation.database_forwards(self.app_label, schema_editor, project_state, new_state) File "D:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards schema_editor.remove_field(from_model, from_model._meta.get_field_by_name(self.name)[0]) File "D:\Python27\lib\site-packages\django\db\backends\schema.py", line 439, in remove_field self.execute(sql) File "D:\Python27\lib\site-packages\django\db\backends\schema.py", line 99, in execute cursor.execute(sql, params) File "D:\Python27\lib\site-packages\django\db\backends\utils.py", line 81, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "D:\Python27\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "D:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "D:\Python27\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "D:\Python27\lib\site-packages\django\db\backends\oracle\base.py", line 916, in execute return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-00904: "ID": invalid identifier Answer: you dont need id =models.IntegerField(primary_key=True) django adds it for you. dont worry about it. delete these fields, `makemigrations`, `migrate` and you are fine.
Web crawler to extract from list elements Question: I am trying to extract from `<li>` tags the dates and store them in an Excel file. <li>January 13, 1991: At least 40 people <a href ="......."> </a> </li> **Code:** import urllib2 import os from datetime import datetime import re os.environ["LANG"]="en_US.UTF-8" from bs4 import BeautifulSoup page1 = urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes") soup = BeautifulSoup(page1) li =soup.find_all("li") count = 0 while count < len(li): soup = BeautifulSoup(li[count]) date_string, rest = soup.li.text.split(':', 1) print datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y') count+=1 **Error:** Traceback (most recent call last): File "C:\Users\sony\Desktop\Trash\Crawler Try\trytest.py", line 13, in <module> soup =BeautifulSoup(li[count]) File "C:\Python27\lib\site-packages\bs4\__init__.py", line 161, in __init__ markup = markup.read() TypeError: 'NoneType' object is not callable [Finished in 4.0s with exit code 1] I don't know how to write each text extracted in excel thus. Haven't included in it the code. Refer question: [Web crawler to extract in between the list](http://stackoverflow.com/questions/27822862/web-crawler-to-extract-in- between-the-list) Answer: The problem is - there are irrelevant `li` tags that don't contain the data you need. Be more specific. For example, if you want to get the list of events from the "20th century", first find the header and get the list of events from it's parent's [following `ul` sibling](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling- and-previous-sibling). Also, not every item in the list has the date in the `%B %d, %Y` format - you need to handle it via `try/except` block: import urllib2 from datetime import datetime from bs4 import BeautifulSoup page1 = urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes") soup = BeautifulSoup(page1) events = soup.find('span', id='20th_century').parent.find_next_sibling('ul') for event in events.find_all('li'): try: date_string, rest = event.text.split(':', 1) print datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y') except ValueError: print event.text Prints: 19/09/1902 30/12/1903 11/01/1908 24/12/1913 23/10/1942 09/03/1946 1954 500-800 killed at Kumbha Mela, Allahabad. 01/01/1956 02/01/1971 03/12/1979 20/10/1982 29/05/1985 13/03/1988 20/08/1988 * * * Updated version (getting all ul groups under a century): events = soup.find('span', id='20th_century').parent.find_next_siblings() for tag in events: if tag.name == 'h2': break for event in tag.find_all('li'): try: date_string, rest = event.text.split(':', 1) print datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y') except ValueError: print event.text
find all possible combinations of letters in a string in python Question: I have a string in python, I need to find all the possible ways any substring of that string (including itself) could be selected. A substring (for my purposes) does not have to be contiguous, in the original string -- it could have gaps. Eg "frogman" is one of the many substrings of "froghuman' under this definition. For example of the would function: If my string is `"abcd"`, the output should be: ["a","b","c","d","ab","ac","ad","bc","bd","cd","abc","abd","acd","bcd","abcd"] Answer: Your example input/output suggests that you are looking for a [power set](http://en.wikipedia.org/wiki/Power_set). You could [generate a power set for a string using `itertools` module in Python](https://docs.python.org/dev/library/itertools.html#itertools-recipes): from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) print(list(map(''.join, powerset('abcd')))) ### Output ['', 'a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd', 'abcd'] Note: the output includes the empty string.
Python filecmp.cmp('old_index.html', 'new_index.html') in if event Question: how can I make this python command in a if question: import filecmp filecmp.cmp('old_index.html', 'new_index.html') the answer from these command is True or False. So that I can execute something when the files are the same or when they are not. Thanks for your help Answer: You can simply use that in an `if` statement, like this if filecmp.cmp('old_index.html', 'new_index.html'): # Do whatever you want if the files are the same print("Both the files are same") else: # Do whatever you want if the files are NOT the same print("No, the files are NOT the same")
Python: Convert xlrd sheet to numpy matrix (ndarray) Question: What is the conversion syntax to convert a successfully loaded xlrd excel sheet to a numpy matrix (that represents that sheet)? Right now I'm trying to take each row of the spreadsheet and add it to the numpy matrix. I can't figure out the syntax for converting a Sheet.row into a numpy.ndarray. Here's what I've tried so far: import xlrd workbook = xlrd.open_workbook('input.xlsx') worksheet = workbook.sheet_by_name('Sheet1') num_rows = worksheet.nrows - 1 num_cells = worksheet.ncols - 1 inputData = numpy.empty([worksheet.nrows - 1, worksheet.ncols]) curr_row = -1 while curr_row < num_rows: # for each row curr_row += 1 row = worksheet.row(curr_row) if curr_row > 0: # don't want the first row because those are labels inputData[curr_row - 1] = numpy.array(row) I've tried all sorts of things on that last line to try to convert the row to something numpy will accept and add to the inputData matrix. What is the correct conversion syntax? Answer: I am wondering if you are aware of the Pandas library which features xlsx loading: import pandas as pd df = pd.read_excel('input.xlsx') You can control which sheet to read with `sheetname` argument and you can get Numpy array from the Pandas DataFrame in the `values` attribute.
arduino turning on/off led using pySerial Question: I am trying to communicate between arduino and pySerial but the serial monitor is giving me back weird characters so the arduino is not turning on/off led like it should. Thanks in advance. Arduino code int ledpin = 13; int state; // 0 = led off, 1 = led on int flag = 0; // used so msg is only printed once char val; void setup(){ pinMode(ledpin, OUTPUT); digitalWrite(ledpin, LOW); Serial.begin(9600); } void loop(){ //if data sent, read and save if(Serial.available() > 0){ state = Serial.read() -'0'; val = char(state); Serial.println(val); flag = 0; } //if state = 0 if (val == '0'){ digitalWrite(ledpin, LOW); if(flag = 0){ Serial.println('LED : Off'); flag = 1; } } //if state = 1 if (val = '1'){ digitalWrite(ledpin,HIGH); if(flag = 0){ Serial.println('LED : On'); flag = 1; } } } Python code import serial from tkinter import * port = '/dev/ttyACM0' speed = 9600 def send_command(val): connection = serial.Serial(port,speed) connection.write(b"val") connection.close() #Create the window win = Tk() #Modify the root window win.title("Arduino system") # gives title to window win.geometry("320x100") # sets the size of the window #Creating components f = Frame(win) # creates window #label with text l = Label(win , text = "Flash LED") b1 = Button(f, text ="Send 0") b2 = Button(f, text ="Send 1") #Defining methods def but1(): send_command('0') # command run if button 1 pressed def but2(): send_command('1') # command run if button 1 pressed b1.configure(command = but1) # assiging methods to buttons b2.configure(command = but2) # assiging methods to buttons #Adding Components l.pack() #packs in the label b1.pack(side = LEFT) #packs the buttons in one after the other b2.pack(side = LEFT) #packs the buttons in one after the other f.pack() win.mainloop() # start Gui after sending a 0 from python to arduino the following appears on the serial monitor F 1 < after sending a 1 the same thing appears Answer: The piece of code: state = Serial.read() -'0'; val = char(state); Serial.println(val); will print a `(char) 0` instead of a `'0'` and a `(char) 1` instead of `'1'`. Also you compare val with character constants as if it was a character. However your code converts it to integer values that you store in a character. → You should make up your mind about what types your variables are and what you store in them. In addition Serial.println('LED : Off'); and Serial.println('LED : On'); should most probably use `"` instad of `'` quotation marks.
Python time delay Question: Alright, I want to know how to delay a portion of a program without pausing the entire program. I'm not necessarily good at python so if you could give me a relatively simple answer if possible, that would be great. I want to have a turtle draw a circle on screen every time this function is called, this is what I have: import time from random import randint turtle5 = turtle.Turtle() coinx = randint(-200, 200) coiny = randint(-200, 200) turtle5.pu() turtle5.goto(coinx, coiny) turtle5.pd() turtle5.begin_fill() turtle5.fillcolor("Gold") turtle5.circle(5, 360, 8) turtle5.end_fill() time.sleep(1) turtle5.clear() Answer: You need to put the part of the program you want to delay in its own thread, and then call sleep() in that thread. I am not sure exactly what you are trying to do in your example, so here is a simple example: import time import threading def print_time(msg): print 'The time %s is: %s.' % (msg, time.ctime(time.time())) class Wait(threading.Thread): def __init__(self, seconds): super(Wait, self).__init__() self.seconds = seconds def run(self): time.sleep(self.seconds) print_time('after waiting %d seconds' % self.seconds) if __name__ == '__main__': wait_thread = Wait(5) wait_thread.start() print_time('now') Output: The time now is: Mon Jan 12 01:57:59 2015. The time after waiting 5 seconds is: Mon Jan 12 01:58:04 2015. Notice that we started the thread that will wait 5 seconds first, but it did not block the print_time('now') call, rather it waited in the background. **EDIT:** From J.F. Sebastian's comment, the simpler solution with threading is: import time import threading def print_time(msg): print 'The time %s is: %s.' % (msg, time.ctime(time.time())) if __name__ == '__main__': t = threading.Timer(5, print_time, args = ['after 5 seconds']) t.start() print_time('now')
Memory consumption of python ESL Question: I have written a ESL server, which controls call flow on FreeSWITCH server. The problem is that after the connection closes, the memory consumption does not decrease to normal. After some hundred connections are made to the server, its memory consumption goes to GBs and it has to be killed forcefully. I have pinpointed the issue to be of ESLconnection object. I have tried deleting the object and its instances using del, but to no avail. The code is as below: ivrServer.py import SocketServer from ESL import * import importlib import sys import threading import traceback import signal import time class ESLRequestHandler(SocketServer.BaseRequestHandler): #svr_ivr_log = None def setup(self): fd = self.request.fileno() self.con = ESLconnection(fd) self.svr_ivr_log.info("Client connected: %s" % str(self.client_address)) def handle(self): ivr_script = importlib.import_module('script') ivr_script = reload(ivr_script) ivr_script.process(self.con) def finish(self): self.con.disconnect() ESLRequestHandler.svr_ivr_log = logging('server') SocketServer.ThreadingTCPServer.allow_reuse_address = True server = SocketServer.ThreadingTCPServer(('', 9090), ESLRequestHandler) server.serve_forever() script.py: def process(con): info = con.getInfo() uuid = info.getHeader('unique-id') con.execute('hangup', "NORMAL_CLEARING", uuid) This would require ESL module of freeswitch compiled for your linux version. Let me know if I need to explain the procedure to do that. Python2.7 is being used here. Answer: From [SocketServer doc](https://docs.python.org/2/library/socketserver.html?highlight=tcpserver): > ...A new instance is created for each request. Each request creates a new `ESLRequestHandler` instance. In your `setup()`, you make a connection to the FreeSWITCH server, but you never close it after you finish handling the request. I suspect this is the source of the memory leak. To close the connection to the FreeSWITCH server you do something along the lines of: class ESLRequestHandler(SocketServer.BaseRequestHandler): #svr_ivr_log = None def setup(self): fd = self.request.fileno() self.con = ESLconnection(fd) self.svr_ivr_log.info("Client connected: %s" % str(self.client_address)) def handle(self): pass # your code for interacting with the FreeSWITCH server here def finish(self): self.con.disconnect() # close the connection
Python SyntaxError: invalid syntax elif statement Question: So I am pretty new to python, I am familiar with Java, C and Ruby. I tried compiling a script for Kali to fix the RFkill issue for wifi devices since Kali does not have an RFKill. #!/usr/bin/python # replacement for rfkill util, which is missing in kali # By: Geist from sys import argv if(argv[1] == "unblock"): x = open("/sys/class/rfkill/rfkill%s/soft" % argv[2], "w") x.seek(0) x.write('0') elif(argv[1] == "block"): x = open("/sys/class/rfkill/rfkill%s/soft" % argv[2], "w") x.seek(0) x.write('1') print("interface %s %sed" % (argv[2], argv[1])) I did not write this but I am trying to run it and I keep getting a SyntaxError: invalid syntax under elif(argv[1] == "block"): I am assuming this has something to do with improper indentation, if anyone could be as kind to let me know what I am doing wrong and why that would be great! Answer: **Indentation matters in Python**. You have unindented lines between your `if` block and your `elif` block. These will cause a SyntaxError because you've effectively got an `elif` block _without an`if` block._ Either indent your lines so they match the `if` block, or use a second `if` statement rather than `elif`. Looking at your code, I'd imagine you'll want to indent them otherwise you would get NameErrors. In this case it becomes: #!/usr/bin/python # replacement for rfkill util, which is missing in kali # By: Geist from sys import argv if(argv[1] == "unblock"): x = open("/sys/class/rfkill/rfkill%s/soft" % argv[2], "w") x.seek(0) x.write('0') elif(argv[1] == "block"): x = open("/sys/class/rfkill/rfkill%s/soft" % argv[2], "w") x.seek(0) x.write('1') print("interface %s %sed" % (argv[2], argv[1]))
How to use python script to automate software installation Question: I am new to Python. I want to automate the software installation process. The scenario is as follow > Run the installation file. On first screen it has two buttons next, cancel. > On click of next it goes to next screen having two buttons, next, cancel and > some input data is required. After details are provided, it will show finish > or cancel button. > In this I want to write python script that would automate this activity. It should identify the button click it, should enter the data wherever required and finish the installation. To achieve this functionality 1. Python API is required, if any? 2. Some code samples or link of the tutorials to use the same. [Sample image for referance](http://i.stack.imgur.com/WLyqh.jpg) Thank you!! Answer: As Rawing mentioned, pywinauto is good choice for Windows installer. Here is nice sample video: <http://pywinauto.github.io/> For waiting next page use something like that: `app.WizardPageTitle.Wait('ready')` When installer finished: `app.FinishPage.WaitNot('visible')` For edit box input: `app.WizardPage.Edit.TypeKeys('some input path', with_spaces=True)` For button clicks I'd recommend `ClickInput()` as more reliable method. If you want to install the app on many machines automatically, you can create Remote Desktop or VNC session and run local copy of the Python script inside that session. Just do not minimize RDP or VNC window to prevent GUI context loss. Losing focus is safe and you can continue your work on master machine in another window without affecting remote installation. Example of easy install script for FastStone Image Viewer 4.6: import os from pywinauto.application import Application as app fsv = app.Start("FSViewerSetup46.exe") fsv.InstallDialog.NextButton.Wait('ready', timeout=30).ClickInput() fsv.InstallDialog.IAgreeRadioButton.Wait('ready', timeout=30).ClickInput() fsv.InstallDialog.Edit.Wait('ready', timeout=30).TypeKeys(os.getcwd() + "\FastStone Image Viewer", with_spaces=True) fsv.InstallDialog.InstallButton.Wait('ready', timeout=30).ClickInput() fsv.InstallDialog.FinishButton.Wait('ready', timeout=30).ClickInput()
Checking for particular style using python-docx Question: from docx import * document = Document('ABC.docx') for paragraph in document.paragraphs: for run in paragraph.runs: if run.style == 'Strong': print run.text This is the code I am using to open a docx file and to check if there is Bold text but I am not getting any result. If I remove the if statement , the entire file is printed without any formatting / styles. Can you please let me know how to identify text in particular style like Bold or Italics using python-docx ? Thank you Answer: Although _bold_ and the style _Strong_ appear the same when rendered, they use two different mechanisms. The first applies bold directly and the second applies a character style that can include any other number of font characteristics. To identify all occurrences of text that _appears_ bold, you may need to do both. But to just find the text having bold applied you would do something like this: for paragraph in document.paragraphs: for run in paragraph.runs: if run.bold: print run.text Note there are ways this can miss text that appears bold, like text that appears in a paragraph whose font formatting is bold for the entire paragraph (Heading1 for example). But I think this is the property you were looking for.
Trac - Problems upgrading from 0.12.5 to 1.0.1 Question: I've been trying to upgrade our trac environment from 0.12.5 to 1.0.1 on debian squeeze. I updated it using wheezy backports. After I installed the new version using apt-get I ran the following: trac-admin /var/lib/trac upgrade trac-admin /var/lib/trac wiki upgrade When I opened trac in my browser I got the following errors: Trac[env] WARNING: base_url option not set in configuration, generated links may be incorrect Trac[loader] ERROR: Skipping "trac.wiki.admin = trac.wiki.admin": (can't import "ImportError: No module named admin") Trac[loader] ERROR: Skipping "tracopt.ticket.commit_updater = tracopt.ticket.commit_updater": (can't import "ImportError: cannot import name cleandoc_") Trac[loader] ERROR: Skipping "tracopt.versioncontrol.svn.svn_fs = tracopt.versioncontrol.svn.svn_fs": (can't import "ImportError: cannot import name ChoiceOption") Trac[loader] ERROR: Skipping "tracopt.ticket.clone = tracopt.ticket.clone": (can't import "ImportError: cannot import name captioned_button") Trac[loader] ERROR: Skipping "tracopt.ticket.deleter = tracopt.ticket.deleter": (can't import "ImportError: cannot import name from_utimestamp") Trac[loader] ERROR: Skipping "trac.wiki.web_api = trac.wiki.web_api": (can't import "ImportError: No module named web_api") Trac[loader] ERROR: Skipping "trac.versioncontrol.admin = trac.versioncontrol.admin": (can't import "ImportError: No module named admin") Trac[loader] ERROR: Skipping "trac.ticket.batch = trac.ticket.batch": (can't import "ImportError: No module named batch") Trac[loader] ERROR: Skipping "tracopt.perm.config_perm_provider = tracopt.perm.config_perm_provider": (can't import "ImportError: cannot import name ConfigSection") Trac[loader] ERROR: Failed to load plugin from /var/lib/trac/plugins/setup.py: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/trac/loader.py", line 91, in _load_py_files As I can see I have the following plugins installed if it helps: TracHierWiki TracXMLRPC Answer: As I see it, the line > Failed to load plugin from /var/lib/trac/plugins/setup.py means, that there is not properly packaged multi-file Trac plugin source code (`setup.py` file) in the `/plugin` directory of your Trac environment, that must not be there. This situation has been recently discussed in Trac ticket [#11846](http://trac.edgewall.org/ticket/11846) for a solution in upstream Trac development.
Lock process until subprocess reaches a certain point Question: I am running multiple subprocesses in parallel, but I need to lock each process until the subprocess gives an output (via print function). The subprocesses are running a python script that has been packaged to an executable. The code looks like this: import multiprocessing as mp import subprocess import os def main(args): l,inpath = args l.acquire() print "Running KNN.exe for files in %s" % os.path.normpath(inpath).split('\\')[-1] #Run KNN executable as a subprocess subprocess.call(os.path.join(os.getcwd(), "KNN.exe")) #This is where I want to wait for any output from the subprocess before releasing the lock l.release() #Here I would like to wait until subprocess is done then print that it is done l.acquire() print "Done %s" % os.path.normpath(inpath).split('\\')[-1] l.release() if __name__ == "__main__": #Set working directory path containing input text file os.chdir("C:\Users\Patrick\Google Drive\KNN") #Get folder names in directory containing GCM input manager = mp.Manager() l = manager.Lock() gcm_dir = "F:\FIDS_GCM_Data_CMIP5\UTRB\UTRB KNN-CAD\Input" paths = [(l, os.path.join(gcm_dir, folder)) for folder in os.listdir(gcm_dir)] #Set up multiprocessing pool p = mp.Pool(mp.cpu_count()) #Map function through input paths p.map(main, paths) So the goal is to lock the process so that a subprocess can be run until receiving an output. After which the lock can be released and the subprocess can continue, until it is complete, then I'd like to print that it is complete. My question is how can I wait for the single (and only) output from the subprocess before releasing the lock on the process (out of multiple)? Additionally how can I wait for the process to terminate then print that it is complete? Answer: Your code makes use of the `call` method, which already waits for the subprocess to finish (which means all output has already been generated). I'm inferring from your question you'd like to be able to differentiate between when output is first written and when the subprocess is finished. Below is your code with my recommended modifications inline: def main(args): l,inpath = args l.acquire() print "Running KNN.exe for files in %s" % os.path.normpath(inpath).split('\\')[-1] #Run KNN executable as a subprocess #Use the Popen constructor proc = subprocess.Popen(os.path.join(os.getcwd(), "KNN.exe"), stdout=subprocess.PIPE) #This is where I want to wait for any output from the subprocess before releasing the lock # Wait until the subprocess has written at least 1 byte to STDOUT (modify if you need different logic) proc.stdout.read(1) l.release() #Here I would like to wait until subprocess is done then print that it is done #proc.wait() (proc_output, proc_error) = proc.communicate() l.acquire() print "Done %s" % os.path.normpath(inpath).split('\\')[-1] l.release() Note that the above doesn't assume you want to do anything with the subprocess's output other than check that it has been generated. If you want to do anything with that output that is less trivial than the above (consume 1 byte then drop it on the floor), the `proc.stdout` (which is a `file` object) should represent everything that the subprocess generates while running.
How to make Menu.add_command() work in tkinter on the Mac? Question: If I create a tkinter menu on OS X and try to add a menu button to it with `add_comand()`, nothing shows up in the menu. If the code below is run on Ubuntu, I get a menubar with two commands labeled "Red" and "Blue" that change the background color of the window. On OS X 10.10.1 (Yosemite) the buttons do not appear. I know I can make a dropdown menu with the Red and Blue commands, but in my real app, I'd prefer not to do that. from platform import python_version_tuple major = python_version_tuple()[0] if major == '3': import tkinter as tk else: import Tkinter as tk root = tk.Tk() fr = tk.Frame(root, height = 200, width = 200) fr.pack() menu = tk.Menu(root) root.configure(menu=menu) menu.add_command(label='Red', command=lambda:fr.configure(bg='red')) menu.add_command(label='Blue', command=lambda:fr.configure(bg='blue')) root.mainloop() Can you tell me how to do what I want? Answer: I don't think you can do that with the native ("Aqua") Tk on OS X and you probably shouldn't try. OS X native menus don't work like that and Tk tries to follow Apple's [Human Interface Guide for menus](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/OSXHIGuidelines/MenuAppearanceBehavior.html#//apple_ref/doc/uid/20000957-CH23-SW1). You need to have a menu bar with dropdown _cascades_. The `TkDocs` website has a good introduction to [Tk menus and their platform differences.](http://www.tkdocs.com/tutorial/menus.html) (You _could_ use an X11-based Tk on OS X, but that is not recommended as Apple does not ship X11 servers anymore with OS X and your app would look and behave oddly for OS X users.)
How to create custom elements styled like material design? Question: I love material design. I love jquery, web forms and elements. It have many styles. But when i use PyQt i have default button and checkbox... I love something like this: ![enter image description here](http://i.stack.imgur.com/7du9s.jpg) Can I change qt elements so that they become similar to the elements of web- forms? Tell me what to read or may have examples of how to do this already? I just do not know if this is possible because I do not know in which direction to look for ... i use qt4 and windows... and know only python, not C/C++ Answer: Start creating your own widgets and override the paintEvent I am putting in an example here that mostly summarizes what you need to know. The example shows the checkbox as an on/off button. from PyQt4 import QtGui, QtCore import sys #=============================================================================== # MyCheckBox #=============================================================================== #className class MyCheckBox(QtGui.QCheckBox): #|-----------------------------------------------------------------------------| # class Variables #|-----------------------------------------------------------------------------| #no classVariables #|-----------------------------------------------------------------------------| # Constructor #|-----------------------------------------------------------------------------| def __init__(self, *args, **kwargs): QtGui.QCheckBox.__init__(self, *args, **kwargs) self.setStyleSheet("background-color: rgb(0, 0, 0);\n" + "color: rgb(255, 255, 255);\n") #set default check as True self.setChecked(True) #set default enable as True # if it set to false will always remain on/off # here it is on as setChecked is True self.setEnabled(True) self._enable = True #|--------------------------End of Constructor---------------------------------| #|-----------------------------------------------------------------------------| # mousePressEvent #|-----------------------------------------------------------------------------| #overrite def mousePressEvent(self, *args, **kwargs): #tick on and off set here if self.isChecked(): self.setChecked(False) else: self.setChecked(True) return QtGui.QCheckBox.mousePressEvent(self, *args, **kwargs) #|--------------------------End of mousePressEvent-----------------------------| #|-----------------------------------------------------------------------------| # paintEvent #|-----------------------------------------------------------------------------| def paintEvent(self,event): #just setting some size aspects self.setMinimumHeight(40) self.setMinimumWidth(100) self.setMaximumHeight(50) self.setMaximumWidth(150) self.resize(self.parent().width(),self.parent().height()) painter = QtGui.QPainter() painter.begin(self) #for the black background brush = QtGui.QBrush(QtGui.QColor(0,0,0),style=QtCore.Qt.SolidPattern) painter.fillRect(self.rect(),brush) #smooth curves painter.setRenderHint(QtGui.QPainter.Antialiasing) #for the on off font font = QtGui.QFont() font.setFamily("Courier New") font.setPixelSize(28) painter.setFont(font) #change the look for on/off if self.isChecked(): #blue fill brush = QtGui.QBrush(QtGui.QColor(50,50,255),style=QtCore.Qt.SolidPattern) painter.setBrush(brush) #rounded rectangle as a whole painter.drawRoundedRect(0,0,self.width()-2,self.height()-2, \ self.height()/2,self.height()/2) #white circle/button instead of the tick mark brush = QtGui.QBrush(QtGui.QColor(255,255,255),style=QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.drawEllipse(self.width()-self.height(),0,self.height(),self.height()) #on text painter.drawText(self.width()/4,self.height()/1.5, "On") else: #gray fill brush = QtGui.QBrush(QtGui.QColor(50,50,50),style=QtCore.Qt.SolidPattern) painter.setBrush(brush) #rounded rectangle as a whole painter.drawRoundedRect(0,0,self.width()-2,self.height()-2, \ self.height()/2,self.height()/2) #white circle/button instead of the tick but in different location brush = QtGui.QBrush(QtGui.QColor(255,255,255),style=QtCore.Qt.SolidPattern) painter.setBrush(brush) painter.drawEllipse(0,0,self.height(),self.height()) #off text painter.drawText(self.width()/2,self.height()/1.5, "Off") #|-----------------------End of paintEvent-------------------------------------| if __name__ == '__main__': app = QtGui.QApplication(sys.argv) wgt = QtGui.QWidget() wgt.setStyleSheet("background-color: rgb(0, 0, 0);\n") cb = MyCheckBox() cb.setParent(wgt) layout = QtGui.QHBoxLayout() layout.addWidget(cb) wgt.resize(200,100) wgt.show() sys.exit(app.exec_()) # EDIT: Attaching screen-shots for how it looks ![enter image description here](http://i.stack.imgur.com/uwnJP.png) ![enter image description here](http://i.stack.imgur.com/msgy6.png)
Can you specify a command to run after you embed into IPython? Question: When calling IPython.embed() is it possible to give it a command or magic function to run after embeding happens. I would like to run something like this import IPython IPython.embed(command='%pylab qt4') My current workaround is to copy the command string to the clipboard, spawn a background thread which sends keystrokes %paste followed by enter to the current window. This works ok on linux, but it is very hacky and I can't get it working as well on Windows. It seems like it should be possible to specify this, but I've never grasped how the IPython configs are working or what arguments to embed are used for. Answer: The document stated that `IPython.start_ipython` reads the configuration file, while `IPython.embed` does not. With that in mind, let's use the former: import IPython c = IPython.Config() c.InteractiveShellApp.exec_lines = [ '%pylab qt4', "print 'System Ready!'", ] IPython.start_ipython(config=c) # Update I am not sure what you meant by _to keep the current namespace_. If you meant local/global variables: IPython.start_ipython(config=c, user_ns=locals()) # Pass in local variables IPython.start_ipython(config=c, user_ns=globals()) # Pass in global variables
Appending CSV files, matching unordered columns Question: Problem: matching columns while appending CSV files I have 50 .csv files where each column is a word, each row is a time of day and each file holds all words for one day. They look like this: Date Time Aword Bword Cword Dword Date1 t1 0 1 0 12 Date1 t2 0 6 3 0 Date Time Eword Fword Gword Hword Bword Date2 t1 0 0 1 0 3 Date2 t2 2 0 0 19 0 I want to append the files so that any columns with the same word (like Bword in this example) are matched while new words are added in new columns: Date Time Aword Bword Cword Dword Eword Fword Gword Hword Date1 t1 0 1 0 12 Date1 t2 0 6 3 0 Date2 t1 3 0 0 1 0 Date2 t2 0 2 0 0 19 I'm opening the csv files as dataframes to manipulate them and using dataframe.append the new files are added like this: Date Time Aword Bword Cword Dword Date1 t1 0 1 0 12 Date1 t2 0 6 3 0 Date Time Eword Fword Gword Hword Bword Date2 t1 0 0 1 0 3 Dat2e t2 2 0 0 19 0 Is there a different approach which could align matching columns while appending? ie without iterating through each column and checking for matches. _Sincere apologies if this question is too vague, I'm new to python and still struggling to know when I'm thinking un-pythonically and when I'm using the wrong tools._ EDIT: more information 1) I'll need to perform this task multiple times, once for each of five batches of csvs 2) The files all have 25 rows but have anything from 5 to 294 columns 3) The order of rows is important Day1(t1, t2...tn) then Day2(t1, t2...tn) 4) The order of columns is not important Answer: I think for this kind of thing you might find using the pandas library a bit easier. Say `filelist` is a list of file names. import pandas as pd df = pd.concat([pd.read_csv(fl, index_col=[0,1]) for fl in filelist]) And you're done! As a side note if you'd like to combine the date and time columns (depending on their format) you can try df = pd.concat([pd.read_csv(fl, parse_dates=['Date','Time']) for fl in filelist]).drop('Date', axis=1)
How to set the background color of a ttk.Combobox Question: I have a problem to set background color for Combobox using tkinter ttk with 'vista' theme (I'm using Python 3). I've tried code from here [ttk.Combobox glitch when state is read-only and out of focus](http://stackoverflow.com/questions/18610519/ttk-combobox-glitch-when- state-is-read-only-and-out-of-focus) import tkinter as tk from tkinter import ttk root = tk.Tk() combo = ttk.Combobox(root, values=['1', '2', '3']) combo['state'] = 'readonly' combo.pack() tk.Entry(root).pack() style = ttk.Style() style.map('TCombobox', selectbackground=[('readonly', 'red')]) #style.map('TCombobox', fieldbackground=[('readonly', 'blue')]) #not working as well But this will change only background for text, rest part of combobox rests white. Also I saw a post on the tcl forum: <http://wiki.tcl.tk/15780> and I've tried with 'fieldbackground' but it seems that tkinter ignores this parameter. Do you have any idea how to solve it? Maybe there is a way to configure only specific style in specific theme? I saw that for 'default' theme, the background changes to gray color if state is 'readonly'. Answer: This code below worked fine for me.It is important set the order of the parameters. ` style = ttk.Style() style.map('TCombobox', fieldbackground=[('readonly','white')]) style.map('TCombobox', selectbackground=[('readonly', 'white')]) style.map('TCombobox', selectforeground=[('readonly', 'black')]) self.mycombo = ttk.Combobox(self.frame,textvariable=self.combo_var, height=15,justify='left',width=21, values=lista) self.mycombo['state'] = 'readonly' # Set the state according to configure colors self.mycombo.bind('<<ComboboxSelected>>', lambda event: self._click_combo()) `
pythonic way to customize classes Question: I am trying to figure out a clean way to use inheritance for custom classes. I have the following directory structure. inheritTest.py Level1 __init__.py t_Generic.py Level2 __init__.py t_Custom.py **Goal:** I want all the classes of t_Generic accessible by importing t_Custom module and allow needed customization in t_Custom. There is nothing in two of the **init**.py files above. t_Generic.py contains some generic classes like these: class A(object): def __init__(self): self.hello = "Hello! I am Mr.A from t_generic" def someOtherMethod(self): pass class B(object): def __init__(self): self.hello = "Hello! I am Mr.B from t_generic" def someOtherMethod(self): pass class C(object): def __init__(self): self.hello = "Hello! I am Mr.C from t_generic" def changeHello(self): pass Experimental t_Custom.py is as below: import Level1.t_Generic #Override any Generic classes in this module. #Option 1: Let's get Generic A so it lives in this scope as A from Level1.t_Generic import A #Option 2: Let's create B and inherit from Generic, make future custom changes here class B(Level1.t_Generic.B): def __init__(self): super(B,self).__init__() #I really want to inherit from C and change it's behavior class C(Level1.t_Generic.C): def __init__(self): super(C,self).__init__() def changeHello(self): self.hello = "Hello! I am Mr.C modified in t_Custom" **Question:** What's the pythonic way to do something like this? Should I just import all the generic classes in Custom module as in option 1 or should I create an inherited class in Custom as in Option 2 and modify the ones I want to inherit from? Example use case in inheritTest.py: import Level2.t_Custom a = Level2.t_Custom.A() b = Level2.t_Custom.B() c = Level2.t_Custom.C() print a.hello print b.hello print c.hello c.changeHello() print c.hello output: Hello! I am Mr.A from t_generic Hello! I am Mr.B from t_generic Hello! I am Mr.C from t_generic Hello! I am Mr.C modified in t_Custom Answer: _I haven't tested this, but I think it should do what you want. Consider it whiteboard code_ First, you need to use relative imports in t_Custom.py then import the generic classes from ..Level1 import t_Generic from t_Generic import A as GenericA from t_Generic import B as GenericB from t_Generic import C as GenericC I rename the classes to avoid any clashes in your module's namespace. Now, to get your desired output, in t_Custom.py (copying your original code) A = GenericA # Just re-export the generic A class class B(GenericB): def __init__(self): super(B,self).__init__() #I really want to inherit from C and change it's behavior class C(GenericC): def __init__(self): super(C,self).__init__() def changeHello(self): self.hello = "Hello! I am Mr.C modified in t_Custom" and then, to try and avoid exporting t_Generic.A etc from your module __all__ = ["A","B","C"] As Alex mentioned in his comment, it is generally considered a "Bad Thing" (TM) to pointlessly override a method of a base class. Only do that if you want to modify or add behavior. Then t_Custom.py becomes more like this: from ..Level1 import t_Generic from t_Generic import A as GenericA from t_Generic import B as GenericB from t_Generic import C as GenericC A = GenericA # Just re-export the generic A class B = GenericB # I'll subclass when I know what I want to do to it #I really want to inherit from C and change it's behavior class C(GenericC): def changeHello(self): self.hello = "Hello! I am Mr.C modified in t_Custom" __all__ = ["A","B","C"]
How to get the content of a tkinter Text object Question: I'm trying to use `tkinter.Text` to create a text area in _Python_. With that, I want to get all the input they put into that text area and display it in the Entry field above it. It gives an error saying it needs two arguments. from Tkinter import * def create_index(): var = body.get(0) link.insert(10,var) file.close() master = Tk() Label(master, text="Link:").grid(row=0) Label(master, text="Body:").grid(row=1) link = Entry(master) body = Text(master) link.grid(row=0, column=1) body.grid(row=1, column=1) Button(master, text='Show', command=create_index).grid(row=3, column=1, sticky=W, pady=4) mainloop() Answer: To get all the input from a `tkinter.Text`, you should use the method `get` from the `tkinter.Text` object you are using to represent the text area. In your case, `body` should be the variable of type `tkinter.Text`, so here's an example: text = body.get(1.0, "end-1c") `tkinter.Text` objects count their content as rows and columns. The `1.0` indicates exactly that: you want to get the content starting from row 1 and column 0 (this is the default starting point of a `tkinter.Text` object). Here's a complete working example, where basically on the click of a button, the method `get_text` is called and adds the content of `body` to an `tkinter.Entry` object that I called `entry` (through the use of a variable of type `tkinter.StringVar`. See documentation for more information): import tkinter def get_text(): content = body.get(1.0, "end-1c") entry_content.set(content) master = tkinter.Tk() body = tkinter.Text(master) body.pack() entry_content = tkinter.StringVar() entry = tkinter.Entry(master, textvariable=entry_content) entry.pack() button = tkinter.Button(master, text="Get tkinter.Text content", command=get_text) button.pack() master.mainloop() For another good example, see this other [post](http://stackoverflow.com/questions/5560828/how-to-read-text-from-a- tkinter-text-widget) and the first comment below.
Python pandas idxmax for multiple indexes in a dataframe Question: I have a series that looks like this: delivery 2007-04-26 706 23 2007-04-27 705 10 706 1089 708 83 710 13 712 51 802 4 806 1 812 3 2007-04-29 706 39 708 4 712 1 2007-04-30 705 3 706 1016 707 2 ... 2014-11-04 1412 53 1501 1 1502 1 1512 1 2014-11-05 1411 47 1412 1334 1501 40 1502 433 1504 126 1506 100 1508 7 1510 6 1512 51 1604 1 1612 5 Length: 26255, dtype: int64 where the query is: `df.groupby([df.index.date, 'delivery']).size()` For each day, I need to pull out the delivery number which has the most volume. I feel like it would be something like: df.groupby([df.index.date, 'delivery']).size().idxmax(axis=1) However, this just returns me the idxmax for the entire dataframe; instead, I need the second-level idmax (not the date but rather the delivery number) for each day, not the entire dataframe (ie. it returns a vector). Any ideas on how to accomplish this? Answer: Suppose you have this series: delivery 2001-01-02 0 2 1 3 6 2 7 2 9 3 2001-01-03 3 2 6 1 7 1 8 3 9 1 dtype: int64 If you want _one delivery_ per date with the maximum value, you could use `idxmax`: dates = series.index.get_level_values(0) series.loc[series.groupby(dates).idxmax()] yields delivery 2001-01-02 1 3 2001-01-03 8 3 dtype: int64 If you want _all deliveries_ per date with the maximum value, [use `transform` to generate a boolean mask](http://stackoverflow.com/a/27868335/190597): mask = series.groupby(dates).transform(lambda x: x==x.max()).astype('bool') series.loc[mask] yields delivery 2001-01-02 1 3 9 3 2001-01-03 8 3 dtype: int64 * * * This is the code I used to generate `series`: import pandas as pd import numpy as np np.random.seed(1) N = 20 rng = pd.date_range('2001-01-02', periods=N//2, freq='4H') rng = np.random.choice(rng, N, replace=True) rng.sort() df = pd.DataFrame(np.random.randint(10, size=(N,)), columns=['delivery'], index=rng) series = df.groupby([df.index.date, 'delivery']).size()
pip install python-novaclient is failing due to netifaces.c Question: I'm trying to install OpenStack python novaclient using pip install python- novaclient This task fails: netifaces.c:185:6 #error You need to add code for your platform I have no idea what code it wants. Does anyone understand this? Answer: This has to do with the order that libraries are imported in the netifaces setup.py and is fixed in version 10.3+ (which you need to install from source). Here's how to install 10.4 (current latest release): mkdir -p /tmp/install/netifaces/ cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://pypi.python.org/packages/source/n/netifaces/netifaces-0.10.4.tar.gz#md5=36da76e2cfadd24cc7510c2c0012eb1e" tar xvzf netifaces-0.10.4.tar.gz cd netifaces-0.10.4 && python setup.py install
Creating a normalized histogram Question: I am working on a research paper published on Hair recognition from human face, in the research paper I am stuck at the following part: > We downsample each of Y,Cb and Cr channels into 64 levels.Then we can > construct a three-dimensional color histogram in which each dimension has 64 > bins. **We normalize the color histogram in order to approximate** **the > hair color likelihood distribution.** As far as I have understood this statement, I am given 3 different histograms and I have to create a new compiled histogram, Since I am not using MATLAB in my project so I need to find a way to normalize 3 different histograms into 1, I googled a lot but found nothing, Can somebody please help me on this. I need the formula or something like that to implement this, Preferable languages are : > python, C++ Answer: I doubt it is 3 histograms. It sounds more like you have a 3 dimensional array of 64x64x64 values of Y,Cb,Cr, where by each bucket (in that 3D array of buckets) is a count of how many people had that particular hair color. Normalizing is simply a matter of dividing each bucket by the total count (how many people you got color samples from). With that assumption the following code would work (I used 16 instead of 64): # Initialize 3D array to random counts import random cbucket = {} for y in range(0,16): for cb in range(0,16): for cr in range(0,16): cbucket[ y,cb,cr ] = float(round(random.uniform(0,10))) # Find total count tcount = 0 for y in range(0,16): for cb in range(0,16): for cr in range(0,16): tcount += cbucket[ y,cb,cr ] print("tcount: %6.2f " % tcount) # now normalize for y in range(0,16): for cb in range(0,16): for cr in range(0,16): cbucket[ y,cb,cr ] = cbucket[ y,cb,cr ]/tcount
No module named '_sqlite3' error Question: Python 2.6 and Django 1.6 was installed on the server (Suse). I installed Python 3.4 and Django 1.7. I can run > django-admin.py startproject hi Once I run any command related to manage.py like > python manage.py syncdb I will get this error File "/usr/local/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 33, in <module> from pysqlite2 import dbapi2 as Database ImportError: No module named 'pysqlite2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 35, in <module> from sqlite3 import dbapi2 as Database File "/usr/local/lib/python3.4/sqlite3/__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.4/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named '_sqlite3' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/usr/local/lib/python3.4/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.4/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/usr/local/lib/python3.4/site-packages/django/contrib/auth/models.py", line 40, in <module> class Permission(models.Model): File "/usr/local/lib/python3.4/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, **kwargs)) File "/usr/local/lib/python3.4/site-packages/django/db/models/base.py", line 297, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.4/site-packages/django/db/models/options.py", line 166, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/usr/local/lib/python3.4/site-packages/django/db/__init__.py", line 40, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python3.4/site-packages/django/db/utils.py", line 242, in __getitem__ backend = load_backend(db['ENGINE']) File "/usr/local/lib/python3.4/site-packages/django/db/utils.py", line 108, in load_backend return import_module('%s.base' % backend_name) File "/usr/local/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/usr/local/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 38, in <module> raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc) django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3' according to [Install pysqlite in virtualenv with python3 support](http://stackoverflow.com/questions/23181197/install-pysqlite-in- virtualenv-with-python3-support) There is no public version of pysqlite for Python 3.x. Also, I installed sqlite-autoconf-3080704. and still I get the same error message. how can I solve it? Answer: You seem to have only a minimum installation of Python 3. If you're using Debian or a Debian-based system like Ubuntu, you can do `apt-get install python3` to install the full version.
Can't start pyspark (DSE 4.6) Question: I've installed Datastax enterprise 4.6 in a cluster and I can't figure out why the pyspark throw this error. The scala interface works nicely but the python doesn't. Does anyone have a clue how to fix this? Python 2.6.6 Centos 6.5 Cheers bash-4.1$ dse pyspark --master spark://IP:7077 Python 2.6.6 (r266:84292, Jan 22 2014, 01:49:05) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last): File "/usr/share/dse/spark/python/pyspark/shell.py", line 33, in <module> import pyspark File "/usr/share/dse/spark/python/pyspark/__init__.py", line 63, in <module> from pyspark.context import SparkContext File "/usr/share/dse/spark/python/pyspark/context.py", line 34, in <module> from pyspark import rdd File "/usr/share/dse/spark/python/pyspark/rdd.py", line 1972 return {convertColumnValue(v) for v in columnValue} ^ SyntaxError: invalid syntax >>> Answer: The PySpark support included in DSE 4.6 requires Python 2.7.x and will throw that error you're seeing on Python 2.6.x. An upcoming patch release should fix the problem with Python 2.6.x. There is not a specific date yet.
getting p2p_device_address from wpa_cli status Question: Is there any way to get different information from the command "wpa_cli status", e.g., p2p_device_address, ssid etc. separately, ? What i am currently using is by calling wpa_cli from a python script: import subprocess cmd = "wpa_cli -i wlan3 status" p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) output = p.stdout.read() my output is printed out as: bssid=xx:xx:xx:xx:xx:xx ssid=lifa_2 id=0 mode=station pairwise_cipher=CCMP group_cipher=CCMP key_mgmt=WPA2-PSK wpa_state=COMPLETED ip_address=192.168.0.104 p2p_device_address=xx:xx:xx:xx:xx:xx address=xx:xx:xx:xx:xx:xx uuid=xxxxx-xxxx-xxxx-xxxx-xxxxxxx what i want here is the p2p_device_address only, i.e output = p.stdout.read() # in this case ouput must be a string containing only the address what i am thinking of my self is to use str.split() and select line 9, and do some string manipulation to get the id, however that will be a hack, it will be much smother to let wpa_cli to return the address only, if there any? Answer: Try to use `pipe` in Linux: import subprocess cmd = "wpa_cli -i wlan3 status | grep ip_address" p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) output = p.stdout.read() Then you will get the only line with `ip_address`.
What DLL's I have to load for Gobject in cx_freeze Question: I have a little problem with cx_freeze and hoping one of you can help me. I have searched trough this wonderfull forum but I can't find the answer. I have used cx_freeze before with python 3.3 and ktinker and that worked flawless. Now I made a little tool with a bit more complex gui and tried Glade. Building the gui with Glade works perfect for me and on Linux and Windows 7 the application I have made works fine (in python interpreter). When I run `python setup.py bdist_msi` I don't see any faults but when I try to run the exe in windows I get this error window: (I can't post images jet) The last 4 lines are: _load_backward_compatible File "ExtentionLoader_gi_gi.py", line 22, in <module File "ExtentionLoader_gi_gi.py", line 14, in_bootstrap_ ImportError: DLL load failed: The specified module could not be found I don't use any plugins, exotic imports so the dll's I have to load are only the dll's for Gobject. The setup file I have made from an example on this forum. For my ktinker app I did not have to import any dll. Finally the question: Is there a list of dll's somewhere that tells me what dll's I have to add? And is there something wrong with my setup.py? The code is nothing special but if you want to check it: <https://github.com/EddenBeer/CodeGenerator> The imports in Python: import csv import sys import datetime from gi.repository import Gtk Installed on Windows 7: Python-3.4.2 cx_Freeze-4.3.3.win32-py3.4 pygi-aio-3.14.0_rev6-setup Setup.py: import os, site, sys from cx_Freeze import setup, Executable ## Get the site-package folder, not everybody will install ## Python into C:\PythonXX site_dir = site.getsitepackages()[1] include_dll_path = os.path.join(site_dir, "gnome") ## Collect the list of missing dll when cx_freeze builds the app missing_dll = ['libgtk-3-0.dll', 'libgdk-3-0.dll', 'libatk-1.0-0.dll', 'libcairo-gobject-2.dll', 'libgdk_pixbuf-2.0-0.dll', 'libjpeg-8.dll', 'libpango-1.0-0.dll', 'libpangocairo-1.0-0.dll', 'libpangoft2-1.0-0.dll', 'libpangowin32-1.0-0.dll', 'libgnutls-26.dll', 'libgcrypt-11.dll', 'libp11-kit-0.dll' ] ## We also need to add the glade folder, cx_freeze will walk ## into it and copy all the necessary files glade_folder = 'glade' ## We need to add all the libraries too (for themes, etc..) gtk_libs = ['etc', 'lib', 'share'] ## Create the list of includes as cx_freeze likes include_files = [] for dll in missing_dll: include_files.append((os.path.join(include_dll_path, dll), dll)) ## Let's add glade folder and files include_files.append((glade_folder, glade_folder)) ## Let's add gtk libraries folders and files for lib in gtk_libs: include_files.append((os.path.join(include_dll_path, lib), lib)) base = None ## Lets not open the console while running the app if sys.platform == "win32": base = "Win32GUI" executables = [ Executable("CodeGenerator.py", base=base ) ] buildOptions = dict( compressed = False, includes = ["gi", "csv", "datetime",], packages = ["gi"], include_files = include_files ) setup( name = "Code Generator", author = "Ed den Beer", version = "1.0", description = "Generating copy instructions for RsLogix5000 out of a list with tags in a CSV file", options = dict(build_exe = buildOptions), executables = executables ) Answer: My problem is solved. Looking for an answer if found a utility called ListDlls.exe. In this link is explaned how to use it: <https://bitbucket.org/anthony_tuininga/cx_freeze/issue/92/pygi-and-cx_freeze- error>
Python can't import my package Question: I have the following directory structure: myapp ├── a │   ├── amodule.py │   └── __init__.py ├── b │   ├── bmodule.py │   ├── __init__.py └── __init__.py In `a/amodule.py` I have this snippet which calls a simple function in `b/bmodule.py` from myapp.b import bmodule b.myfunc() But when i run `python a/amodule.py` I get this error: File "a/amodule.py", line 1, in <module> from myapp.b import bmodule ImportError: No module named 'myapp' What am I doing wrong? Answer: you need to put your project root onto your python path you can set the PYTHONPATH environmental variable or you can alter `sys.path` before importing or you can use an IDE like pycharm that will do this kind of thing for you (although it will probably be `from b import blah`) there is likely other ways to resolve this issue as well watch out for circular imports ... (in python 3 you can also do relative imports... although I am not a big fan of this feature) from ..b import blah the best way to allow from myapp.b import whatever would be to edit your `.bashrc` file to always add your parent path to the PYTHONPATH export PYTHONPATH=$PYTHONPATH;/home/lee/Code now every time you log into the system python will treat your `Code` folder as a default place to look for import modules, regardless of where the file is executed from
Taking form button input Question: So i'm using Flask to build a basic control panel for an IR Automation in my home. However I'm failing to understand how to take a response from the form in my HTML. So I basically have a button that changes the state of a device when pressed. The issue I'm having is taking that response and updating it on the HTML page to say it's on or off. My python flask code: if request.method == 'POST': if request.form['lamp'] == 'on': btn1 = True s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) s.send(MSG.encode()) data = str(s.recv(BUFFER).decode()) print(data) s.close() elif request.form['lamp'] == 'off': btn1 = False s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) s.send(MSG.encode()) data = str(s.recv(BUFFER).decode()) print(data) s.close() And the HTML part it works with: <form method=post> {% if btn1 == True %} <button type=submit class="btn btn-default" name="lamp" value="on"><i class="fa fa-lightbulb-o fa-5x" style="color:yellow;"></i><br>Lamp</button> {{ btn1 }} {% else %} <button type=submit class="btn btn-default" name="lamp" value="off"><i class="fa fa-lightbulb-o fa-5x"></i><br>Lamp</button> {{ btn1 }} {% endif %} </form> Why isn't btn1's state changing when I click it? Thanks, James Answer: really you should probably just be using json calls **flaskapp.py** from flask import Flask,render_template import json app = Flask(__name__) def load_data(flat_file): try: return json.load(open(flat_file)) except (IOError,ValueError): return {} db_file = "my_data.json" @app.route("/lamp/on") def lamp_on(): data = load_data(db_file) data["lamp"] = "on" json.dump(data,open(db_file,"wb")) return json.dumps(data) @app.route("/lamp/off") def lamp_off(): data = load_data(db_file) data["lamp"] = "off" json.dump(data,open(db_file,"wb")) return json.dumps(data) @app.route("/status") def status(): return load_data(db_file).get("lamp","off") @app.route("/") def main(): return render_template("template.html") if __name__ == "__main__": app.run(debug=True) this app will provide an api to turn on and off the light (obviously you will want to do more than just write to a file). as well as a visual dashboard at the "/" route **template.html** <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> </head> <body> <div id="content"> </div> </body> <script> function OnButton(){ var url = "/lamp/"+$("#lamp_btn").val().toLowerCase() $.get(url,update_button) } function update_button(){ $.get("/status",function($data){ var next_state = $data == "off"? "On":"Off" var button = $('<button id="lamp_btn" value="'+next_state+'">Turn Lamp '+next_state+'</button>') button.click(OnButton); $("#content").html(button) }); } update_button(); </script> this is the dashboard it just uses json calls to the api and updates just the button (but you could update much more... this is just a very simple example)
How can I install pip-accel on Ubuntu 14.10? Question: I would like to use [pip-accel](https://pypi.python.org/pypi/pip-accel) to speed up compilation-heavy installations to virtual environments (e.g. matplotlib, NumPy). It isn't in the 14.10 Ubuntu repos so I must install it manually. However, my installation attempt fails as follows: > pip install --user pip-accel Downloading/unpacking pip-accel Using download cache from /home/username/.cache/pip/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fp%2Fpip-accel%2Fpip-accel-0.22.2.tar.gz Running setup.py (path:/tmp/pip_build_username/pip-accel/setup.py) egg_info for package pip-accel Downloading/unpacking cached-property>=0.1.5 (from pip-accel) Using download cache from /home/username/.cache/pip/https%3A%2F%2Fpypi.python.org%2Fpackages%2F3.3%2Fc%2Fcached-property%2Fcached_property-0.1.5-py2.py3-none-any.whl Downloading/unpacking coloredlogs>=0.8 (from pip-accel) Using download cache from /home/username/.cache/pip/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fc%2Fcoloredlogs%2Fcoloredlogs-0.8.tar.gz Running setup.py (path:/tmp/pip_build_username/coloredlogs/setup.py) egg_info for package coloredlogs Downloading/unpacking humanfriendly>=1.14 (from pip-accel) Using download cache from /home/username/.cache/pip/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fh%2Fhumanfriendly%2Fhumanfriendly-1.14.tar.gz Running setup.py (path:/tmp/pip_build_username/humanfriendly/setup.py) egg_info for package humanfriendly Downloading/unpacking pip>=1.4,<1.5 (from pip-accel) Using download cache from /home/username/.cache/pip/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fp%2Fpip%2Fpip-1.4.1.tar.gz Running setup.py (path:/tmp/pip_build_username/pip/setup.py) egg_info for package pip warning: no files found matching '*.html' under directory 'docs' warning: no previously-included files matching '*.rst' found under directory 'docs/_build' no previously-included directories found matching 'docs/_build/_sources' Installing collected packages: pip-accel, cached-property, coloredlogs, humanfriendly, pip Running setup.py install for pip-accel Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip_build_username/pip-accel/setup.py", line 55, in <module> test_suite='pip_accel.tests') File "/usr/lib/python2.7/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/usr/lib/python2.7/dist-packages/setuptools/command/install.py", line 61, in run return orig.install.run(self) File "/usr/lib/python2.7/distutils/command/install.py", line 613, in run self.run_command(cmd_name) File "/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command self.distribution.run_command(command) File "/usr/lib/python2.7/distutils/dist.py", line 970, in run_command cmd_obj = self.get_command_obj(command) File "/usr/lib/python2.7/distutils/dist.py", line 845, in get_command_obj klass = self.get_command_class(command) File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 388, in get_command_class self.cmdclass[command] = cmdclass = ep.load() File "/usr/local/lib/python2.7/dist-packages/pkg_resources.py", line 2048, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/usr/lib/python2.7/dist-packages/setuptools/command/install_egg_info.py", line 5, in <module> from setuptools.archive_util import unpack_archive File "/usr/lib/python2.7/dist-packages/setuptools/archive_util.py", line 15, in <module> from pkg_resources import ensure_directory, ContextualZipFile ImportError: cannot import name ContextualZipFile Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_username/pip-accel/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-kD1BYu-record/install-record.txt --single-version-externally-managed --compile --user: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/utils.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/exceptions.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/config.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/req.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/compat.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/__init__.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/tests.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/bdist.py -> build/lib.linux-x86_64-2.7/pip_accel copying pip_accel/cli.py -> build/lib.linux-x86_64-2.7/pip_accel creating build/lib.linux-x86_64-2.7/pip_accel/caches copying pip_accel/caches/__init__.py -> build/lib.linux-x86_64-2.7/pip_accel/caches copying pip_accel/caches/local.py -> build/lib.linux-x86_64-2.7/pip_accel/caches copying pip_accel/caches/s3.py -> build/lib.linux-x86_64-2.7/pip_accel/caches creating build/lib.linux-x86_64-2.7/pip_accel/deps copying pip_accel/deps/__init__.py -> build/lib.linux-x86_64-2.7/pip_accel/deps copying pip_accel/deps/debian.ini -> build/lib.linux-x86_64-2.7/pip_accel/deps running install_lib copying build/lib.linux-x86_64-2.7/pip_accel/utils.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/exceptions.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/config.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/req.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/compat.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/__init__.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/tests.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/caches/__init__.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel/caches copying build/lib.linux-x86_64-2.7/pip_accel/caches/local.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel/caches copying build/lib.linux-x86_64-2.7/pip_accel/caches/s3.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel/caches copying build/lib.linux-x86_64-2.7/pip_accel/deps/debian.ini -> /home/username/.local/lib/python2.7/site-packages/pip_accel/deps copying build/lib.linux-x86_64-2.7/pip_accel/deps/__init__.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel/deps copying build/lib.linux-x86_64-2.7/pip_accel/bdist.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel copying build/lib.linux-x86_64-2.7/pip_accel/cli.py -> /home/username/.local/lib/python2.7/site-packages/pip_accel byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/utils.py to utils.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/exceptions.py to exceptions.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/config.py to config.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/req.py to req.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/compat.py to compat.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/__init__.py to __init__.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/tests.py to tests.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/caches/__init__.py to __init__.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/caches/local.py to local.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/caches/s3.py to s3.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/deps/__init__.py to __init__.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/bdist.py to bdist.pyc byte-compiling /home/username/.local/lib/python2.7/site-packages/pip_accel/cli.py to cli.pyc running install_egg_info Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip_build_username/pip-accel/setup.py", line 55, in <module> test_suite='pip_accel.tests') File "/usr/lib/python2.7/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/usr/lib/python2.7/dist-packages/setuptools/command/install.py", line 61, in run return orig.install.run(self) File "/usr/lib/python2.7/distutils/command/install.py", line 613, in run self.run_command(cmd_name) File "/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command self.distribution.run_command(command) File "/usr/lib/python2.7/distutils/dist.py", line 970, in run_command cmd_obj = self.get_command_obj(command) File "/usr/lib/python2.7/distutils/dist.py", line 845, in get_command_obj klass = self.get_command_class(command) File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 388, in get_command_class self.cmdclass[command] = cmdclass = ep.load() File "/usr/local/lib/python2.7/dist-packages/pkg_resources.py", line 2048, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/usr/lib/python2.7/dist-packages/setuptools/command/install_egg_info.py", line 5, in <module> from setuptools.archive_util import unpack_archive File "/usr/lib/python2.7/dist-packages/setuptools/archive_util.py", line 15, in <module> from pkg_resources import ensure_directory, ContextualZipFile ImportError: cannot import name ContextualZipFile ---------------------------------------- Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_username/pip-accel/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-kD1BYu-record/install-record.txt --single-version-externally-managed --compile --user failed with error code 1 in /tmp/pip_build_username/pip-accel Storing debug log for failure in /home/username/.pip/pip.log **Notes:** * I am using pip from the Ubuntu repos (`pip 1.5.6 from /usr/lib/python2.7/dist-packages (python 2.7)`) but it appears to be downloading it again (because it doesn't like 1.5.x?) * if there's another way to use pip-accel (e.g. install it into the target virtualenv) I'm all ears, but it doesn't seem like it Answer: I'm the author of pip-accel. I don't have an Ubuntu 14.10 system available for testing and on the Ubuntu 12.04 and 14.04 systems where I tested this everything works fine. However I can provide you with some hints about how to resolve this problem. # Root cause analysis The pathnames in the traceback you included seem to hint at the root cause of this issue: * `/usr/lib/python2.7/dist-packages/setuptools` is setuptools installed in `/usr/lib/python2.7` (most likely installed using apt system packages) * `/usr/local/lib/python2.7/dist-packages/pkg_resources.py` is pkg_resources installed in `/usr/local/lib/python2.7` (most likely installed using `sudo easy_install setuptools` or `sudo pip setuptools`) I'm pretty sure this explains why setuptools (a package that provides multiple modules) and pkg_resources (a module provided by setuptools) are "out of sync". Solving the issue might be as simple as getting rid of `/usr/local/lib/python2.7/dist-packages/pkg_resources.py`, however I can't tell (without more context) how that file got there and what the cleanest way to remove it is. You can try `sudo pip uninstall setuptools`, but please double check to make sure it will only touch files in `/usr/local` (you don't want pip to break the version of setuptools that's installed using apt system packages). # pip-accel 0.22 doesn't like pip 1.5.x You mentioned: > I am using pip from the Ubuntu repos (pip 1.5.6 from > /usr/lib/python2.7/dist-packages (python 2.7)) but it appears to be > downloading it again (because it doesn't like 1.5.x?) This is correct, pip-accel 0.22 required a version of pip older than 1.5. Today I released pip-accel 0.23 which uses a newer version of pip (it requires pip 6, which is what pip 1.6 would have been if pip din't change its versioning scheme to make the minor numbers the major numbers, but I digress). # pip-accel and virtual environments You also mentioned: > if there's another way to use pip-accel (e.g. install it into the target > virtualenv) I'm all ears, but it doesn't seem like it This surprises me because the main use case of pip-accel (as documented in its README) is to install it inside the Python virtual environment where you want to install Python packages using pip-accel. So this should work fine, please try it out!
Why does this use of Python's multiprocessing module not seem to process sequentially? Question: I'm trying to learn to use Python's Multiprocessing module. As a first test, I thought I would run four 15 second processes at the same time. I wrote this module, which I called "multiPtest.py":: import time import timeit import multiprocessing def sleepyMe(napTime): time.sleep(napTime) print "Slept %d secs" % napTime def tester(numTests): #Launch 'numTests' processes using multiProcessing module for _ in range(numTests): p = multiprocessing.Process(target=sleepyMe(15)) p.start() #Launch an 'independent' process #p.join() ##Results identical with or without join def multiTester(): #Time running of 4 processes totTime = timeit.Timer('tester(4)', setup = 'from multiPtest import tester').repeat(1,1) print "Total = ", totTime[0] However, when I run, I get these results: Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from multiPtest import * >>> multiTester() Slept 15 secs Slept 15 secs Slept 15 secs Slept 15 secs Total = 60.0739970207 I would have expected the Total time to be closer to 15 seconds, rather than 60. I know that I have 4 cores, because I looked at /proc/cpuinfo: ~/Projects/PythonProjects$ cat /proc/cpuinfo processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 60 model name : Intel(R) Core(TM) i7-4900MQ CPU @ 2.80GHz stepping : 3 microcode : 0x17 cpu MHz : 800.000 cache size : 8192 KB physical id : 0 siblings : 8 core id : 0 cpu cores : 4 ... Why don't I see these 4 sleepers asleep at the same time? Shouldn't I have been able to create and launch new processes while others were asleep/busy? Am I misunderstanding something about multiprocessing, about Python's multiprocessing module or something else? Answer: In the line p = multiprocessing.Process(target=sleepyMe(15)) you actually already _call_ `sleepyMe` and use the result (`None`) as the value for the `target` parameter, thus waiting 15 seconds. Try p = multiprocessing.Process(target=sleepyMe, args=(15, )) and modify the function to `join()` all subprocesses _after the for loop_ , or it will return immediately and you'll end up with a total time close to zero..
Install PyX under python 2.7.6 Question: I am trying to install PyX in yosemite under python 2.7.6 Initially, the setup looks ok python setup.py install running install running build running build_py running install_lib running install_egg_info Removing /Users/alkaloge/Library/Python/2.7/site-packages/PyX-0.12.1-py2.7.egg-info Writing /Users/alkaloge/Library/Python/2.7/site-packages/PyX-0.12.1-py2.7.egg-info but when trying to run an example python hello.py Traceback (most recent call last): File "hello.py", line 1, in <module> from pyx import * ImportError: No module named pyx Any help ? thanks Answer: Make sure, this is a common problem, your Command Line Interface is using the appropriate version of Python. Most users have multiple versions of python installed, and your CLI only recognizes one at at time. In your terminal window type in python and you will see what version you have. Also check where you installed PyX if it isn't under another python directory.
random color text generat Question: I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color This is what I have: color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']; I want to be able to have a program that can let me type out a paragraph, then it uses the colors in the list and randomly assigns them to each letter. For an output, I would like to to be something like this. [color=random]H[/color][color=random]i[/color] [color=random]t[/color] [color=random]h[/color] [color=random]e[/color][color=random]r[/color][color=random]e[/color] The colors should be random from the list I made. Is this possible to make? Answer: This works for me: from random import choice color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] l = len(color) str = "Hit Here" html = '' for x in str: html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x print(html) Sample output: [color=yellow]H[/color][color=#f60]i[/color][color=yellow]t[/color] [color=black]H[/color][color=black]e[/color][color=white]r[/color][color=purple]e[/color] [color=purple]H[/color][color=white]i[/color][color=purple]t[/color] [color=black]H[/color][color=green]e[/color][color=red]r[/color][color=blue]e[/color] [color=yellow]H[/color][color=green]i[/color][color=#f60]t[/color] [color=blue]H[/color][color=white]e[/color][color=green]r[/color][color=pink]e[/color]
Why is it considered 'powerful' to pass a function as a parameter? Question: I am reading through _A Concise Introduction to Programming in Python_ by Mark J.Johnson and I stumbled upon a piece of code that uses darts to estimate the area under the graph. The code is working perfectly fine but I am getting confused as to why you would pass a function as a parameter if you could just call the function anyway. from random import uniform from math import exp def area(function , a ,b ,m ,n = 1000 ): #changed parameter for better understanding hits = 0 total_area = m * (b-a) for i in range(n): x = uniform(a,b) y = uniform(0,m) if y <= function(x): hits += 1 frac = hits / float(n) return frac * total_area def f(x): return exp(-x**2) def g(x): #new function return exp(-x**2) + 2 def main(): print area(f,0,2,1) print area(g,0,2,1) main() He states that passing a function as a parameter is 'powerful' but I can't see why? Answer: `f` is but _one graph function_. It is not the only function that you could define to create a graph. You can also define other functions: def g(x): return 2 * x ** 2 + x + 5 and pass this into `area()` **without having to alter that function**. `area()` is generic enough to calculate the area of different graph functions, and all you need to do is pass in the graph function to have it calculate that area. Had you hardcoded `f` instead of using a parameter, you could no longer do that.
How to make a random text python Question: I need help to output a random text. I've been given a text with 25k words, from this `text_file` I've been calculating the probability for the single letters, and the single words to see which letters/words have been used most. Now I need to make a other text with 500 letters, but this text should include the probability that I have calculated, and should be wroten by the letters that I "found" from the first text. It's like: Text1 -> do probability over the usen letters, which letters have been represented most. Make text2 -> use the probability u found from text1. Hope u can help me, Im new in Python. Answer: The easiest thing is to randomly select letters of the 25k file. Then the resultant has the same probability as the original. import random print(''.join(random.choice(original_text) for _ in range(500)))
Serialize python objects along with class definition Question: I'm trying to understand how to make RPC calls using Python. I have a stupid server that defines a class and exposes a method that create instances of that class: # server.py class Greeter(object): def __init__(self, name): self.name = name def greet(self): return "Hi {}!".format(self.name) def greeter_factory(name): return Greeter(name) some_RPC_framework.register(greeter_factory) and a client that wants to get an instance of the `Greeter`: # client.py greeter_factory = some_RPC_framework.proxy(uri_given_by_server) h = greeter_factory("Heisemberg") print("Server returned:", h.greet()) The problem is that I've found no framework that allows to return instances of user-defined objects, or that only returns a dict with the attributes of the object (for example, Pyro4). In the past I've used Java RMI, where you can specify a codebase on the server where the client can download the compiled classes, if it needs to. Is there something like this for Python? Maybe some framework that can serialize objects along with the class bytecode to let the client have a full-working instance of the class? Answer: Pyro can do this to a certain extent. You can register custom class (de)serializers when using the default serializer. Or you can decide to use the pickle serializer, but that has severe security implications. See <http://pythonhosted.org/Pyro4/clientcode.html#serialization> What Pyro won't do for you, even when using the pickle serializer, is transfer the actual bytecode that makes up the module definition. The client, in your case, has to be able to import the module defining your classes in the regular way. There's no code transportation.
Sphinx autodoc TypeError: 'type' object is not iterable Question: When trying to build documentation (any type: html, man pages, latexpdf...) sphinx fails while trying to autodoc a subdirectory of a project. I've tried many different approaches to try to narrow down what the problem is but I can't seem to find the culprit. All of the rst files were generated by sphinx- apidoc. directory A has the following rst file: Directory A ======================================= Submodules ---------- .. toctree:: A.fileB A.fileC A.fileD A.fileE Module contents --------------- .. automodule:: A :members: :undoc-members: :show-inheritance: Failure does not occur if the :members: directive is removed. Failure also does not occur if files B or E are missing, or if the import of file B in E is missing or commented out. It will still fail if fileB and fileE are paired down to simply the following: fileB: class B(object): pass fileE: from fileB import B class E(B): pass with the following stack trace: # Sphinx version: 1.3b2 # Python version: 2.7.5 # Docutils version: 0.12 release # Jinja2 version: 2.6 # Last messages: # reading sources... [ 37%] foo # reading sources... [ 37%] foo # reading sources... [ 38%] foo # reading sources... [ 38%] foo # reading sources... [ 39%] foo # reading sources... [ 39%] foo # reading sources... [ 40%] foo # reading sources... [ 40%] foo # reading sources... [ 41%] foo # reading sources... [ 41%] problem file # Loaded extensions: # sphinx.ext.autodoc (1.3b2) from Sphinx-1.3b2-py2.7.egg/sphinx/ext/autodoc.pyc # sphinx.ext.viewcode (1.3b2) from Sphinx-1.3b2-py2.7.egg/sphinx/ext/viewcode.pyc Traceback (most recent call last): File "Sphinx-1.3b2-py2.7.egg/sphinx/cmdline.py", line 246, in main app.build(opts.force_all, filenames) File "Sphinx-1.3b2-py2.7.egg/sphinx/application.py", line 257, in build self.builder.build_update() File "Sphinx-1.3b2-py2.7.egg/sphinx/builders/__init__.py", line 237, in build_update 'out of date' % len(to_build)) File "Sphinx-1.3b2-py2.7.egg/sphinx/builders/__init__.py", line 251, in build self.doctreedir, self.app)) File "Sphinx-1.3b2-py2.7.egg/sphinx/environment.py", line 585, in update self._read_serial(docnames, app) File "Sphinx-1.3b2-py2.7.egg/sphinx/environment.py", line 601, in _read_serial self.read_doc(docname, app) File "Sphinx-1.3b2-py2.7.egg/sphinx/environment.py", line 753, in read_doc pub.publish() File "docutils/core.py", line 217, in publish self.settings) File "docutils/readers/__init__.py", line 72, in read self.parse() File "docutils/readers/__init__.py", line 78, in parse self.parser.parse(self.input, document) File "docutils/parsers/rst/__init__.py", line 172, in parse self.statemachine.run(inputlines, document, inliner=self.inliner) File "docutils/parsers/rst/states.py", line 170, in run input_source=document['source']) File "docutils/statemachine.py", line 239, in run context, state, transitions) File "docutils/statemachine.py", line 460, in check_line return method(match, context, next_state) File "docutils/parsers/rst/states.py", line 2726, in underline self.section(title, source, style, lineno - 1, messages) File "docutils/parsers/rst/states.py", line 327, in section self.new_subsection(title, lineno, messages) File "docutils/parsers/rst/states.py", line 395, in new_subsection node=section_node, match_titles=True) File "docutils/parsers/rst/states.py", line 282, in nested_parse node=node, match_titles=match_titles) File "docutils/parsers/rst/states.py", line 195, in run results = StateMachineWS.run(self, input_lines, input_offset) File "docutils/statemachine.py", line 239, in run context, state, transitions) File "docutils/statemachine.py", line 460, in check_line return method(match, context, next_state) File "docutils/parsers/rst/states.py", line 2726, in underline self.section(title, source, style, lineno - 1, messages) File "docutils/parsers/rst/states.py", line 327, in section self.new_subsection(title, lineno, messages) File "docutils/parsers/rst/states.py", line 395, in new_subsection node=section_node, match_titles=True) File "docutils/parsers/rst/states.py", line 282, in nested_parse node=node, match_titles=match_titles) File "docutils/parsers/rst/states.py", line 195, in run results = StateMachineWS.run(self, input_lines, input_offset) File "docutils/statemachine.py", line 239, in run context, state, transitions) File "docutils/statemachine.py", line 460, in check_line return method(match, context, next_state) File "docutils/parsers/rst/states.py", line 2299, in explicit_markup nodelist, blank_finish = self.explicit_construct(match) File "docutils/parsers/rst/states.py", line 2311, in explicit_construct return method(self, expmatch) File "docutils/parsers/rst/states.py", line 2054, in directive directive_class, match, type_name, option_presets) File "docutils/parsers/rst/states.py", line 2103, in run_directive result = directive_instance.run() File "Sphinx-1.3b2-py2.7.egg/sphinx/ext/autodoc.py", line 1441, in run documenter.generate(more_content=self.content) File "Sphinx-1.3b2-py2.7.egg/sphinx/ext/autodoc.py", line 816, in generate self.document_members(all_members) File "Sphinx-1.3b2-py2.7.egg/sphinx/ext/autodoc.py", line 699, in document_members members_check_module, members = self.get_object_members(want_all) File "Sphinx-1.3b2-py2.7.egg/sphinx/ext/autodoc.py", line 878, in get_object_members for mname in memberlist: TypeError: 'type' object is not iterable Is there something wrong in the files that autodoc is trying to read or if their is an issue with autodoc itself? is there some kind of work around I can try? Thanks! Answer: So the solution to my issue was that the **init** for A simply had from A.fileD import D __all__ == D when it should have contained: from A.fileD import D __all__ == ["D"] Sphinx has also been updated so that instead of failing out when this happens it will issue a warning: WARNING: missing attribute mentioned in :members: or __all__: ... see <https://github.com/sphinx-doc/sphinx/issues/1674> for more information.
Permission denied error near end of python module (igraph) install Question: I'm trying to install igraph 0.7. It's on a cluster, so it must be done in my home directory. I'm using `pip` and pointing it to a local archive. The process works well, until then end, when I get a permission denied error. pequodr@labq02 [~/modules] % pip install --user python-igraph-0.7.tar.gz [LOTS OF OUTPUT CLIPPED] byte-compiling /home/pequodr/pequodr/.local/lib/python2.7/site-packages/igraph/clustering.py to clustering.pyc byte-compiling /home/pequodr/pequodr/.local/lib/python2.7/site-packages/igraph/summary.py to summary.pyc byte-compiling /home/pequodr/pequodr/.local/lib/python2.7/site-packages/igraph/statistics.py to statistics.pyc byte-compiling /home/pequodr/pequodr/.local/lib/python2.7/site-packages/igraph/compat.py to compat.pyc running install_headers creating /soft/python-epd/canopy-1.4.1/include/site error: could not create '/soft/python-epd/canopy-1.4.1/include/site': Permission denied ---------------------------------------- Cleaning up... Command /soft/python-epd/canopy-1.4.1/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-_iGu38-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_slLtx-record/install-record.txt --single-version-externally-managed --compile --install-headers /soft/python-epd/canopy-1.4.1/include/site/python2.7 --user failed with error code 1 in /tmp/pip-_iGu38-build Storing debug log for failure in /home/pequodr/pequodr/.pip/pip.log pequodr@labq02 [~/modules] % What's interesting is that the package seems to work okay. I can import it and use it in python. How can I get around this error? Since the package works, can it be ignored, or will it come back to haunt me later? What does it mean? # EDIT Here is the output of `ls -l /soft/python-epd/canopy-1.4.1/include/` total 8640 -rw-r--r--. 1 swinst swinst 4857 Jan 8 12:07 clog_commset.h -rw-r--r--. 1 swinst swinst 696 Jan 8 12:07 clog_const.h -rw-r--r--. 1 swinst swinst 737 Jan 8 12:07 clog_inttypes.h -rw-r--r--. 1 swinst swinst 1353 Jan 8 12:07 clog_uuid.h -rw-r--r--. 1 swinst swinst 3997 Jan 8 12:00 cpl_atomic_ops.h -rw-r--r--. 1 swinst swinst 627 Jan 8 12:00 cpl_config_extras.h -rw-r--r--. 1 swinst swinst 6397 Jan 8 12:00 cpl_config.h -rw-r--r--. 1 swinst swinst 13436 Jan 8 12:00 cpl_conv.h -rw-r--r--. 1 swinst swinst 2871 Jan 8 12:00 cpl_csv.h -rw-r--r--. 1 swinst swinst 5072 Jan 8 12:00 cpl_error.h -rw-r--r--. 1 swinst swinst 3478 Jan 8 12:00 cpl_hash_set.h -rw-r--r--. 1 swinst swinst 4148 Jan 8 12:00 cpl_http.h -rw-r--r--. 1 swinst swinst 2828 Jan 8 12:00 cplkeywordparser.h -rw-r--r--. 1 swinst swinst 2813 Jan 8 12:00 cpl_list.h -rw-r--r--. 1 swinst swinst 6641 Jan 8 12:00 cpl_minixml.h -rw-r--r--. 1 swinst swinst 3114 Jan 8 12:00 cpl_minizip_ioapi.h -rw-r--r--. 1 swinst swinst 13825 Jan 8 12:00 cpl_minizip_unzip.h -rw-r--r--. 1 swinst swinst 9758 Jan 8 12:00 cpl_minizip_zip.h -rw-r--r--. 1 swinst swinst 6285 Jan 8 12:00 cpl_multiproc.h -rw-r--r--. 1 swinst swinst 9352 Jan 8 12:00 cpl_odbc.h -rw-r--r--. 1 swinst swinst 21384 Jan 8 12:00 cpl_port.h -rw-r--r--. 1 swinst swinst 2212 Jan 8 12:00 cpl_progress.h -rw-r--r--. 1 swinst swinst 4505 Jan 8 12:00 cpl_quad_tree.h -rw-r--r--. 1 swinst swinst 3569 Jan 8 12:00 cpl_spawn.h -rw-r--r--. 1 swinst swinst 14916 Jan 8 12:00 cpl_string.h -rw-r--r--. 1 swinst swinst 1935 Jan 8 12:00 cpl_time.h -rw-r--r--. 1 swinst swinst 16181 Jan 8 12:00 cpl_virtualmem.h -rw-r--r--. 1 swinst swinst 11897 Jan 8 12:00 cpl_vsi.h -rw-r--r--. 1 swinst swinst 2549 Jan 8 12:00 cpl_vsil_curl_priv.h -rw-r--r--. 1 swinst swinst 8307 Jan 8 12:00 cpl_vsi_virtual.h -rw-r--r--. 1 swinst swinst 2973 Jan 8 12:00 cpl_win32ce_api.h -rw-r--r--. 1 swinst swinst 1821 Jan 8 12:00 cpl_wince.h drwxr-xr-x. 2 swinst swinst 4096 Jan 8 12:00 curl -rw-r--r--. 1 swinst swinst 3364 Jan 8 12:00 expat_external.h -rw-r--r--. 1 swinst swinst 40339 Jan 8 12:00 expat.h drwxr-xr-x. 3 swinst swinst 8192 Jan 8 12:02 freetype2 -rw-r--r--. 1 swinst swinst 19306 Jan 8 12:00 gdal_alg.h -rw-r--r--. 1 swinst swinst 7501 Jan 8 12:00 gdal_alg_priv.h -rw-r--r--. 1 swinst swinst 1890 Jan 8 12:00 gdal_csv.h -rw-r--r--. 1 swinst swinst 9476 Jan 8 12:00 gdalexif.h -rw-r--r--. 1 swinst swinst 7373 Jan 8 12:00 gdal_frmts.h -rw-r--r--. 1 swinst swinst 2397 Jan 8 12:00 gdalgeorefpamdataset.h -rw-r--r--. 1 swinst swinst 5289 Jan 8 12:00 gdalgrid.h -rw-r--r--. 1 swinst swinst 3009 Jan 8 12:00 gdalgrid_priv.h -rw-r--r--. 1 swinst swinst 41298 Jan 8 12:00 gdal.h -rw-r--r--. 1 swinst swinst 2123 Jan 8 12:00 gdaljp2abstractdataset.h -rw-r--r--. 1 swinst swinst 4888 Jan 8 12:00 gdaljp2metadata.h -rw-r--r--. 1 swinst swinst 12217 Jan 8 12:00 gdal_pam.h -rw-r--r--. 1 swinst swinst 37917 Jan 8 12:00 gdal_priv.h -rw-r--r--. 1 swinst swinst 17067 Jan 8 12:00 gdal_proxy.h -rw-r--r--. 1 swinst swinst 12975 Jan 8 12:00 gdal_rat.h -rw-r--r--. 1 swinst swinst 17447 Jan 8 12:00 gdal_simplesurf.h -rw-r--r--. 1 swinst swinst 1034 Jan 8 12:00 gdal_version.h -rw-r--r--. 1 swinst swinst 4538 Jan 8 12:00 gdal_vrt.h -rw-r--r--. 1 swinst swinst 16951 Jan 8 12:00 gdalwarper.h -rw-r--r--. 1 swinst swinst 6250 Jan 8 12:00 gdalwarpkernel_opencl.h drwxr-xr-x. 15 swinst swinst 8192 Jan 8 12:03 geos -rw-r--r--. 1 swinst swinst 64011 Jan 8 12:03 geos_c.h -rw-r--r--. 1 swinst swinst 866 Jan 8 12:03 geos.h drwxr-xr-x. 3 swinst swinst 4096 Jan 8 12:05 gio-unix-2.0 drwxr-xr-x. 5 swinst swinst 4096 Jan 8 12:05 glib-2.0 drwxr-xr-x. 3 swinst swinst 4096 Jan 8 12:05 gstreamer-0.10 -rw-r--r--. 1 swinst swinst 2886 Jan 8 12:00 gvgcpfit.h -rw-r--r--. 1 swinst swinst 22588 Jan 8 12:00 H5ACpublic.h -rw-r--r--. 1 swinst swinst 14401 Jan 8 12:00 H5api_adpt.h -rw-r--r--. 1 swinst swinst 5629 Jan 8 12:00 H5Apublic.h -rw-r--r--. 1 swinst swinst 1918 Jan 8 12:00 H5Cpublic.h -rw-r--r--. 1 swinst swinst 1592 Jan 8 12:00 H5DOpublic.h -rw-r--r--. 1 swinst swinst 6616 Jan 8 12:00 H5Dpublic.h -rw-r--r--. 1 swinst swinst 2748 Jan 8 12:00 H5DSpublic.h -rw-r--r--. 1 swinst swinst 19492 Jan 8 12:00 H5Epubgen.h -rw-r--r--. 1 swinst swinst 9174 Jan 8 12:00 H5Epublic.h -rw-r--r--. 1 swinst swinst 1705 Jan 8 12:00 H5FDcore.h -rw-r--r--. 1 swinst swinst 2172 Jan 8 12:00 H5FDdirect.h -rw-r--r--. 1 swinst swinst 1723 Jan 8 12:00 H5FDfamily.h -rw-r--r--. 1 swinst swinst 3243 Jan 8 12:00 H5FDlog.h -rw-r--r--. 1 swinst swinst 2806 Jan 8 12:00 H5FDmpi.h -rw-r--r--. 1 swinst swinst 2499 Jan 8 12:00 H5FDmpio.h -rw-r--r--. 1 swinst swinst 1900 Jan 8 12:00 H5FDmpiposix.h -rw-r--r--. 1 swinst swinst 2095 Jan 8 12:00 H5FDmulti.h -rw-r--r--. 1 swinst swinst 13879 Jan 8 12:00 H5FDpublic.h -rw-r--r--. 1 swinst swinst 1555 Jan 8 12:00 H5FDsec2.h -rw-r--r--. 1 swinst swinst 1561 Jan 8 12:00 H5FDstdio.h -rw-r--r--. 1 swinst swinst 8717 Jan 8 12:00 H5Fpublic.h -rw-r--r--. 1 swinst swinst 7309 Jan 8 12:00 H5Gpublic.h -rw-r--r--. 1 swinst swinst 3432 Jan 8 12:00 H5IMpublic.h -rw-r--r--. 1 swinst swinst 4641 Jan 8 12:00 H5Ipublic.h -rw-r--r--. 1 swinst swinst 9324 Jan 8 12:00 H5Lpublic.h -rw-r--r--. 1 swinst swinst 14340 Jan 8 12:00 H5LTpublic.h -rw-r--r--. 1 swinst swinst 1933 Jan 8 12:00 H5MMpublic.h -rw-r--r--. 1 swinst swinst 10238 Jan 8 12:00 H5Opublic.h -rw-r--r--. 1 swinst swinst 99992 Jan 8 12:00 H5overflow.h -rw-r--r--. 1 swinst swinst 2882 Jan 8 12:00 H5PLextern.h -rw-r--r--. 1 swinst swinst 24235 Jan 8 12:00 H5Ppublic.h -rw-r--r--. 1 swinst swinst 4011 Jan 8 12:00 H5PTpublic.h -rw-r--r--. 1 swinst swinst 22089 Jan 8 12:00 H5pubconf.h -rw-r--r--. 1 swinst swinst 11180 Jan 8 12:00 H5public.h -rw-r--r--. 1 swinst swinst 3686 Jan 8 12:00 H5Rpublic.h -rw-r--r--. 1 swinst swinst 7405 Jan 8 12:00 H5Spublic.h -rw-r--r--. 1 swinst swinst 8577 Jan 8 12:00 H5TBpublic.h -rw-r--r--. 1 swinst swinst 27329 Jan 8 12:00 H5Tpublic.h -rw-r--r--. 1 swinst swinst 12558 Jan 8 12:00 H5version.h -rw-r--r--. 1 swinst swinst 11262 Jan 8 12:00 H5Zpublic.h -rw-r--r--. 1 swinst swinst 2655 Jan 8 12:00 hdf5.h -rw-r--r--. 1 swinst swinst 1604 Jan 8 12:00 hdf5_hl.h -rw-r--r--. 1 swinst swinst 1352 Oct 13 10:42 jconfig.h -rw-r--r--. 1 swinst swinst 14581 Oct 13 10:42 jerror.h -rw-r--r--. 1 swinst swinst 12653 Oct 13 10:42 jmorecfg.h -rw-r--r--. 1 swinst swinst 47474 Oct 13 10:42 jpeglib.h drwxr-xr-x. 2 swinst swinst 4096 Jan 8 12:00 libexslt drwxr-xr-x. 2 swinst swinst 4096 Jan 8 11:58 libpng16 drwxr-xr-x. 3 swinst swinst 4096 Jan 8 12:00 libxml2 drwxr-xr-x. 2 swinst swinst 4096 Jan 8 12:00 libxslt -rw-r--r--. 1 swinst swinst 5712 Jan 8 12:00 memdataset.h -rw-r--r--. 1 swinst swinst 2342 Jan 8 12:07 mpe_callstack.h -rw-r--r--. 1 swinst swinst 1184 Jan 8 12:06 mpe_graphicsf.h -rw-r--r--. 1 swinst swinst 6083 Jan 8 12:06 mpe_graphics.h -rw-r--r--. 1 swinst swinst 355 Jan 8 12:06 mpe.h -rw-r--r--. 1 swinst swinst 1833 Jan 8 12:06 mpe_logf.h -rw-r--r--. 1 swinst swinst 11102 Jan 8 12:07 mpe_log.h -rw-r--r--. 1 swinst swinst 2721 Jan 8 12:07 mpe_log_thread.h -rw-r--r--. 1 swinst swinst 1322 Jan 8 12:06 mpe_misc.h -rw-r--r--. 1 swinst swinst 102269 Jan 8 12:06 mpi_base.mod -rw-r--r--. 1 swinst swinst 45898 Jan 8 12:07 mpi_constants.mod -rw-r--r--. 1 swinst swinst 100748 Jan 8 12:07 mpicxx.h -rw-r--r--. 1 swinst swinst 18320 Jan 8 12:07 mpif.h -rw-r--r--. 1 swinst swinst 55767 Jan 8 12:07 mpi.h -rw-r--r--. 1 swinst swinst 158455 Jan 8 12:07 mpi.mod -rw-r--r--. 1 swinst swinst 1190 Jan 8 12:06 mpiof.h -rw-r--r--. 1 swinst swinst 16710 Jan 8 12:07 mpio.h -rw-r--r--. 1 swinst swinst 9390 Jan 8 12:07 mpi_sizeofs.mod -rw-r--r--. 1 swinst swinst 591 Jan 8 12:07 mpix.h -rw-r--r--. 1 swinst swinst 60373 Jan 8 12:00 netcdf.h -rw-r--r--. 1 swinst swinst 29693 Jan 8 12:00 ogr_api.h -rw-r--r--. 1 swinst swinst 20574 Jan 8 12:00 ogr_core.h -rw-r--r--. 1 swinst swinst 17318 Jan 8 12:00 ogr_feature.h -rw-r--r--. 1 swinst swinst 19439 Jan 8 12:00 ogr_featurestyle.h -rw-r--r--. 1 swinst swinst 2554 Jan 8 12:00 ogr_geocoding.h -rw-r--r--. 1 swinst swinst 26955 Jan 8 12:00 ogr_geometry.h -rw-r--r--. 1 swinst swinst 6974 Jan 8 12:00 ogr_p.h -rw-r--r--. 1 swinst swinst 17903 Jan 8 12:00 ogrsf_frmts.h -rw-r--r--. 1 swinst swinst 26958 Jan 8 12:00 ogr_spatialref.h -rw-r--r--. 1 swinst swinst 36834 Jan 8 12:00 ogr_srs_api.h -rw-r--r--. 1 swinst swinst 6682 Jan 8 12:07 opa_config.h -rw-r--r--. 1 swinst swinst 5937 Jan 8 12:07 opa_primitives.h -rw-r--r--. 1 swinst swinst 14465 Jan 8 12:07 opa_queue.h -rw-r--r--. 1 swinst swinst 882 Jan 8 12:07 opa_util.h lrwxrwxrwx. 1 swinst swinst 18 Jan 8 11:58 pngconf.h -> libpng16/pngconf.h lrwxrwxrwx. 1 swinst swinst 14 Jan 8 11:58 png.h -> libpng16/png.h lrwxrwxrwx. 1 swinst swinst 21 Jan 8 11:58 pnglibconf.h -> libpng16/pnglibconf.h drwxr-xr-x. 2 swinst swinst 4096 Jan 8 12:07 primitives -rw-r--r--. 1 swinst swinst 6630 Jan 8 12:00 rawdataset.h drwxr-xr-x. 2 swinst swinst 4096 Jan 8 12:04 theora -rw-r--r--. 1 swinst swinst 4927 Jan 8 12:00 thinplatespline.h -rw-r--r--. 1 swinst swinst 35765 Jan 8 12:00 vrtdataset.h drwxr-xr-x. 21 swinst swinst 274432 Jan 8 12:03 vtk-5.10 drwxr-xr-x. 3 swinst swinst 4096 Jan 8 12:02 wx-2.8 -rw-r--r--. 1 swinst swinst 54225 Jan 8 12:05 yaml.h -rw-r--r--. 1 swinst swinst 14351 Jan 8 12:00 zconf.h -rw-r--r--. 1 swinst swinst 86076 Jan 8 12:00 zlib.h -rw-r--r--. 1 swinst swinst 14084 Jan 8 12:02 zmq.h -rw-r--r--. 1 swinst swinst 3588 Jan 8 12:02 zmq_utils.h Answer: You can safely ignore the message. `python-igraph` tries to add a header file named `igraphmodule_api.h` to the list of Python headers to make it possible for other extension written in C to use some of igraph's internal API. You won't need this unless you want to develop another Python extension in C to extend the functionality of the `igraph` module in Python. If the message annoys you, you can edit `setup.py` and remove the line that refers to `igraphmodule_api.h` to get rid of the warning.
Python: Creating a new dictionary while switching keys and values Question: If I am given a dictionary that has student names as keys and the subjects they're proficient in as a set of strings, how would I go about creating a new dictionary that would have the subjects as keys and everybody who's proficient in those subjects in a set? Sorry, this is my first time asking a question here, so I'm not quite sure how to include snippets of functions. Answer: Use a [defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) making each of the subjects/values in each set a key and append/add each student to a list/set as values. s = {'Sherman':{'calculus', 'english'}, 'Tyler': {'computers','history'}, 'Kevin': {'chemistry','PE','geometry'}, 'Joe': {'calculus','computers'}, 'Bryan': {'nothing'}, 'Steven': {'biology','research', 'algebra'}} from collections import defaultdict d = defaultdict(list) for k,v in s.items(): # iterate over key/value tuples. for sub in v: # get each subject in the set/value d[sub].append(k) # add the students to a list and and make each subject a key print(d) defaultdict(<type 'list'>, {'calculus': ['Sherman', 'Joe'], 'biology': ['Steven'], 'algebra': ['Steven'], 'geometry': ['Kevin'], 'computers': ['Tyler', 'Joe'], 'research': ['Steven'], 'english': ['Sherman'], 'nothing': ['Bryan'], 'chemistry': ['Kevin'], 'PE': ['Kevin'], 'history': ['Tyler']}) If you want sets as values use defaultdict(set) and .add instead of append: from collections import defaultdict d = defaultdict(set) for k,v in s.items(): for sub in v: d[sub].add(k) print(d) defaultdict(<type 'set'>, {'calculus': set(['Sherman', 'Joe']), 'biology': set(['Steven']), 'algebra': set(['Steven']), 'geometry': set(['Kevin']), 'computers': set(['Tyler', 'Joe']), 'research': set(['Steven']), 'english': set(['Sherman']), 'nothing': set(['Bryan']), 'chemistry': set(['Kevin']), 'PE': set(['Kevin']), 'history': set(['Tyler'])}) Using a defaultdict means if the key does not exist in the dict it will be added and the value appended or just appended if it does already exist, you can use dict.setdefault but a defaultdict is more efficient.
Python subtract first element from each respective row of matrix Question: I want to subtract the first value of a row from the rest of the elements of that row, so for import numpy as np z = np.array([[1,2,3,4],[4,5,6,7],[7,8,9,9]]) for n in range(0,3): znew = z[n,:]-z[n,0] `znew` should be `np.array([[0,1,2,3],[0,1,2,3],[0,1,2,2]])`. How can I do this? It kind of seems trivial. Answer: You can do this by taking advantage of broadcasting: >>> z - z[:,0][:, None] # or z - z[:,0][:, np.newaxis] array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 2]])
Installing psycopg2 in virtual env on RHEL fails Question: I have been on this for days now. Everytime I attempt to install psycopg2 into a virtual environment on my RHEL VPS it fails with the following error. Anyone with a clue should please help out. Thanks. (pyenv)[root@10 pyenv]# pip install psycopg2==2.5.4 Collecting psycopg2==2.5.4 Using cached psycopg2-2.5.4.tar.gz /tmp/pip-build-Vn6ET9/psycopg2/setup.py:12: DeprecationWarning: Parameters to load are deprecated. Call .resolve and .require separately. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= 2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSI ON="2.5.4 (dt dec pq3 ext)" -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHA VE_PQFREEMEM=1 -DPG_VERSION_HEX=0x080414 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_B OOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.6 -I. -I/usr/include -I/usr/ include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.6/ psycopg/psycopgmodule.o -Wdeclaration-after-statement unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 Complete output from command /root/pyenv/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-Vn6ET9/psycopg2/setup.py';exec(compile(getatt r(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'ex ec'))" install --record /tmp/pip-9d8Iwo-record/install-record.txt --single-vers ion-externally-managed --compile --install-headers /root/pyenv/include/site/pyt hon2.6: running install running build running build_py creating build creating build/lib.linux-x86_64-2.6 creating build/lib.linux-x86_64-2.6/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-2.6/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-2.6/psycopg2 creating build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_copy.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_notify.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_quote.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/dbapi20.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_lobject.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_bug_gc.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_psycopg2_dbapi20.py -> build/lib.linux-x86_64-2.6/psycop g2/tests copying tests/testutils.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_cursor.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/__init__.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_bugX000.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_types_basic.py -> build/lib.linux-x86_64-2.6/psycopg2/te sts copying tests/test_connection.py -> build/lib.linux-x86_64-2.6/psycopg2/tes ts copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-2.6/psyco pg2/tests copying tests/test_transaction.py -> build/lib.linux-x86_64-2.6/psycopg2/te sts copying tests/test_module.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_dates.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/testconfig.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_cancel.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_async.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_with.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_green.py -> build/lib.linux-x86_64-2.6/psycopg2/tests copying tests/test_types_extras.py -> build/lib.linux-x86_64-2.6/psycopg2/t ests running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-2.6 creating build/temp.linux-x86_64-2.6/psycopg gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= 2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSI ON="2.5.4 (dt dec pq3 ext)" -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHA VE_PQFREEMEM=1 -DPG_VERSION_HEX=0x080414 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_B OOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.6 -I. -I/usr/include -I/usr/ include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.6/ psycopg/psycopgmodule.o -Wdeclaration-after-statement unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/root/pyenv/bin/python -c "import setuptools, tokenize;__file__='/ tmp/pip-build-Vn6ET9/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --rec ord /tmp/pip-9d8Iwo-record/install-record.txt --single-version-externally-manag ed --compile --install-headers /root/pyenv/include/site/python2.6" failed with error code 1 in /tmp/pip-build-Vn6ET9/psycopg2 Answer: I found my way around it. I noticed it installs successfully globally. So I installed psycopg2 globally and created a new virtual environment with `--system-site-packages` option. Then I installed my other packages using the `-I` option. Hope this helps someone else. OK. I later found out that I had no `gcc` installed. So I had to install it first. And after that, I could `pip install psycopg2`. Thank you cel for the direction.
I am using python 3.2 and pip 6.0.6, when I run scrapy startproject tutorial I get the following error Question: When I run the command scrapy startproject tutorial, i get lots of lines of errors and at the end AttributeError:'NoneType'object has no attribute 'startswith'. In the previous lines it is pointing to various lines in various files c:\Python27>scrapy startproject tutorial Traceback(most recent call last): File "C:\Python32\Scripts\scrapy-script.py", line 9, in <module> load_entry_point('Scrapy==0.24.4', 'console_scripts', 'scrapy')() File "C:\Python32\lib\site-packages\pkg_resources\__init__.py", line 519, in load_entry_point return get_distribution(dist).load_entry_point(group,name) File "C:\Python32\lib\site-packages\pkg_resources\__init__.py", line 2630, in load_entry_point return ep.load() File "C:\Python32\lib\site-packages\pkg_resources\__init__.py", line 2310, in load return self.resolve() File "C:\Python32\lib\site-packages\pkg_resources\__init__.py",line 2316, in resolve module=__import__(self.module_name, fromlist=['__name__'], level=0) File "C:\Python32\lib\site-packages\scrapy\__init__.py", line 10, in <module> __version__=pkgutil.get_data(__package__, 'VERSION').decode('ascii').strip() File "C:\Python32\lin\pkgutil.py", line 565, in get_data loader=get_loader(package) File "C:\Python32\lib\pkgutil.py", line 453, in get_loader return find_loader(fullname) File "C:\Python32\lib\pkgutil.py", line 463, in find_loader for importer in iter_importers(fullname): File "C:\Python32\lib\pkgutil.py", line 413, in iter_importers if fullname.startswith('.'): AttributeError: 'NoneType'object has no attribute 'startswith' Answer: Scrapy [does not support Python 3](http://doc.scrapy.org/en/0.24/faq.html#faq- python-versions): > What Python versions does Scrapy support? Scrapy is supported under Python > 2.7 only. Python 2.6 support was dropped starting at Scrapy 0.20. > > Does Scrapy work with Python 3? No, but there are plans to support Python > 3.3+. At the moment, Scrapy works with Python 2.7. You need to use Python 2.7.
python running test: ImproperlyConfigured Question: I'm trying to run some testes for django (1.7) project. have created a `test_models.py` directory `/tests/` under project directory. On running test >> python tests/test_models.py -v Error: django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Although following django stanards commands works fine >> python manage.py runserver >> python manage.py shell **test_models.py** import unittest from django.contrib.auth.models import User from accounts.models import school class TestAccounts(unittest.TestCase): def setUp(self): admin_user = User.objects.get_or_create( username="testuser", password=111) self.admin = admin_user[0] self.school_name = "merucabs" self.email = "[email protected]" def test_school(self): print "Testing school ..." school = School(name=self.school_name) school.created_by = self.admin school.updated_by = self.admin school.save() self.school = school self.assertEqual(self.school.name, self.school_name) def suite(): suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(TestAccounts)) if __name__ == '__main__': unittest.main() Answer: You can [run Django tests](https://docs.djangoproject.com/en/1.7/topics/testing/overview/#running- tests) with the `test` command. ./manage.py test tests/test_models If you want to run your tests as a stand alone script (i.e. python `tests/test_models.py`), then you have to set the `DJANGO_SETTINGS_MODULE` environment variable. As of Django 1.7, you must call `django.setup()` as well. import django import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' django.setup()
Python flask cannot open an xml file Question: I try to implement a server-side multilanguage service on my website. This is the structure on the folders: data --locale static --css --images --js templates --index.html --page1.html ... main.py I use Crowdin to translate the website and the output files are in XML. The locale folder contains one folder for each language with one xml file for every page. I store on Cookies the language and here is my python code: from flask import request from xml.dom.minidom import parseString def languages(page): langcode = request.cookies.get("Language") xml = "/data/locale/%s/%s.xml" % (langcode, page) dom = parseString(xml) ................ ............. Which I call in every page, like `languages("index")` This is an example of the exported xml files <?xml version="1.0" encoding="utf-8"?> <!--Generated by crowdin.com--> <!-- This is a description of my page --> <resources> <string name="name1">value 1</string> <string name="name2">value 2</string> <string name="name3">value 3</string> </resources> However, I have the following error `ExpatError: not well-formed (invalid token): line 1, column 0` I googled it. I ended up to other stackoverflow questions, but most of them says about encoding problems and I cannot find any in my example. Answer: You have to use `parse()` if you want to parse a file. `parseString()` will parse a string, the file name in your case. from flask import request from xml.dom.minidom import parse def languages(page): langcode = request.cookies.get("Language") xml = "/data/locale/%s/%s.xml" % (langcode, page) dom = parse(xml)
How would I write this program in Python 3.3.2? Question: This is Guess_The_Number program I wrote in Python: import random print("Hello! Today we are going to play Guess The Number!") number = int(input("Guess a number between 0 and 5")) random_number = random.randint(0, 5) if number == random_number: print("You won!") print("Your prize is...") print("Nothing!") else: print("You lost!") print("The number was %s") % (random_number) I tested it and it returned: print("The number was {0}").format(random_number) AttributeError: 'NoneType' object has no attribute 'format' Then I tried: print("The number was {0}").format(random_number) for the last print statement It stated: print("The number was {0}").format(random_number) AttributeError: 'NoneType' object has no attribute 'format' Answer: You have misplaced parenthesis print("The number was {0}".format(random_number)) **SMALL NOTE** \- It works in Py2 EDit - I meant your program works in Py2 that is `("The number was {0}").format(random_number)` works in Py2
What is wrong here with Choice 2? Question: I have been working on this code (in python) to print a CSV file, sorted. The first choice works fine and sorts it Alphabetically. However the Choice 2 section is supposed to sort the csv file to the highest score. The text/csv file ( name, score, out of: Ben,5,20 James,6,20 Adam,12,20 Will,20,20 code: import operator import csv file = open("scores.txt", "r") scores = csv.reader(file, delimiter=",") sort = sorted(scores) for i in range(0, len(sort)): sort[i].append((max(sort[i][1:2]))) #Alphabetical Order choice = input("Choice: ") if choice == "1": sort = list(sorted(sort,key = operator.itemgetter(0), reverse=False)) print("\nAlphabetical Order:") print("===================") for i in range(0, len(sort)): print("Name: ", sort[i][0], "\tScore: ", sort[i][1]) #Highest score #sort = sorted(scores) elif choice == "2": print("\nHigh Scores:") print("============") sort = list(sorted(sort,key = operator.itemgetter(1, 2),reverse=True)) for i in range(0, len(sort)): print("Name:", sort[i][0], "\tScore:", sort[i][1], "Out of", sort[i][2]) Answer: First of all: max(sort[i][1:2]) will return just the first of the pair of numbers, because the slice returns elements `1` through `2-1`. You could change it to max(sort[i][1:3]) However, the fields that correspond to numbers in the .csv file are strings (as they are returned from `csv.reader`). You should consider turning them to ints when sorting. An easy way without using the `operator` thingy is using an anonymous function that maps a string pair to a tuple of ints: sort = sorted(sort, key = lambda x: (int(x[1]), int(x[2])), reverse = True) # no need to put the rvalue in list() which uses as key a tuple of integers that correspond to your number pair. Also, if you are using `python 2.x`, you should either switch to `raw_input` or use `input` and use `str(choice)`, as BigBang's answer points out. To see why your key choice does not work when sorting according to the number pair, keep in mind that the number pair is returned from csv.reader in a list of strings (like ['Name', '12', '20']). It's easy to see that: >>> ('12', '20') > ('6', '20') False This comparison fails to comply with the case of `12 > 6` because strings are compared lexicographically. Here, '1' is smaller than '6'.
Biopython SeqIO: how to write modified SeqRecord header Question: I thought I'd try using Biopython to salvage some trivially corrupted fastq files provided by a collaborator. I simply need to modify header lines (starting with `@`) which contain a certain substring. However, the new fastq files created by the following code are unchanged. No doubt I'm missing something obvious. What is the correct way to write a modified fastq SeqRecord? import os, sys from Bio import SeqIO path_to_reads = sys.argv[1] if not os.path.exists(path_to_reads + '/fixed'): os.mkdir(path_to_reads + '/fixed') fwd_fastqs = [fn for fn in os.listdir(path_to_reads) if fn.endswith('_F.fastq')] rev_fastqs = [fn for fn in os.listdir(path_to_reads) if fn.endswith('_R.fastq')] fastq_pairs = zip(fwd_fastqs, rev_fastqs) for fastq_pair in fastq_pairs: with open(path_to_reads + '/' + fastq_pair[0], 'rU') as fwd_fastq: with open(path_to_reads + '/fixed/' + fastq_pair[0], 'w') as fixed_fwd_fastq: fixed_fwd_records = [] for fwd_record in SeqIO.parse(fwd_fastq, 'fastq'): fwd_record.name = fwd_record.name.replace('/2','/1') fixed_fwd_records.append(fwd_record) SeqIO.write(fixed_fwd_records, fixed_fwd_fastq, 'fastq') # ... Input data (two records, header lines start with `@`): @MISEQ01:115:000000000-A8FBM:1:1112:18038:15085/1 GATCGGAAGAGCACACGTCTGAACTCCAGTCACTGCCAATCATCTCGTATGCCGTCTTCTGCTTG + AAAAAAAAAF4CGGGGGAGGGFGHBHGHC5AGEGFFHGA3F355FGG223FFAEE0GCGA55BAB @MISEQ01:115:000000000-A8FBM:1:1101:20590:9966/2 GATCACTCCCCTGTGAGGAACTACTGTCTTCACGCAGAAAGCGTCTAGCCATGGCGTTAGTATGA + 1>A111DFBA1CFA1FFG1BFGB1D1DGFGH3GECA0ABFFG?E///DDGFBB0FEAEEFBDAB2 Answer: I'm not a python guy but I do bioinformatics so I understand the file formats. I can explain what happened and why: Looking at the BioPython [Bio.SeqIO.QualityIO fastq writer code](http://biopython.org/DIST/docs/api/Bio.SeqIO.QualityIO- pysrc.html#FastqPhredWriter.write_record) the way that BioPython's `SeqRecord` object works is it has 2 fields to store parts of the defline. A `name` and a `description`. Usually one would think it would work like FASTA files and split the defline on white space with the name being the left split and the description being the optional comment in the right split. However the BioPython parser puts a copy of the defline as the description. My guess is this is a hack (along with the writer code I explain below) to get around CASAVA 1.8 reads which have spaces in them. When the writer writes out the records, it checks to see if the name and description match and if they DON'T then it writes out the `description` line which is assumed to be the CASAVA 1.8 read I guess... Since you were only changing the `name` portion, the match test was failing so the unchanged description was was used instead. When you blanked out the `description` the writer correctly uses the `name` field instead.
Tkinter AttributeError: object has no attribute 'tk' Question: I've looked around a bit, but I can't find an answer to my error. Here is the code: import tkinter as tk root=tk.Tk() class Page(tk.Frame): '''Enables switching between pages of a window.''' def __init__(self): self.widgets={} self.grid(column=0,row=0) page=Page() tk.mainloop() Here is the error: Traceback (most recent call last): File "C:\Documents and Settings\Desktop\Python Scripts\Tkinter.py", line 11, in <module> page=Page() File "C:\Documents and Settings\Desktop\Python Scripts\Tkinter.py", line , in __init__ self.grid(column=0,row=0) File "C:\Python34\lib\tkinter\__init__.py", line 2055, in grid_configure self.tk.call( AttributeError: 'Page' object has no attribute 'tk' I'm fairly new to tkinter, and this error has me stumped. I'd really appreciate any help, thank you! Answer: Your `Page` init method should call `Frame`'s init. class Page(tk.Frame): '''Enables switching between pages of a window.''' def __init__(self): super(Page, self).__init__() self.widgets={} self.grid(column=0,row=0)
ConvergenceWarning: Maximum Likelihood slows kernel-run-time? Question: I use the very nicht code-object `arma_order_select_ic` in order to finde the lowest Information Criterion for chor choosing p- and q values. I am not sure if i do it right or if the code just stumbles upon some mistakes... In: y = indexed_df res = arma_order_select_ic(y, max_ar=7, max_ma=7, ic=['aic', 'bic', 'hqic'], trend='c', fit_kw=dict(method='css')) print res print ('AIC-order: {}' .format(res.aic_min_order)) print ('BIC-order: {}' .format(res.bic_min_order)) print ('HQIC-order: {}' .format(res.hqic_min_order)) Out: /Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/base/model.py:466: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals "Check mle_retvals", ConvergenceWarning) Plus: it prints out the three matrix-style lists (for each IC one matrix) with the final recommendation: AIC-order: (7, 5) BIC-order: (7, 0) HQIC-order: (7, 0) So, the whole thing seems to work. The problem is, it takes approx 30-60 seconds as the warning is printed for every calculation i.e. it is super slow! I checked the relevant source code (statsmodels/base/model.py) and how to skip printing the CovergenceWarning: #TODO: hardcode scale? if isinstance(retvals, dict): mlefit.mle_retvals = retvals if warn_convergence and not retvals['converged']: from warnings import warn from statsmodels.tools.sm_exceptions import ConvergenceWarning warn("Maximum Likelihood optimization failed to converge. " "Check mle_retvals", ConvergenceWarning) mlefit.mle_settings = optim_settings return mlefit So i tried to delete the if part which is linked to the ConvergenceWarning but it wont work. This part from the same source code: mle_retvals : dict Contains the values returned from the chosen optimization method if full_output is True during the fit. Available only if the model is fit by maximum likelihood. See notes below for the output from the different methods. does not tell me where and how to change mle_retvals How to check the mle_retvals and what to change? Is there a way to make the ConvergenceWarning disappear to make the calculation run faster? Answer: The documentation in the Notes section explicitly states how you can speed things up...See the docstring for `fit_kw` to change arguments given to the `ARMA.fit` method. This is going to be slow for high numbers of models. It's a naive implementation and just does a pairwise fit of them all. Try doing `method='css'` for faster results. I don't know why you want to change `mle_retvals`. It is in the returns section. It's not something you change directly. You shouldn't have to delete any source code to get things to run. That check is there to warn you that things are going wrong. I.e., it might be the case that the models causing these warnings are really poor models for your data.
Python/Matplotlib -> to_rgba: Invalid rgba arg Question: I'm trying to plot contours and have previously used a RGB tuple to specify the color (only one for all contours) - however, now I get a ValueError from to_rgba: ValueError: to_rgba: Invalid rgba arg "1" to_rgb: Invalid rgb arg "1" cannot convert argument to rgb sequence Here is an example: import numpy as np import matplotlib.pyplot as plt grid = np.random.random((10,10)) contours = np.linspace(0, 1, 10) Now this works! plt.contour(grid, levels = contours, colors = 'r') plt.show() But this does NOT work! plt.contour(grid, levels = contours, colors = (1,0,0)) plt.show() Am I doing something wrong or is this bug (/new feature) in Matplotlib? Thanks. Answer: As pointed out in the comments, `plt.contour()` expects a sequence of colors. If you want to specify an RGB tuple, make it the first element of such a sequence. plt.contour(grid, levels = contours, colors = ((1,0,0),) ) or plt.contour(grid, levels = contours, colors = [(1,0,0),] )
XML Not Parsing in Python 2.7 with ElementTree Question: I have the following XML file which I get from REST API > > <?xml version="1.0" encoding="utf-8"?> > <boxes> > <home id="1" name="productname"/> > <server>111.111.111.111</server> > <approved>yes</approved> > <creation>2007 handmade</creation> > <description>E-Commerce, buying and selling both > attested</description> > <boxtype> > <sizes>large, medium, small</sizes> > <vendor>Some Organization</vendor> > <version>ANY</version> > </boxtype> > <method>Handmade, Handcrafted</method> > <time>2014</time> > </boxes> > I am able to get the above output, store in a string variable and print in console, but when I send this to xml ElementTree import base64 import urllib2 from xml.dom.minidom import Node, Document, parseString from xml.etree import ElementTree as ET from xml.etree.ElementTree import XML, fromstring, tostring print outputxml ##Printing xml correctly, outputxml contains xml above content = ET.fromstring(outputxml) boxes = content.find('boxes') print boxes boxtype = boxes.find("boxes/boxtype") If I print the boxes it is giving me `None` and hence is giving me below error boxtype = boxes.find("boxes/boxtype") AttributeError: 'NoneType' object has no attribute 'find' Answer: The root level node is `boxes`, and it cannot find `boxes` within itself. boxtype = content.find("boxtype") should be sufficient. DEMO: >>> import base64 >>> import urllib2 >>> from xml.dom.minidom import Node, Document, parseString >>> from xml.etree import ElementTree as ET >>> from xml.etree.ElementTree import XML, fromstring, tostring >>> >>> print outputxml ##Printing xml correctly, outputxml contains xml above <?xml version="1.0" encoding="utf-8"?> <boxes> <home id="1" name="productname"/> <server>111.111.111.111</server> <approved>yes</approved> <creation>2007 handmade</creation> <description>E-Commerce, buying and selling both attested</description> <boxtype> <sizes>large, medium, small</sizes> <vendor>Some Organization</vendor> <version>ANY</version> </boxtype> <method>Handmade, Handcrafted</method> <time>2014</time> </boxes> >>> content = ET.fromstring(outputxml) >>> boxes = content.find('boxes') >>> print boxes None >>> >>> boxes >>> content #note that the content is the root level node - boxes <Element 'boxes' at 0x1075a9250> >>> content.find('boxtype') <Element 'boxtype' at 0x1075a93d0> >>>
Urllib2 using Tor and socks in python Question: I'm trying to crawl websites in Python using tor. I tried below code, which gives the IP used by tor, trying this code for 2-3 times gives me different IP's from different countries. I want IP's from specific country **eg India**. Can we do it using tor and socks? import socks import socket import urllib2 socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, "127.0.0.1", 9050) socket.socket = socks.socksocket print urllib2.urlopen('http://my-ip.herokuapp.com').read() Answer: To get ip from specific country you have to set two parameters **ExitNodes={countrycode}** and **StrictNodes=1**.Here for India country code is **{in}**.To know country code check <http://www.b3rn3d.com/blog/2014/03/05/tor-country-codes/>. Using python you can set the these parameters as follows Code:- import socks import socket import urllib2 def newIdentity(self): socks.setdefaultproxy() s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("127.0.0.1", 9051)) s.send('AUTHENTICATE "my_password" \r\n') response = s.recv(128) if response.startswith("250"): s.send("SETCONF ExitNodes={in}\r\n") s.send("SETCONF StrictNodes=1\r\n") s.send("SIGNAL NEWNYM\r\n") s.close() socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050) socket.socket = socks.socksocket if __name__ == '__main__': newIdentity() print urllib2.urlopen('http://my-ip.herokuapp.com').read()
Trying to convert to datetime Question: I am using datetime to convert a time string. I used the [reference](https://docs.python.org/2/library/time.html#time.strptime) for the specifying the format. How should I have coded the format? In [19]:import datetime In [20]: d Out[20]: 'Oct. 30, 2014, 6:17 a.m.' In [21]: format Out[21]: '%b. %d, %Y, %I:%M%p.' In [22]: date_object = datetime.datetime.strptime(d, format) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-22-78ccb659d6ac> in <module>() ----> 1 date_object = datetime.datetime.strptime(d, format) /usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format) 323 if not found: 324 raise ValueError("time data %r does not match format %r" % --> 325 (data_string, format)) 326 if len(data_string) != found.end(): 327 raise ValueError("unconverted data remains: %s" % ValueError: time data 'Oct. 30, 2014, 6:17 a.m.' does not match format '%b. %d, %Y, %I:%M%p.' I came across this tool, "dateutil" and In [20]: d Out[20]: 'Oct. 30, 2014, 6:17 a.m.' In [34]: from dateutil import parser In [35]: date_obj = parser.parse(d) In [36]: date_obj Out[36]: datetime.datetime(2014, 10, 30, 6, 17) I get this /home/tilaprimera/.virtualenvs/picovico/lib/python2.7/site-packages/django/db/models/fields/__init__.py:1278: RuntimeWarning: DateTimeField GCMDevice.created_at received a naive datetime (2014-10-30 06:17:00) while time zone support is active. RuntimeWarning) The thing is, I am trying to query the database with this time but unfortunately, with some information lost, I do not get a match on the time. Answer: Close, but no cigar. I figured it out by doing `datetime.datetime.now().strftime()` with your format string and playing around a bit. You need two changes: d = 'Oct. 30, 2014, 6:17 AM' format = '%b. %d, %Y, %I:%M %p' There is unfortunately no format specifier that accepts `a.m.` (at least not in the English locale I tried). For more on this, see here: <http://stackoverflow.com/a/2925280/4323>
How to correctly test RGB values using images(OpenCV & Python)? Question: I'm currently working on a project which uses color detection (OpenCV). I'm very new to Python and OpenCV so I'm not getting it work exactly as I want it to. I have a class ColourDetection(any suggestions for fine tuning the HSV values?) which contains the static method detect_color which we use to detect a certain color. Here it is: #!/usr/bin/env python import cv2 import numpy as np class ColourDetection(object): #HSV 180-255-255 max values openCV (recalculate from GIMP) #these need adjusting BOUNDARIES = { 'red': ([170, 160, 60], [180, 255, 255]), 'blue': ([110, 50, 50], [130, 255, 255]), 'green': ([38, 50, 50], [75, 255, 255]), 'yellow':([103, 50, 50], [145, 255, 255]) } @staticmethod def detect_color(detection_image): img_hsv = cv2.cvtColor(detection_image, cv2.COLOR_BGR2HSV) #loop for all defined colours for k,v in ColourDetection.BOUNDARIES.iteritems(): #convert to numpy arrays lower_color = np.array(v[0]) upper_color = np.array(v[1]) #create mask from colour bounds mask = cv2.inRange(img_hsv, lower_color, upper_color) #count found colour pixels amount_not_zero = cv2.countNonZero(mask) if amount_not_zero > 9000: return k else: return "No colour found" The first 2 tests are working correctly. However the last test should return red using these RGB values. It seems I need some fine tuning with the HSV values. Can anyone help me? from unittest import TestCase from ColourDetection import ColourDetection import numpy as np __author__ = 'user' class TestColourDetection(TestCase): def test_detect_color_not_found(self): image = np.zeros((512, 512, 3), np.uint8) color = ColourDetection.detect_color(image) self.assertEqual("No colour found", color) def test_detect_color_is_red(self): image = np.zeros((512, 512, 3), np.uint8) image[:,0:512] = (0, 0, 255) color = ColourDetection.detect_color(image) self.assertEqual("red", color) def test_detect_color_is_blue(self): image = np.zeros((512, 512, 3), np.uint8) image[:,0:512] = (255, 0, 0) color = ColourDetection.detect_color(image) self.assertEqual("blue", color) def test_detect_color_is_green(self): image = np.zeros((512, 512, 3), np.uint8) image[:,0:512] = (0, 255, 0) color = ColourDetection.detect_color(image) self.assertEqual("green", color) def test_detect_color_is_yellow(self): image = np.zeros((512, 512, 3), np.uint8) image[:,0:512] = (0, 255, 255) color = ColourDetection.detect_color(image) self.assertEqual("yellow", color) Answer: The reason why you're only detecting blue might be because of a bug in your `detect_color` function. @staticmethod def detect_color(detection_image): for k,v in ColourDetection.BOUNDARIES.iteritems(): # . . . if amount_not_zero > 9000: return k else: return "No colour found" Notice that you will always return a value in your _first_ iteration over the k,v pairs. That is, either the first `k` that iteritems() gives you, or "No colour found".
Connection to MySql server fails - Python Question: I'm trying to connect to mySql database using Python. The database is situated on free webhosting server webzdarma.cz. I use `mysql.connector.connect` and all of my arguments are correct in my opinion. The information about connecting to the database are: This information is for PHP but I suppose it should work with Python: Server: mysql.webzdarma.cz Username: flat Database: flat Password: xxxx This is my code: # -*- coding: utf-8 -*- import mysql.connector cnx = mysql.connector.connect(user='flat', password='xxxx', host='mysql.webzdarma.cz', database='flat') When try to run this code the error occure: Traceback (most recent call last): File "C:/Users/Python/PycharmProjects/Flat/Flat.py", line 6, in <module> database='flat') File "C:\Python27\lib\site-packages\mysql\connector\__init__.py", line 159, in connect return MySQLConnection(*args, **kwargs) File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 129, in __init__ self.connect(**kwargs) File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 454, in connect self._open_connection() File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 417, in _open_connection self._socket.open_connection() File "C:\Python27\lib\site-packages\mysql\connector\network.py", line 470, in open_connection errno=2003, values=(self.get_address(), _strioerror(err))) File "C:\Python27\lib\site-packages\mysql\connector\errors.py", line 181, in __init__ self.msg = self.msg % values UnicodeDecodeError: 'ascii' codec can't decode byte 0xf8 in position 15: ordinal not in range(128) This error is raised because program recieved message in czech language about failed connection. Do anybody know what am I doing wrong? Answer: import MySQLdb db = MySQLdb.connect(host="mysql.webzdarma.cz", user="flat", passwd="xxxx", db="flat") cur = db.cursor() cur.execute("SELECT * FROM YOUR_TABLE_NAME") res = cur.fetchall() Try this it will work for sure. for more details follow question asked [How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a- mysql-database-in-python)
os.rename() error no such file or folder exists Question: I have been trying to create a python script that logs my data into a .dat file called 'log.dat' and every minute, rename log.dat to something else and just start writing the incoming log data to a new, empty log.dat file. But however my os.rename line is creating a error and I have been trying to debug it for so long but it is not helping. I keep getting the same error saying Error : Traceback (most recent call last):rov sel.:0; homenet:0(-1); current net:0; File "tracer.py", line 56, in <module> main() File "tracer.py", line 44, in main os.rename("/home/debian/fname", "/home/debian/log-{}.dat".format(time.strftime("%y%m%d%H%M%S"))) OSError: [Errno 2] No such file or directory This is my code : from __future__ import print_function def main(): #!/usr/bin/python # get lines of text from serial port, save them to a file import serial, io import time import os s = open('log.dat', 'w') log = time.strftime("%Y%m%d-%H%M%S") s = open(log + '.dat', 'w') delete = 'cat /dev/null > log.dat' addr = '/dev/ttyACM0' # serial port to read data from baud = 9600 # baud rate for serial port fname = 'log.dat' # log file to save data in fmode = 'a' # log file mode = append with serial.Serial(addr,9600) as pt, open(fname,fmode) as outf: spb = io.TextIOWrapper(io.BufferedRWPair(pt,pt,1), encoding='ascii', errors='ignore', newline='\r',line_buffering=$ spb.readline() while (1): now = time.time() with open(fname,fmode) as outf: while (time.time() - now) < 60: x = spb.readline() # read one line of text from serial$ print (x,end='') # echo line of text on-screen outf.write(x) # write line of text to file outf.flush() # make sure it actually gets written os.rename("/home/debian/fname", "/home/debian/log- {}.dat".format(time.strftime("%y%m%d%H%M%S"))) if __name__ == '__main__': main() I don't understand what am I doing wrong here. Any suggestion or help is deeply appreciated. Answer: try : os.rename("/home/debian/"+fname, "/home/debian/log- {}.dat".format(time.strftime("%y%m%d%H%M%S"))) or: os.rename("/home/debian/log.dat", "/home/debian/log- {}.dat".format(time.strftime("%y%m%d%H%M%S")))
Jython inside IDE ok, outside IDE, "no os specific module found"? Question: I already had the Jython interpreter working. But when changing from java 1.7u45 to java 8, it only runs inside the IDE. My project uses Jython2.5.3. All standard python modules are packaged into a zip file and put on the java classpath. Now Jython fails finding 'os' reporting: Traceback (most recent call last): File "a.py", line 36, in <module> import b.c as c File "c.py", line 1, in <module> import os File "__pyclasspath__/os.py", line 132, in <module> ImportError: no os specific module found I compared VM settings using JVisualVM between starting my app from a command- file and from the IDE. No glaring differences. I also changed the command file to use JDK1.8.0 (as netbeans startsup) instead JRE1.8.0 I also changed the command file to run the IDE generated .class files, instead of the production jar. I also added the "-XDebug" to the command-file version to match the IDE settings When checking with VisualVM: = the JVM is exactly the same, = the JVM arguments are exactly the (same except that Netbeans has "Xrunjdwp") = System properties almost identical: * 'java.library.path' is identical * jars on the 'java.class.path' are same, although the jars are have different paths. * But python.console.encoding=cp437 is missing in the command-file version (How does IDE introduce this one?) * user.dir is different I don't know what to do/check next. Hope someone has an idea. Thanks **UPDATE** Seems that the Jython internal variable 'sys.builtin_module_names' which is a set, content differs in each scenario. Outside IDE, 'nt' and 'jffi' are missing. os.py raises the exception "ImportError: no os specific module found". if the set does not contain any of * posix * nt * os2 * ce * riscos * ibmi **UPDATE 2** Found it.. turned out that Jython2.5.1 was mixed with a zip of modules of Jython2.5.3 Answer: Turned out that Jython2.5.1 interpreter was mixed with the zip-of-the- standard-modules of Jython2.5.3 I had the interpreter version and zip-of-standard-modules mixed-up before, but this time the interpreter had the minor version, which i didn't see comming.
nosetests framework: how to pass environment variables to my tests? Question: I have a test suite that gets executed as a part of a larger build framework, written in Python. Some of the tests require parameters, which I want to pass using environment variables. Apparently the nosetests runner has an `env` parameter, which does what I want, [according to the documentation.](http://nose.readthedocs.org/en/latest/api/core.html#nose.core.run) It seems, however, that it does not work as thought it should? Here's a minimal test script that exemplifies the problem: #!/usr/bin/env python # pip install nose import os, nose, unittest class Test(unittest.TestCase): def test_env(self): self.assertEquals(os.environ.get('HELLO'), 'WORLD') if __name__ == '__main__': nose.run(env={'HELLO': 'WORLD'}) The assertion fails, because the `env` parameter does not get passed to the test. Does anyone know why? NB: I worked around the problem by launching the console `nosetests` tool: #!/usr/bin/env python import sys, os, nose, unittest, subprocess class Test(unittest.TestCase): def test_env(self): self.assertEquals(os.environ.get('HELLO'), 'WORLD') if __name__ == '__main__': subprocess.Popen(['nosetests', sys.argv[0]], env={'HELLO': 'WORLD'}).wait() However, this feels like a kludge, and I'd still be interested in learning to use `nose.run()` properly. Answer: I couldn't get `env` to behave itself either, but I have come up with a solution that I consider slighly less kludgy than opening a subprocess. You can modify the `os.environ` variable before you call `nose.run()`, and as long as the tests are running in the same process, the tests will all see the modified `os.environ`: #!/usr/bin/env python import os, nose, unittest class Test(unittest.TestCase): def test_env(self): self.assertEquals(os.environ.get('HELLO'), 'WORLD') if __name__ == '__main__': os.environ["HELLO"] = "WORLD" nose.run()
python-requests - user-agent is being overriden Question: I have logindata = { 'username': 'me', 'password': 'blbla' } payload = {'from':'me', 'lang':'en', 'url':csv_url} headers = { 'User-Agent': 'Mozilla/5.0' } api_url = 'http://dev.mypage.com/admin/app/import/' with requests.Session() as s: s.post(api_url, data=json.dumps(logindata), headers=headers) print s.headers # An authorised request. r = s.get(api_url, params=payload, headers=headers) I am getting rejected but it is because of 403 forbidden. And I printed the headers, I get: ..'User-Agent': 'python-requests/2.2.1 CPython/2.7.5 Windows/7'.. Why is my `'User-Agent': 'Mozilla/5.0'` getting overriden? what am I missing here? Answer: `headers` _are not kept inside session_ this way. You need to either explicitly pass them every time you make a request, or set the [`s.headers`](http://docs.python- requests.org/en/latest/api/?highlight=session#requests.Session.headers) once: with requests.Session() as s: s.headers = {'User-Agent': 'Mozilla/5.0'} You can check that the correct headers were sent via inspecting `response.request.headers`: with requests.Session() as s: s.headers = {'User-Agent': 'Mozilla/5.0'} r = s.post(api_url, data=json.dumps(logindata)) print(r.request.headers) Also see how the [`Session` class](https://github.com/kennethreitz/requests/blob/master/requests/sessions.py#L263) is implemented - every time you make a request [it merges the `request.headers` with `headers`](https://github.com/kennethreitz/requests/blob/master/requests/sessions.py#L374) you have set on the session object: headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
Python regex to parse semi-fixed width file Question: I have a data file that is essentially a fixed-width text file. There are a variable number of spaces and positioning in the text. I'm trying to parse the file into a list with python and can't figure out the appropriate regex (of course am open to non-regex options too). Date Run By Level 1 Level 2 Level 3 Level 4 Level 5 Level 6 Level 7 Level 8 Level 9 11-15-2014 12:27:43 AM 1 ** 259.0 11-15-2014 7:47:09 AM 1 ** 98.0 11-15-2014 3:45:07 PM 1 ** 785.0 11-16-2014 12:27:43 AM 1 ** 245.0 11-16-2014 7:51:36 AM 1 ** 96.0 11-16-2014 3:43:12 PM 1 ** 788.0 11-17-2014 12:27:43 AM 1 ** 248.0 11-17-2014 7:51:21 AM 1 ** 104.0 11-17-2014 12:45:57 PM 1 ** 97.0 257.0 793.0 11-17-2014 3:46:33 PM 1 ** 792.0 11-18-2014 12:32:31 AM 1 ** 253.0 11-18-2014 7:50:31 AM 1 ** 104.0 11-18-2014 3:48:43 PM 1 ** 781.0 11-19-2014 12:30:36 AM 1 ** 260.0 11-19-2014 8:40:26 AM 1 ** 102.0 11-19-2014 3:47:45 PM 1 ** 803.0 11-20-2014 12:28:40 AM 1 ** 243.0 11-20-2014 7:53:38 AM 1 ** 107.0 11-20-2014 3:43:55 PM 1 ** 787.0 11-21-2014 1:03:45 AM 0 PS 245.0 11-21-2014 7:52:55 AM 1 ** 101.0 11-21-2014 3:44:09 PM 1 ** 789.0 11-22-2014 12:37:26 AM 1 ** 250.0 11-22-2014 7:49:55 AM 1 ** 103.0 Thus far I've tried: for line in f: line = re.split(r' (?=[A-Z])| (?=[0-9])| ',line) However, I don't get even alignment of the columns. I need them to line up for use downstream. The desired output is (sorry for the limited number of rows, parsing it manually is deadly!). ['Date', '', 'Run', 'By', 'Level 1', 'Level 2', 'Level 3', 'Level 4', 'Level 5', 'Level 6', 'Level 7', 'Level 8', 'Level 9','\r\n'] ['\r\n'] ['\r\n'] ['11-15-2014', '12:27:43', 'AM 1', '**', '', '259.0', '', '', '', '', '', '', '', '\r\n'] ['11-15-2014', '7:47:09', 'AM 1', '**', '98.0', '', '', '', '', '', '', '', '', '\r\n'] ['11-15-2014', '3:45:07', 'PM 1', '**', '', '', '785.0', '', '', '', '', '', '', '\r\n'] ... ... ['11-17-2014', '12:45:57', 'PM 1', '**', '97.0', '257.0', '793.0', '', '', '', '', '', '', '\r\n'] In essence 13 items followed by a line break; combining date and time into a single field would be fine, mostly I need the dates and three levels to line up properly; there are only values for Level 1, Level 2, and Level 3. Values are usually a single level/row, but occasionally there are all three (as shown). Answer: I cannot say how reliable this is in a production environment, but it works on the example data. Given: txt='''\ Date Run By Level 1 Level 2 Level 3 Level 4 Level 5 Level 6 Level 7 Level 8 Level 9 11-15-2014 12:27:43 AM 1 ** 259.0 11-15-2014 7:47:09 AM 1 ** 98.0 11-15-2014 3:45:07 PM 1 ** 785.0 11-16-2014 12:27:43 AM 1 ** 245.0 11-16-2014 7:51:36 AM 1 ** 96.0 11-16-2014 3:43:12 PM 1 ** 788.0 11-17-2014 12:27:43 AM 1 ** 248.0 11-17-2014 7:51:21 AM 1 ** 104.0 11-17-2014 12:45:57 PM 1 ** 97.0 257.0 793.0 11-17-2014 3:46:33 PM 1 ** 792.0 11-18-2014 12:32:31 AM 1 ** 253.0 11-18-2014 7:50:31 AM 1 ** 104.0 11-18-2014 3:48:43 PM 1 ** 781.0 11-19-2014 12:30:36 AM 1 ** 260.0 11-19-2014 8:40:26 AM 1 ** 102.0 11-19-2014 3:47:45 PM 1 ** 803.0 11-20-2014 12:28:40 AM 1 ** 243.0 11-20-2014 7:53:38 AM 1 ** 107.0 11-20-2014 3:43:55 PM 1 ** 787.0 11-21-2014 1:03:45 AM 0 PS 245.0 11-21-2014 7:52:55 AM 1 ** 101.0 11-21-2014 3:44:09 PM 1 ** 789.0 11-22-2014 12:37:26 AM 1 ** 250.0 11-22-2014 7:49:55 AM 1 ** 103.0 ''' Try: import re data=txt.splitlines() header=data.pop(0) for line in data: m=re.search(r'^([\d\-\s:]+)(AM|PM)\s+(\d)\s+(..)([\s\d\.]+)$', line) if m: l=[] l.append(m.group(1)+m.group(2)) l.append(m.group(3)) l.append(m.group(4)) l.append([e.strip() for e in re.findall(r'(\s{15,16}|\s*\d+\.\d)', m.group(5))]) print l Prints: ['11-15-2014 12:27:43 AM', '1', '**', ['', '259.0', '', '', '', '', '', '']] ['11-15-2014 7:47:09 AM', '1', '**', ['98.0', '', '', '', '', '', '', '']] ['11-15-2014 3:45:07 PM', '1', '**', ['', '', '785.0', '', '', '', '', '']] ['11-16-2014 12:27:43 AM', '1', '**', ['', '245.0', '', '', '', '', '', '']] ['11-16-2014 7:51:36 AM', '1', '**', ['96.0', '', '', '', '', '', '', '']] ['11-16-2014 3:43:12 PM', '1', '**', ['', '', '788.0', '', '', '', '', '']] ['11-17-2014 12:27:43 AM', '1', '**', ['', '248.0', '', '', '', '', '', '']] ['11-17-2014 7:51:21 AM', '1', '**', ['104.0', '', '', '', '', '', '', '']] ['11-17-2014 12:45:57 PM', '1', '**', ['97.0', '257.0', '793.0', '', '', '', '', '']] ['11-17-2014 3:46:33 PM', '1', '**', ['', '', '792.0', '', '', '', '', '']] ['11-18-2014 12:32:31 AM', '1', '**', ['', '253.0', '', '', '', '', '', '']] ['11-18-2014 7:50:31 AM', '1', '**', ['104.0', '', '', '', '', '', '', '']] ['11-18-2014 3:48:43 PM', '1', '**', ['', '', '781.0', '', '', '', '', '']] ['11-19-2014 12:30:36 AM', '1', '**', ['', '260.0', '', '', '', '', '', '']] ['11-19-2014 8:40:26 AM', '1', '**', ['102.0', '', '', '', '', '', '', '']] ['11-19-2014 3:47:45 PM', '1', '**', ['', '', '803.0', '', '', '', '', '']] ['11-20-2014 12:28:40 AM', '1', '**', ['', '243.0', '', '', '', '', '', '']] ['11-20-2014 7:53:38 AM', '1', '**', ['107.0', '', '', '', '', '', '', '']] ['11-20-2014 3:43:55 PM', '1', '**', ['', '', '787.0', '', '', '', '', '']] ['11-21-2014 1:03:45 AM', '0', 'PS', ['', '245.0', '', '', '', '', '', '']] ['11-21-2014 7:52:55 AM', '1', '**', ['101.0', '', '', '', '', '', '', '']] ['11-21-2014 3:44:09 PM', '1', '**', ['', '', '789.0', '', '', '', '', '']] ['11-22-2014 12:37:26 AM', '1', '**', ['', '250.0', '', '', '', '', '', '']] ['11-22-2014 7:49:55 AM', '1', '**', ['103.0', '']]
Installing Orange into a virtualenv Question: Linux Mint 17.1 with native Python 2.7.6. All pre-reqs listed in the INSTALL.txt: python-numpy libqt4-opengl-dev libqt4-dev cmake qt4-qmake python-sip-dev python-qt4 python-qt4-dev python- qwt5-qt4 python-sip graphviz python-networkx python-imaging python-qt4-gl build-essential python-pip python-scipy python-pyparsing ipython python- matplotlib Has anyone installed orange into a virtualenv? I am trying to install Orange into a virtualenv using pip as follows: $ cd ~/venv/ $ mkdir orange $ cd orange $ virtualenv venv $ source venv/bin/activate $ pip install --global-option="build_pyqt_ext" orange The install begins well enough: Collecting orange Using cached Orange-2.7.8.tar.gz Requirement already satisfied (use --upgrade to upgrade): setuptools in ./venv/lib/python2.7/site-packages (from orange) Collecting numpy (from orange) Using cached numpy-1.9.1.tar.gz Running from numpy source directory. Collecting scipy (from orange) Using cached scipy-0.15.0.tar.gz At this point there is along pause (compilation) and eventually a long list of errors, which I've posted here: <http://pastebin.com/VZWyGjfz> and I've included the last few lines below: Complete output from command /home/citmkd/venv/orange/venv/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-dLY2eU/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" build_pyqt_ext install --record /tmp/pip-r8dA2D-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/citmkd/venv/orange/venv/include/site/python2.7: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-dLY2eU/scipy/setup.py", line 249, in <module> setup_package() File "/tmp/pip-build-dLY2eU/scipy/setup.py", line 237, in setup_package from numpy.distutils.core import setup ImportError: No module named numpy.distutils.core ---------------------------------------- Command "/home/citmkd/venv/orange/venv/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-dLY2eU/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" build_pyqt_ext install --record /tmp/pip-r8dA2D-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/citmkd/venv/orange/venv/include/site/python2.7" failed with error code 1 in /tmp/pip-build-dLY2eU/scipy Answer: This seems to be an error in pip or scipy's setup script (can you try installing numpy, scipy individually i.e `pip install numpy && pip install scipy`). Note that in any case you should use the system provided numpy, scipy, ... packages by using `virtualenv --system-site-packages venv` to create the virtual environment.
Trouble using date from pyodbc query Question: I am working with an Access 2003 database using python 2.7 connecting with pyodbc. Windows 7 I am having trouble making sense of a date query. In the trivial example below, the first query collects the user's date of birth 'dob' which in the database is a datetime.datetime object. print row >>>> ('A0103', 'Susan', datetime.datetime(1986, 4, 10, 0, 0)) When we collect the date & print it dob = res[2] we get print dob >>>> 1986-04-10 00:00:00 print type(dob) >>> type 'datetime.datetime' But when used in the second query. "SELECT name FROM users WHERE dob = %s" % dob" we get: ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'dob = 1986-04-10 00:00:00'. (-3100) (SQLExecDirectW)") extracting just the date & using datetime.date to recreate a datetime object: y, m, d = dob.year, dob.month, dob.day mydate = date(y, m, d) allows for a sucsesfull query transaction, the query "SELECT id, name FROM Siswa WHERE name ='%s' AND dob => %s" % (nama, mydate) yields ('A0103', 'Susan', datetime.datetime(1986, 4, 10, 0, 0) but would also deliver any other Susan that were younger I would expect the query "SELECT id, name FROM Siswa WHERE name ='%s' AND dob = %s" % (nama, mydate) to yield ('A0103', 'Susan', datetime.datetime(1986, 4, 10, 0, 0) but it comes up empty. What am I missing ? from datetime import datetime, date sql = "SELECT name, dob FROM users" result1 = cur.execute(sql).fetchall() for row in result1: print row name, dob = row[1], row[2] print dob try: sql = "SELECT name FROM users WHERE dob = %s" % dob result2 = cur.execute(sql).fetchall() print result except: y, m, d = dob.year, dob.month, dob.day mydate = date(y, m, d) sql = "SELECT name FROM users WHERE dob => %s" % dob result2 = cur.execute(sql).fetchall() print result sql = "SELECT name FROM users WHERE dob = %s" % dob result2 = cur.execute(sql).fetchall() print result Answer: I run with the same problem, of not being able to query dates. My solution turned out to be: SELECT name FROM users WHERE DateValue(registered) <= '20-04-2015' So `DateValue()` seems to be the solution for comparing dates.
Converting an unknown data structure to a known data structure in Python Question: I recently used an API to pull in some data from a platform I use. But the problem is, the data that I pulled, is not a recognized data structure. It's almost a list of dictionaries, with some extra stuff. I need to know how can I convert it to a recognized data structure. I don't necessarily need the code to do so, just a north on what I need to study would be helpful already. I'm new to Python and I don't have a lot of coding experience. I have a file with this data in each line, this is a sample line from the file: [<OrderProducts at 0x24333f0, {'price_ex_tax': '99.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 3, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '99.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 83, 'price_inc_tax': '99.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': None, 'option_set_id': 15, 'wrapping_message': '', 'weight': '3.0000', 'refund_amount': '0.0000', 'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '99.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '99.0000', 'total_ex_tax': '99.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'S-TIM-BAC-STD', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'University of Timbuktu Bachelor Set', 'is_bundled_product ': False, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [{'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 95, 'display_value': 'Cambridge-Style Bachelor Gown, Size L', 'id': 2, 'option_id': 19, 'value': '77', 'display_name': 'Gown size', 'name': 'Bachelor gown size', 'order_product_id': 3}, {'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 97, 'display_value': 'Bachelor and Masters Trencher, Size L', 'id': 3, 'option_id': 20, 'value': '80', 'display_name': 'Trencher size', 'name': 'Trencher size', 'order_product_id': 3}], 'base_cost_price': '0.0000'}>, <OrderProducts at 0x2433420, {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 4, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 80, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'G-CAM-BAC-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Cambridge-Style Bachelor Gown, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}>, <OrderProducts at 0x2433450, {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 5, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 87, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'C-STD-B&M-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Bachelor and Masters Trencher, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}>] EDIT: This is the code I got: import ast import re order_item = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I) with open('allOrderProducts2') as inf: for line in inf: order = [ast.literal_eval(op) for op in re.findall(order_item, line)] # ta-da! Now do something with the order f = open("test", "w", encoding='utf-8') f.write("\n".join(map(lambda x: str(x), order))) f.close() Answer: What you have is a list (`[ ... ]`) containing three `OrderProducts` objects which, when printed, represent themselves as dictionaries (`{ key1: value1, key2: value2 }`). * * * **Edit:** ok, you have the **string representation** of three OrderProducts etc. So the first order of business is to convert to actual Python data structures, like so: import ast import re order_items = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I).findall with open(FILENAME) as inf: for line in inf: order = [ast.literal_eval(op) for op in order_items(line)] # ta-da! Now do something with the order then continue as before: * * * **Edit2:** Cleaned up a bit: import re DATA = "allOrderProducts2" RESULT = "test" order_items = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I).findall with open(DATA) as inf, open(RESULT, "w", "utf-8") as outf: # Instead of reading each line separately, # we can just parse the whole file in one gulp for item_str in order_items(inf.read()): # Also no need to convert the data # just to cast it back to a string again outf.write(item_str + "\n") Then, when reading the RESULT file back in, you can pass each line to `ast.literal_eval` to turn it back into a dict. * * * Looking at the `id` and `parent_order_product_id` fields, it looks like what you have is a "University of Timbuktu Bachelor Set" consisting of a "Cambridge-Style Bachelor Gown, Size L" and "Bachelor and Masters Trencher, Size L" with a package price of 99.0 (units unknown) and no tax. I wrote a quick script to figure out what a default OrderProduct looks like: from collections import Counter from pprint import pprint as pp data = [ {'price_ex_tax': '99.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 3, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '99.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 83, 'price_inc_tax': '99.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': None, 'option_set_id': 15, 'wrapping_message': '', 'weight': '3.0000', 'refund_amount': '0.0000', 'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '99.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '99.0000', 'total_ex_tax': '99.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'S-TIM-BAC-STD', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'University of Timbuktu Bachelor Set', 'is_bundled_product ': False, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [{'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 95, 'display_value': 'Cambridge-Style Bachelor Gown, Size L', 'id': 2, 'option_id': 19, 'value': '77', 'display_name': 'Gown size', 'name': 'Bachelor gown size', 'order_product_id': 3}, {'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 97, 'display_value': 'Bachelor and Masters Trencher, Size L', 'id': 3, 'option_id': 20, 'value': '80', 'display_name': 'Trencher size', 'name': 'Trencher size', 'order_product_id': 3}], 'base_cost_price': '0.0000'}, {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 4, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 80, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'G-CAM-BAC-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Cambridge-Style Bachelor Gown, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}, {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 5, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 87, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'C-STD-B&M-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Bachelor and Masters Trencher, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'} ] def get_defaults(lst_of_dct): defaults = {} majority = (len(data) + 1) // 2 for key in lst_of_dct[0]: try: ctr = Counter(d[key] for d in lst_of_dct) value,count = ctr.most_common(1)[0] defaults[key] = value if count >= majority else "" except TypeError: # Counter doesn't like unhashable type ie lists defaults[key] = [] return defaults defaults = get_defaults(data) pp(defaults) which gives {'applied_discounts': [], 'base_cost_price': '0.0000', 'base_price': '0.0000', 'base_total': '0.0000', 'base_wrapping_cost': '0.0000', 'bin_picking_number': '', 'configurable_fields': [], 'cost_price_ex_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'cost_price_tax': '0.0000', 'ebay_item_id': '', 'ebay_transaction_id': '', 'event_date': '', 'event_name': None, 'fixed_shipping_cost': '0.0000', 'id': '', 'is_bundled_product ': True, 'is_refunded': False, 'name': '', 'option_set_id': None, 'order_address_id': 2, # should be 0 'order_id': 614534, # should be 0 'parent_order_product_id': 3, # should be 0 'price_ex_tax': '0.0000', 'price_inc_tax': '0.0000', 'price_tax': '0.0000', 'product_id': '', 'product_options': [], 'quantity': 1, # should be 0 'quantity_shipped': 0, 'refund_amount': '0.0000', 'return_id': 0, 'sku': '', 'total_ex_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_tax': '0.0000', 'type': 'physical', 'weight': '0.0000', 'wrapping_cost_ex_tax': '0.0000', 'wrapping_cost_inc_tax': '0.0000', 'wrapping_cost_tax': '0.0000', 'wrapping_message': '', 'wrapping_name': ''} After manually checking and fixing some bad default values, def strip_defaults(dct, defaults): return {key:value for key,value in dct.items() if value != defaults[key]} res = [strip_defaults(d, defaults) for d in data] pp(res) which removes all default-valued fields and gives us a slightly more readable version: [{'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}], 'base_price': '99.0000', 'base_total': '99.0000', 'id': 3, 'is_bundled_product ': False, 'name': 'University of Timbuktu Bachelor Set', 'option_set_id': 15, 'order_address_id': 2, 'order_id': 614534, 'price_ex_tax': '99.0000', 'price_inc_tax': '99.0000', 'product_id': 83, 'product_options': [{'display_name': 'Gown size', 'display_style': 'Pick list', 'display_value': 'Cambridge-Style Bachelor Gown, ' 'Size L', 'id': 2, 'name': 'Bachelor gown size', 'option_id': 19, 'order_product_id': 3, 'product_option_id': 95, 'type': 'Product list', 'value': '77'}, {'display_name': 'Trencher size', 'display_style': 'Pick list', 'display_value': 'Bachelor and Masters Trencher, ' 'Size L', 'id': 3, 'name': 'Trencher size', 'option_id': 20, 'order_product_id': 3, 'product_option_id': 97, 'type': 'Product list', 'value': '80'}], 'quantity': 1, 'sku': 'S-TIM-BAC-STD', 'total_ex_tax': '99.0000', 'total_inc_tax': '99.0000', 'weight': '3.0000'}, {'id': 4, 'name': 'Cambridge-Style Bachelor Gown, Size L', 'order_address_id': 2, 'order_id': 614534, 'parent_order_product_id': 3, 'product_id': 80, 'quantity': 1, 'sku': 'G-CAM-BAC-L'}, {'id': 5, 'name': 'Bachelor and Masters Trencher, Size L', 'order_address_id': 2, 'order_id': 614534, 'parent_order_product_id': 3, 'product_id': 87, 'quantity': 1, 'sku': 'C-STD-B&M-L'}]
How can I start to write Unit test in web Scrapy using python? Question: class AljazeeraSpider(XMLFeedSpider): name = "aljazeera" allowed_domains = ["aljazeera.com"] start_urls = [ 'http://www.aljazeera.com/', ] def parse(self, response): hxs = HtmlXPathSelector(response) # The xPath selector titles = hxs.select('//div[contains(@class,"SkyScrapperBoxes")]/div[contains(@class,"skyscLines")]') if not titles: MailNotify().send_mail("Aljazeera", "Scraper Report") items = [] for titles in titles: item = NewsItem() item['title'] = escape(''.join(titles.select('a/text()').extract())) item['link'] = "http://www.aljazeera.com" + escape(''.join(titles.select('a/@href').extract())) item['description'] = '' item = Request(item['link'], meta={'item': item}, callback=self.parse_detail) items.append(item) return items def parse_detail(self, response): item = response.meta['item'] sel = HtmlXPathSelector(response) detail = sel.select('//td[@class = "DetailedSummary"]') item['details'] = remove_html_tags(escape(''.join(detail.select('p').extract()))) item['location'] = '' published_date = sel.select('//span[@id = "ctl00_cphBody_lblDate"]') item['published_date'] = escape(''.join(published_date.select('text()').extract())) return item I am currently working on Scrapy to crawl the website. I have some knowledge about unittest in python. But,How can I write the unittest to check that link is working, and `item['location']`, `item['details']` are returning the value or not? I have learned Scrapy contract but cannot understand anything.So, how can write the unittest in this case? Answer: If we are talking specifically about how to test the spiders (not pipelines, or loaders), then what we did is provided a "fake response" from a local HTML file. Sample code: def fake_response(file_name=None, url=None): """Create a Scrapy fake HTTP response from a HTML file""" if not url: url = 'http://www.example.com' request = Request(url=url) if file_name: if not file_name[0] == '/': responses_dir = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(responses_dir, file_name) else: file_path = file_name file_content = open(file_path, 'r').read() else: file_content = '' response = TextResponse(url=url, request=request, body=file_content, encoding='utf-8') return response Then, in your `TestCase` class, call the `fake_response()` function and feed the response to the `parse()` callback: from unittest.case import TestCase class MyTestCase(TestCase): def setUp(self): self.spider = MySpider() def test_parse(self): response = fake_response('input.html') item = self.spider.parse(response) self.assertEqual(item['title'], 'My Title') # ... * * * Aside from that, you should definitely start using [`Item Loaders`](http://doc.scrapy.org/en/latest/topics/loaders.html) with input and output processors - this would help to achieve a better modularity and, hence, isolation - spider would just yield item instances, data preparation and modification would be incapsulated inside the loader, which you would test separately.
Multiple requests using urllib2.urlopen() at the same time Question: My question is this; Is it possible to request two different URLs at the same time? What I'm trying to do, is use a Python script to call requests from two different URLs at the same time. Making two PHP scripts run simultaneously (on different servers, running a terminal command). My issue is that I can't do them right after each other, because they each take a specific time to do something, and need to run at the same time, and end at the same time. Is this possible using urllib2.urlopen? If so, how would I go about doing this? If not, then what would be a good method to do so? Currently I have something like: import urllib2 ... if cmd.startswith('!command '): cmdTime = cmd.replace('!command ','',1) urllib2.urlopen('http://example.com/page.php?time='+cmdTime) urllib2.urlopen('http://example2.com/page.php?time='+cmdTime) print "Finished." My issue is that they don't run at the same time. If I did !command 60, then it'll run site.com for 60 seconds, then go to site2.com for 60 seconds and run that one. Answer: I would suggest you to create a function for getting the parsed source, where you should pass a list of url's to be crawled in a list as argument. Later on loop on the list of URL's and use threading. I will post some sample code for you, please modify it accordingly. import threading import urllib2 def execute_url_list(urls_list): if cmd.startswith('!command '): cmdTime = cmd.replace('!command ','',1) for url in urls_list: urllib2.urlopen(url+cmdTime) urls_list = ['url1', 'url2'] for k in urls_list: processes = [] process = threading.Thread(target=execute_url_list, args=[k]) process.setDaemon(True) process.start() processes.append(process) for process in processes: process.join()
Compare date with current date in python Question: How do I compare a datetime object of this format "Thu, 15 Jan 2015 06:35:37 GMT" with the current time ? Answer: The easiest way is with the `dateutil` package. First install `dateutil` and then: from dateutil.parser import parse parsed_time = parse("Thu, 15 Jan 2015 06:35:37 GMT") Then you can do `from datetime import datetime` and get the current time with `datetime.now()`, and you'll have two datetime objects you can compare however you like. If you can't use `dateutil`, you can still do it with `datetime.strptime()`, but you'll have to specify the date string exactly which is quite fiddly. Refer to the standard library documentation in that case.
reading a file, taking file line content, then using content as parameters for class method definitions Python Question: What I am trying to do here is read a line of a file. If the content in the file meets the correct criteria execute one of the definitions in my class. The thing is I have no clue on what kind of code I need for this. here is what I have so far: class Score: # class to hold a running score, from object to parameter # also to set number of scores that contribute to total of 1 def __init__(self): #initalizes the running score and score input accumilators self.runScore = 0 self.scoreInputs = 0 def updateOne (self, amount): #updates running score by amount and Score input by 1 self.runScore += amount self.scoreInputs += 1 def updateMany(self,lst): #updates running score by the sum of the list and score inputs by the amount of # number of items in the list self.runScore += sum(lst) self.scoreInputs += len(lst) def get(self): #returns the current score based on total amount scored print(self.runScore) def average(self): #returns the average of the scores that have contributed to the total socre print(self.runScore // self.scoreInputs) def processScores (file): with open('file','r') as f: for line in f: line The Idea is that processScores will be ran. As the code reads the file line by line if it finds a certian marker in the line example G then the next line it reads shall be input into the def updateOne. But thats just an example. Anyideas on what I can do better? Thank you Answer: It would be better to pass a Score instance to the function and have it update it as it reads the file. def processScores(file, score): with open(file, 'r') as f: for line in f: if line[0] == 'G': amount = int(next(f)) # read next line & convert to integer score.UpdateOne(amount) However it would be even better than that to make it a method to provide better [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_%28object- oriented_programming%29), or bundling of data and functions within it -- which is an important principle of object-oriented programming. This way if you change what information is stored in instances of class, how it updating is done, or how the data file formatted, you have to make changes in one place. def processScores(self, file): with open(file, 'r') as f: for line in f: if line[0] == 'G': amount = int(next(f)) # read next line & convert to integer self.UpdateOne(amount)
Python Matplotlib: black squares when saving eps of plot of masked array, why? Question: When I run the following code: import numpy as np import matplotlib import matplotlib.pyplot as plt x_data = np.random.randn(10000) y_data = np.random.randn(10000) hist, xbins, ybins = np.histogram2d(x_data, y_data, bins=100) hist_masked = np.ma.masked_where(hist<1e-3, hist) cmap = matplotlib.cm.jet #cmap.set_bad('w',1.) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.imshow(hist_masked.T, interpolation = 'none', cmap = cmap) plt.savefig('test.eps',transparent=False) plt.show() the plot looks fine on screen but the eps file has extra black "squares". Why? These black squares are present only if I save the plot as eps and even with eps I can get rid of them by uncommenting the "set_bad" command in the code. Why is that command necessary for the plot to work if I am plotting a masked array? Thanks! Answer: The masked array `hist_masked` sets the _bad_ values to `np.nan` and the colormaps in matplotlib have a predefined value for nans: In [5]: plt.cm.jet._rgba_bad Out[5]: (0.0, 0.0, 0.0, 0.0) So it is set to black and fully transparent by default. However, when you set `transparent=False` upon saving, these points actually become visible (since the alpha is set to 1). When you use: cmap.set_bad('w',1.) you set the _bad_ color to white (`'w'`), and therefore you will not see them in the resulting eps file. eps files can't handle transparency. However, you could consider saving to `pdf` and removing the flag `transparency=False`. This would also solve the issue.
Django Template Does Not Exist Question: I know this has been covered already but none of the solutions have worked for me. I have a basic django project and it cannot find the template. Here is my views.py: now = datetime.datetime.now() t = get_template('index.html') html = t.render(Context({'current_date' : now})) return HttpResponse(html) This is my TEMPLATE_DIRS in settings.py. The project is specified under INSTALLED_APPS TEMPLATE_DIRS = ( '/Users/Howie/Desktop/djangoCode/mysite/Movies/templates/', ) This is the error I get every time Template-loader postmortem: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: C:\Users\Howie\Desktop\djangoCode\mysite..\templates\index.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: C:\Python34\lib\site-packages\django-1.7.2-py3.4.egg\django\contrib\admin\templates\index.html (File does not exist) C:\Python34\lib\site-packages\django-1.7.2-py3.4.egg\django\contrib\auth\templates\index.html (File does not exist) C:\Users\Howie\Desktop\djangoCode\mysite\Movies\templates\index.html (File does not exist) I don't understand why django cant find my index.html file. I've tried moving the templates folder into the app itself(named Movies) and I've also had it in the root project folder but both of those didn't work. Any insight would be helpful. Answer: The [app_directories.Loader](https://docs.djangoproject.com/en/1.7/ref/templates/api/#django.template.loaders.app_directories.Loader) is enabled by default. This means you can put your template in an `app/templates` directory and be done. No need for TEMPLATE_DIRS and/or TEMPLATE_LOADERS settings. Just out of the box Django: project/app/views.py project/app/templates/index.html get_template('index.html') It's even better to [use subdirectories](https://docs.djangoproject.com/en/1.7/ref/templates/api/#using- subdirectories): project/app/views.py project/app/templates/app/index.html get_template('app/index.html') This to avoid a index.html from some other app to take precedence. If you really want a template folder in the root of your project, than don't use hardcoded paths. Do something like [this](https://github.com/twoscoops/django-twoscoops- project/blob/develop/project_name/project_name/settings/base.py): from os.path import abspath, dirname, join, normpath from sys import path SITE_ROOT = dirname(dirname(abspath(__file__))) TEMPLATE_DIRS = ( normpath(join(SITE_ROOT, 'templates')), )