text
stringlengths
226
34.5k
Editing csv file Python 3 - matching file content to the print output Question: I am having an issue with getting the contents of created csv file to show up as the print output. Code: import csv with open('test.csv', 'w', newline='') as csvfile: filewriter = csv.writer(csvfile, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['Spam'] * 2 + ['Baked Beans']) filewriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) with open('test.csv', newline='') as csvfile: filereader = csv.reader(csvfile, delimiter=' ', quotechar=',') for row in filereader: print(', '.join(row)) Output: Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam `test.csv` file: Spam Spam ,Baked Beans, Spam ,Lovely Spam, ,Wonderful Spam, _Notice the weird commas._ Desired contents of `test.csv` Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam Answer: The reason you are getting this output is because you are using comma `quotechar=','` to quote fields containing space which is your delimiter. That being said what you want is use `,` as delimiter which is the default [delimiter value](https://docs.python.org/3.5/library/csv.html#csv.Dialect.delimiter). import csv with open('test.csv', 'w', newline='') as csvfile: filewriter = csv.writer(csvfile) filewriter.writerow(['Spam'] * 2 + ['Baked Beans']) filewriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) The same thing apply if you want to read your `csv` file.
Printing Python output in HTML Question: I have a Python script (which works and outputs correctly when ran) but I am having trouble posting the output to a HTML page. No errors are being shown. I am new to Python. **PYTHON** import urllib2 def internet_on(): try: response=urllib2.urlopen('http://64.233.160.94',timeout=1) return '<img class="right" src="networkon.png" width="32" height="32">' except urllib2.URLError as err: pass return '<img class="right" src="networkoff.png" width="32" height="32">' output = internet_on() print output **HTML/AJAX/JAVASCRIPT** <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="style.css"> <script type="text/javascript"> function wifi() { $.ajax ({ type: "POST", urlurl: "file:///home/pi/Desktop/wifi.py", data: output, dataType: "html", success: function(responcew){ $("wifi").html(responcew); } }); } </script> </head> <body> <div id="topbar"> <span id="wifi"></span> </div> </body> </html> I have also tried: function wifi() { $.ajax ({ type: "POST", urlurl: "file:///home/pi/Desktop/wifi.py", data: output, dataType: "html" }); document.getElementById('wifi').innerHTML; } Answer: I don't understand why both times you have `urlurl` as the url parameter in your ajax post. However, even if you corrected that to `url`, it still won't work. You can't post to a file, you have to post to a URL that will be handled by some sort of server process. That could be CGI, but much better to use some kind of (micro-)framework. Also, you don't seem to have anything in your JS that would actually call the `wifi()` function.
creating MLP in python showing error Question: Iam a newbie in neural networks while creating MLP in python using opencv 3.1.0 error pops.The code is import cv2 import numpy as np import glob print 'Loading training data...' e0 = cv2.getTickCount() # load training data image_array = np.zeros((1, 38400)) label_array = np.zeros((1, 4), 'float') training_data = glob.glob('training_data/*.npz') for single_npz in training_data: with np.load(single_npz) as data: print data.files train_temp = data['train'] train_labels_temp = data['train_labels'] print train_temp.shape print train_labels_temp.shape image_array = np.vstack((image_array, train_temp)) label_array = np.vstack((label_array, train_labels_temp)) train = image_array[1:, :] train_labels = label_array[1:, :] print train.shape print train_labels.shape e00 = cv2.getTickCount() time0 = (e00 - e0)/ cv2.getTickFrequency() print 'Loading image duration:', time0 # set start time e1 = cv2.getTickCount() # create MLP layer_sizes = np.int32([38400, 32, 4]) model = cv2.ml.ANN_MLP_create() model.create(layer_sizes) criteria = (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 500, 0.0001) criteria2 = (cv2.TERM_CRITERIA_COUNT, 100, 0.001) params = dict(term_crit = criteria, train_method = cv2.ml.ANN_MLP_BACKPROP, bp_dw_scale = 0.001, bp_moment_scale = 0.0 ) print 'Training MLP ...' num_iter = model.train(train, train_labels, params = params ) # set end time e2 = cv2.getTickCount() time = (e2 - e1)/cv2.getTickFrequency() print 'Training duration:', time # save param model.save('mlp_xml/mlp.xml') print 'Ran for %d iterations' % num_iter ret, resp = model.predict(train) prediction = resp.argmax(-1) print 'Prediction:', prediction true_labels = train_labels.argmax(-1) print 'True labels:', true_labels print 'Testing...' train_rate = np.mean(prediction == true_labels) print 'Train rate: %f:' % (train_rate*100) this is the error AttributeError: 'cv2.ml_ANN_MLP' object has no attribute 'create' Answer: Based on this [code sample](https://github.com/opencv/opencv/blob/master/samples/python/letter_recog.py#L125), I would suggest setting the number of layers as follows: model.setLayerSizes(layer_sizes) You can also have a look at the [Learning OpenCV 3](https://books.google.co.uk/books?id=iNlOCwAAQBAJ&pg=PA214) book. I can't seem to be able to find a proper complete doc at the minute, but for the record here's what `dir(model)` gives: * calcError * clear * empty * getBackpropMomentumScale * getBackpropWeightScale * getDefaultName * getLayerSizes * getRpropDW0 * getRpropDWMax * getRpropDWMin * getRpropDWMinus * getRpropDWPlus * getTermCriteria * getTrainMethod * getVarCount * getWeights * isClassifier * isTrained * predict * save * setActivationFunction * setBackpropMomentumScale * setBackpropWeightScale * setLayerSizes * setRpropDW0 * setRpropDWMax * setRpropDWMin * setRpropDWMinus * setRpropDWPlus * setTermCriteria * setTrainMethod * train
How can I create folder in importing process [python] Question: How can I create a class that creates directories for both with 1. Initial values and 2. input arguments ? This is my code mypath.py import os myroot = 'D:\\pet' class path(object) dog = os.path.join(myroot, 'dog') cat = os.path.join(myroot, 'cat') # my 1st question (something like this) def __init__(self): for directory in dir(self): if not os.path.exists(directory): os.makedirs(directory) # my 2nd question (something like this) def append(self, newpath) for directory in dir(self): newdir = os.path.join(directory, newpath) if not os.path.exists(newdir): os.makedirs(newdir) # update attribute in self self.directory = newdir When I do import mypath I can see mypath.dog = 'D:\\pet\\dog' mypath.cat = 'D:\\pet\\cat' But they are not created, instead I manually have to do like this: os.mkdir(mypath.dog) os.mkdir(mypath.cat) So my question #1 is How can I make the class to automatically create every path whenever I import? and question #2 is How can I create a sub function .append() so that mypath.append('ishungry') to automatically update all attributes in path so that mypath.dog = 'D:\\pet\\dog\\ishungry' mypath.cat = 'D:\\pet\\cat\\ishungry' Thanks in advance! Answer: So the logic to make the directories exist in the objects __init__ method; this doesn't run upon import. That's why when you import the module, the directories are not made. To make them, you'd have to create an instance of the 'path' object: import mypath my_path= mypath.path() Is there a compelling reason to make these directories upon import instead of upon object initialization? It's generally considered a [code smell](https://en.wikipedia.org/wiki/Code_smell) to have this type of side effect upon module import. A cleaner way to do this might be to have an object that handles all the path stuff for you, and to work with that object directly: class PathManager(object): """Manages file system paths :param root: The base of all paths :type root: String :param top_dirs: The frist class directories we care about. :type top_dirs: List """ def __init__(self, root='D:\\pet', top_dirs=None) self.root = root self.top_dirs = [] if top_dirs is None else top_dirs self._config_dir() def _config_dir(self, new_dir=None) """Updates all managed paths to contain new_dir""" for folder in self.top_dirs: if new_dir is not None: directory = os.path.join(self.root, folder, new_dir) else: directory = os.path.join(self.root, folder) if not os.path.exists(directory): os.makedirs(directory) def append(self, new_dir): """Add a new subdirectory to all managed paths, then update the list of managed paths""" # add new paths to file system self._config_dir(new_dir=new_dir) # update class to know of update managed paths self.top_dirs = [os.path.join(self.root, x, new_dir) for x in self.top_dir] Then use it like: from mypath import PathManager # Creates the initial paths path_mgr = PathManager(top_dirs=['dog, 'cat']) # add a new subdir to managed path path_mgr.append('ishungry')
Check if string in the exact form of “<int1>,<int2>” in Python, without using regex, or try/catch Question: I'm converting a string of two integers into a tuple. I need to make sure my string is formatted exactly in the form of: "<int1>,<int2>" This is not a duplicate to an earlier question. Since that did not address restrictions I did not know about earlier. My parameter will be "4,5" for example. I'm not allowed to write other helper functions to check if they are formatted correctly. The checks must be done in a single function called convert_to_tuple I just looked at the project specs again, and I'm not allowed to import any new modules, so regex is off the table. I'm also not allowed to use try/catch either. Can you point me in the write direction? Thanks Here is my code for converting the string into a tuple. So I need some type of check for executing this code. if foo: s1 = "12,24" string_li = s1.split(',') num_li = [int(x) for x in string_li] num_tuple = tuple(num_li) return num_tuple else: empty_tuple = () return empty_tuple Answer: Does this work? (Edited to meet OP's requirements) def is_int(string): return string and set(string).issubset(set('1234567890')) def check_str(s): parts = s.split(',', 1) return len(parts) == 2 and is_int(parts[0]) and is_int(parts[1])
What does "see docstring of the instance object for more information" mean Question: I feel like this is a dumb question, but when I'm in an IPython notebook and I do help on some numpy/scipy function, like say stat.norm.rvs, it frequently says, about *args and **kargs, "see docstring of the instance object for more information". How do I see this docstring if not with help(stat.norm.rvs)? Answer: Don't feel dumb; sometimes it is hard to find the information you are looking for, especially when starting out. Moreover, much of the docstrings in `scipy.stats` are autogenerated, so they are somewhat generic, not custom- tailored. The good news is, once you undestand how to manipulate on distribution, all the others are basically the same since _they share the same interface_. Let's work through an example. Since you are using IPython (great!), we can also use the question mark after an object, e.g. `obj?`, to find out more about the object. This shows the docstring, like `help(obj)`, plus other useful info such as its type, where it is defined, and (for callables) its call signature. It helps to have a picture of how things are organized. `scipy.stats` is a module: In [386]: from scipy import stats The module docstring lists many kinds of distributions. In [394]: stats? ... Continuous distributions ======================== ... alpha -- Alpha anglit -- Anglit arcsine -- Arcsine beta -- Beta betaprime -- Beta Prime ... norm -- Normal (Gaussian) There are two main classes -- `stats.rv_continuous` and `stats.rv_discrete`. Each of these distributions listed in the `stats` docstring is an **instance** of one of these two classes. `stats.norm` for example, is an [instance of `stats.norm_gen`](https://github.com/scipy/scipy/blob/v0.16.1/scipy/stats/_continuous_distns.py#L191) which is a [subclass of `stats.rv_continuous`](https://github.com/scipy/scipy/blob/v0.16.1/scipy/stats/_continuous_distns.py#L108): In [14]: type(stats.norm).mro() Out[14]: [scipy.stats._continuous_distns.norm_gen, scipy.stats._distn_infrastructure.rv_continuous, scipy.stats._distn_infrastructure.rv_generic, object] * * * Notice that `stats.norms.rvs` is an **instancemethod** : In [387]: stats.norm.rvs? Type: instancemethod String form: <bound method norm_gen.rvs of <scipy.stats._continuous_distns.norm_gen object at 0x7f1479ba2690>> So when later it says > The shape parameter(s) for the distribution (see docstring of the > **instance** object for more information). it is saying there is more information in the docstring of `stats.norm`: In [401]: stats.norm? Docstring: A normal continuous random variable. The location (loc) keyword specifies the mean. The scale (scale) keyword specifies the standard deviation. ... Methods ------- ``rvs(loc=0, scale=1, size=1, random_state=None)`` Random variates. From this description you can see that `stats.norm.rvs(loc=10, scale=2, size=5)` will return 5 random variates with mean 10 and standard deviation 2: In [402]: stats.norm.rvs(loc=10, scale=2, size=5) Out[402]: array([ 9.82454792, 8.52106712, 7.33889233, 8.73638555, 10.90927226]) Alternatively, `stats.norm` is also callable -- you can pass the `loc` and `scale` "shape" parameters [to "freeze" those parameters](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy- stats-norm) into the distribution. What you get back is called a "frozen distribution". For example, you can create a normal distribution with mean 10 and standard devation 2: In [403]: norm = stats.norm(10, 2) and now call the frozen distribution's `rvs` method to obtain 5 random variates: In [404]: norm.rvs(5) Out[404]: array([ 7.21018883, 12.98978919, 10.99418761, 11.2050962 , 8.27780614])
Extracting a string from a text file in python 2.7.5 Question: Hello I am new to python, and I hope you can help me. I have a text file (call it data.txt) with data on gene number with corresponding rs number and some distance measure. The data looks something like this: rs1982171 55349 40802 rs6088650 55902 38550 rs1655902 3105 12220 rs1013677 55902 0 where the first column is rs number, second column is gene number, and third column is some distance measure. The data is much bigger, but hopefully the above gives you an idea of the dataset. What I want to do is find all the rs numbers that correspond to a certain gene. For example, for the data set above, gene 55902= {rs6088650, rs1013677}. Ideally, I want my code to find all rs numbers corresponding to a given gene. Since I am unable to do that now, I instead wrote a short code that gives the lines that contain the string "55902" in the data.txt file: import re data=open("data.txt","r") for line in data: line=line.rstrip() if re.search("55902",line): print line The problem with this code is that the output is something like this: rs6088650 55902 38550 rs1655902 3105 12220 rs1013677 55902 0 I want my code to ignore the string "55902" in the rs number. In other words, I don't my code to output the second line in the above output because the gene number is not 55902. I would like my output to be : rs6088650 55902 38550 rs1013677 55902 0 How can I modify the above code to achieve what I want. Any help would be appreciated. Thanks in advance. Answer: You can use [word boundary (`\b`)](http://www.regular- expressions.info/wordboundaries.html), to match whole word search: >>> import re >>> re.search(r"\b55902\b", "rs1655902 3105 12220") >>> re.search(r"\b55902\b", "rs6088650 55902 38550") <_sre.SRE_Match object at 0x7f82594566b0> * * * if re.search(r"\b55902\b", line): ....
Error running Django in PyCharm Question: I am a Python noob and just recently cloned a Django project into PyCharm. I got it all set up with Django support and located the settings.py and manage.py but I get these traceback errors when I tried running the project. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000000044CC048> Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "C:\Python34\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver for pattern in resolver.url_patterns: File "C:\Python34\lib\site-packages\django\utils\functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python34\lib\site-packages\django\utils\functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "C:\Python34\lib\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 "C:\Users\Public\...\urls.py", line 19, in <module> from . import views File "C:\Users\Public\...\views.py", line 6, in <module> from fproject.lib import hash, userhandler, enum, session, mail File "C:\Users\Public\...\lib\hash.py", line 3, in <module> import bcrypt ImportError: No module named 'bcrypt' I'm not sure what any of these errors are telling me. Am I missing modules or are they located in the wrong directory? Answer: You need to install [bcrypt](https://pypi.python.org/pypi/bcrypt/1.0.1). You can do it from command line by runing `pip install bcrypt` or with [IDE](https://www.jetbrains.com/help/pycharm/2016.1/installing-uninstalling- and-upgrading-packages.html).
Python has modules, what does c++ have? Question: Coming from programming in python, I am familiar with modules. What is the equivalent in c++? Answer: The concept in c++ is more complicated than it is with python, from what I remember of python, a module will work without having to take care of the architecture the module was developed. In C++ (as in C) you have the build process (compile, link) which is important to know when developping with these languages. In C/C++ you have libraries and header files. To make it simple the header shows the interface of the library (which contains the real compiled code). The thing here is that as libraries are compiled, you will need a different version depending on architecture and the compiler you are using. A Mingw built library won't be compliant with MSVC compiler. Namespaces can be thought as modules but not in the same way as we call python modules. In C++ namespaces just allow you to "concat" a prefix to what there is in the namespace to avoid names collision (rough example here, the real mechanism behind isn't just concat) and to order the code logically. You cannot just include a namespace as you import a module in python. I advise you look a tutorial on how the C/C++ build process work, that will explain in detail what are headers, what are libraries and how to use them ;)
Python output not showing on Mac Terminal Question: I have a very simple code that I wanted to execute; #!/usr/bin/env python import sys def Hello(name): name = name + '!!!!' print('Hello', name) if __name__ == '___main___': Hello(sys.argv[0]) and on the Terminal (I'm using iterm2, Mac OSX 10.11.3). python lesson1.py aaaa and is not showing anything. [![enter image description here](http://i.stack.imgur.com/QI4gH.png)](http://i.stack.imgur.com/QI4gH.png) Answer: `___main___` has three underscores surrounding `main`. It should be two: ___main___ ↑ ↑ TO __main__
List manipulation code optimization with Python Question: I have a simple code to group and calculate content of the list. I'm concerned of the time it takes to complete the job. With less than 100 items it is fast enough, but several hundreds items make my Mac to scream. And I have up to 10000 items on a list from real world data. So I need to know, how it is possible to optimize this code: v = [1,2,3,4,5,6,7,8,9,10] v1 = v[:5] l = len(v1) a = [sum(v1[x:y]) for y in range(l+1) for x in range(y)] d = {x:a.count(x) for x in a} So on _v_ there is a list of integers. Digit can be from 1 to 4000. List length on example is 10, but as stated above, it will go go to 10000. _v1_ is just a split list to work with a smaller test data. _a_ gets every item as a single instance AND all preceding items as instances: [1, 3, 2, 6, 5, 3, 10, 9, 7, 4, 15, 14, 12, 9, 5] _d_ groups all items and counts them as a key value pair dictionary: {1: 1, 2: 1, 3: 2, 4: 1, 5: 2, 6: 1, 7: 1, 9: 2, 10: 1, 12: 1, 14: 1, 15: 1} It seems that calculating _a_ already becomes very heavy after 100+ items. With 500 items on _a_ I get 276813 instances for _d_. So when there will be 10000 items on a list, I'm expecting up to 5559333 items to be on _d_ and maybe 100 times more on _a_. **UPDATE** Based on comments and answers below there is some improvement done via implementation below: def t5(v1): l = len(v1) d = {} for x in range(0, l): s = sum(v1[x:]) if s in d: d[s] += 1 else: d[s] = 1 for y in range(1, l-x): s -= v1[-y] if s in d: d[s] += 1 else: d[s] = 1 return d I have no idea, how to use numpy and/or numba for more optimization. Maybe good for different separate question... Answer: You are continually re-calculating sums for slices you already calculated before (each `sum()` call a redundant loop), plus you are creating loads of new list objects by slicing all the time. You can use dynamic programming to calculate the sums instead, walking from the end of your input list; you only need to add the 'current' value to the sums for the next value in your list: # v1 is the input list, l is len(v1) sums = [0] * (l * (l + 1) // 2) for x in range(l - 1, -1, -1): for y in range(x, l): i = (y * (y + 1) // 2) + x sums[i] += v1[x] + (sums[i + 1] if x < y else 0) This adds up already calculated sums for partial subsequences to the next longer subsequence, avoiding a whole inner loop. This takes O(N^2) time, rather than your O(N^3) approach (where `sum()` loops over each subslice up to N elements long). It translates `x` and `y` coordinates into your final 'triangle' to avoid having to create a larger matrix (or a dictionary, which would have additional memory and hashing overhead). That's because you calculate slices between any two points in the list; if you take a matrix where the axis are the start and end indices _included_ in each slice, you can number the final list like this: 0 1 2 3 4 0 0 1 3 6 10 1 2 4 7 11 2 5 8 12 3 9 13 4 14 (blank spaces are reverse slices, duplicates, not used in the output). For each row and column, you can calculate the output index by counting how many values fit in the triangle before that column plus the row number, or `((col * col + 1) // 2) + row)`. The dynamic programming approach adds the sum for already produced slices for later values (the row below the indices) to the `v1` value for the current row: v1 0 1 2 3 4 1 > 0 1 3 6 10 15 ^ ^ ^ ^ 2 > 1 2 5 9 14 ^ ^ ^ 3 > 2 3 7 12 ^ ^ 4 > 3 4 9 ^ 5 > 4 5 So the value at row 2, column 4 is `v1[2]` plus the already calculated sum for row 3, column 4, or in this case, `2 + 12`. There is only ever an already calculated sum for those elements where the row index is smaller than the column index; at position (3, 3) there is no calculated sum at (4, 3). Next problem is that your `list.count()` traverses your _whole_ list of sums to count how often one number appears. Thus, your `{x:a.count(x) for x in a}` expression creates a O(N^2) double loop; it'll take quadratic time to process all counts. Use a [`Counter()` object](https://docs.python.org/2/library/collections.html#collections.Counter) to produce that dictionary instead (a `Counter` is a subclass of `dict`): from collections import Counter d = Counter(sums) A `Counter()` goes through all your elements just _once_ to count the values; it simply keeps counters for each value it has seen so far as it iterates.
BeautifulSoup not showing Korean letters properly Question: I'm a newbie in Python who is learning parsing with BeautifulSoup. This is my code, #-*- coding: utf-8 -*- import urllib from bs4 import BeautifulSoup soup = BeautifulSoup(urllib.urlopen('https://news.google.com/news/section?cf=all&pz=1&q=IoT').read()) editData = soup.find_all('span',{'class','titletext'}) print editData and the result is as follows: (Korean letters are shown "\uc720\ud50c\ub7ec\uc2a4" etc) > [LG\uc720\ud50c\ub7ec\uc2a4, **IoT** \uc720\ub9dd\uae30\uc5c5 > \ubc1c\uad74\u2026 \uc0c1\uc0dd \ud611\ub825 \ucd94\uad6c, > LG\uc720\ud50c\ub7ec\uc2a4, \uc720\ub9dd **IoT** \uc911\uc18c\uae30\uc5c5 > \uc9c0\uc6d0, LGU+ '**IoT** \uc720\ub9dd \uc911\uc18c\uae30\uc5c5 > \ubaa8\uc5ec\ub77c', "**IoT** \ub85c \uace0\uce35\ube4c\ub529 > \uc5d0\ub108\uc9c0 \uc18c\ube44 80% \u2193", > \uc2dc\ud050\ub9ac\ud2f0\ud50c\ub7ab\ud3fc-\uc774\ub354\ube14\uc720\ube44\uc5e0 > **IoT** \ubcf4\uc548 \ud1a0\ud138\uc194\ub8e8\uc158 \uac1c\ubc1c, NIA, > **IoT** \uc735\ud569 \uc2e0\uc0b0\uc5c5 \uc9c0\uc6d0 \uc704\ud574 135\uc5b5 > \uaddc\ubaa8 \ud22c\uc790, **IoT** \ub9db\uc744 \uc54c\uac8c \ub41c > \ud1b5\uc2e03\uc0ac, '\uc0c1\uc0dd'\uc774 \uacb0\uad6d \ubbf8\ub798 > \ub9cc\ub4e0\ub2e4, \uc0bc\uc131\uc804\uc790, \ubd81\ubbf8 `<b>IoT</b> > \uc2a4\ub9c8\ud2b8 \ube4c\ub529 \ucf00\uc5b4 \uc2dc\uc2a4\ud15c` > \uacf5\ub7b5...\ud604\uc9c0 \ub370\uc778\ud2b8\ub9ac\uc640 \ud611\uc5c5, > \ud30c\uc6cc\ubcf4\uc774\uc2a4, \uc74c\uc131\uc778\uc2dd **IoT** > \uc2a4\ub9c8\ud2b8 \uc2a4\uc704\uce58 \ucd9c\uc2dc, \uace0\ub824\ub300, > \uc815\ubcf4\ud1b5\uc2e0 \uace0\ub3c4\ud654\ud55c '**IoT** > \ucea0\ud37c\uc2a4' \ubcc0\uc2e0, ... and so on. I can't find any solutions concerning this problem. Answer: Its not because of BeautifulSoup its because the way you print the node. doing something like: print editData will call the function `__repr__()` of the node, which is implemented by returning the content as ascii string. try this: for span in editData: print span.text and you should see the unicode text (the for-in loop is because the result is a list of nodes and not a single node so we print them all).
How do I pass variables to shell functions in Python? Question: I would like to write a Python script to automate the process of adding the dependencies of a npm package to my Open Build Service project. I have a shell function: function cpobsn { cdobsa mkdir nodejs-$1 cd nodejs-$1 npm2PKGBUILD $1 > PKGBUILD cpserv obsa } this is the Python script I have at the moment (the `package.json` file being imported is the `package.json` of the npm package): import json import os with open("/home/fusion809/OBS/home:fusion809:arch_extra/arch-wiki-man/package/package.json") as json_file: json_data = json.load(json_file) deps = json_data["dependencies"] for key, value in deps.items(): print(key) os.system("cpobsn") I would like to pass the `key` variable to the `cpobsn` shell function (i.e., I would like this Python loop to run the shell command `cpobsn key` on every iteration). How do I do this? Answer: Functions are good for interactive use, but this seems like a case where you want a stand-alone script instead. If you want to have a function you can load into your `.zshrc` or similar, you could do something like the Python `__name__ == '__main__'` idiom in the script file, too. But renaming the file to the name of the command and getting rid of the function would seem like the simplest way to achieve your end goal here. Save this as, say, `$HOME/bin/cpobsn` and `chmod +x` it. Make sure `$HOME/bin` is in your `PATH`, too. #!/bin/sh cdobsa mkdir nodejs-"$1" cd nodejs-"$1" npm2PKGBUILD "$1" > PKGBUILD cpserv obsa (Note the addition of proper quotes for good measure.) Now, you can call it from Python, as with any regular external command. from subprocess import check_call check_call(['cpobsn', key]) The choice between `subprocess.call()` and `subprocess.check_call()` will depend on whether the script returns a useful exit code. It doesn't at the moment, so actually `call` would be sufficient; on the other hand, you should fix that, and use `check_call` to have Python tell you when some part of the shell script failed. Minimally, adding `set -e` to the shell script will make it check for errors, and abort if anything fails; but this often requires refactoring to avoid terminating on non-fatal errors (like `grep` not returning a result -- this is technically an error, but often an acceptable part of normal flow).
Jupyter shows plot without plt.show() Question: I am using the Jupyter notebook with Python 2.7. Importing matplotlib like this: %matplotlib inline import matplotlib.pyplot as plt But I have observed one thing. When I use Python in Spyder I always have to use the `plt.show() commando at the end of the python script in order to see the plots. In Jupyter I do not need this command in order to see a plot. I do get this error message: [<matplotlib.lines.Line2D at 0x91615d0>] but it still makes a plot. Why is that? Answer: You turn on the immediate display with `%matplotlib inline`. The line: [<matplotlib.lines.Line2D at 0x91615d0>] is no error message. It is the return value of the last command. Try adding a `;` at the end of the last line to suppress this.
Pyrhon variable working outside of function, but not inside Question: I have an issue where I am trying to copy feature classes into a geodatabase. I am looping through all the feature classes in the folder and copying only the polygon feature classes. My problem is, that when I copy the first polygon feature class it renames it 'shp', and then tries to name the second 'shp' as well. The variable `fcname` returns the full feature class names ('counties.shp' and 'new_mexico.shp') outside of the copy function, but it does not work properly inside the function. The code below has the function that I want to run commented out to test the `fcname` variable. There are five feature classes in the folder with two of them being polygon feature classes. When uncommented the code runs all the way through the first polygon feature class where `fcname` results in 'shp' instead of 'counties.shp'. It does the same for the second feature class which results in an error since 'shp' already exists in the `gdb`. import arcpy # Set initial variables with different pathnames available # whether I am working on my home or work computer pathhome = "G:/ESRIScriptArcGIS/Python/Data/Exercise06" pathwork = "C:/ESRIPress/Python/Data/Exercise06" arcpy.env.workspace = pathwork gdbname ="NewDatabase.gdb" fclist = arcpy.ListFeatureClasses() # Create new gdb ##arcpy.management.CreateFileGDB(path, gdbname) newgdb = path + "/" + gdbname # Loop through list for fc in fclist: desc = arcpy.Describe(fc) fcname = desc.name outpath = newgdb + "/" + fcname # Check for polygon then copy if desc.shapeType == "Polygon": ##arcpy.management.CopyFeatures(fcname,outpath) ##print fcname + "copied." print fcname else: print "Not a polygon feature class" Thank you to anyone who can help! Answer: I found the answer to the problem. `CopyFeatures` does not want a full file path in the `out_feature_class` argument. I stripped the ".shp" from the end of the file path and it worked. I also took Hector's advice and filtered down to just the polygons in the `ListFeatureClasses` arguments, however, I still needed the loop to walk through the resulting list and copy each feature class. Here is the resulting code that worked. import arcpy # Set initial variables with different pathnames available # whether I am working on my home or work computer pathhome = "G:/ESRIScriptArcGIS/Python/Data/Exercise06" pathwork = "C:/ESRIPress/Python/Data/Exercise06" arcpy.env.workspace = pathwork gdbname ="NewDatabase.gdb" fclist = arcpy.ListFeatureClasses("", "Polygon") # Create new gdb arcpy.management.CreateFileGDB(pathwork, gdbname) newgdb = pathwork + "/" + gdbname # Loop through list for fc in fclist: desc = arcpy.Describe(fc) fcname = str(desc.name) outpath = newgdb + "/" + fcname.replace(".shp","") arcpy.management.CopyFeatures(fcname,outpath) print fcname + " has been copied."
create new xlsx file with python equals to another one Question: I have one xlsx file and I want to create with python script another xlsx file equal to the first one. How can I do? Have you an example script? Answer: shutil can hep you do this. from shutil import copyfile copyfile(src, dst) Taken from this answer although it answers the general case. [How do I copy a file in python?](http://stackoverflow.com/questions/123198/how-do-i-copy-a- file-in-python)
Coloring axvspan from range of colors (Python) Question: **Background** I am trying to plot consecutive colored areas in **Python** using **matplotlib**. I use (imagine i being some iteration variable) axvspan(from_x[i], to_x[i], color=my_color[i]) to plot this. Now, I need a general way to say "plot from green to increasingly more red given N areas to be plotted next to each other". i = 0: area is green, i = 1: area is green but with some red, etc. i = N: area is red. You get the point. **Question** Sure, if N was fixed I could just manually put in the rgb values, but it is not. I have looked up ways to do this if plotting lines etc. but I am not sure how to do this for axvspan(...) and specifically how to get the green to red feature. Most examples I found was regarding color maps which I am not sure I want to use here. Your help is much appreciated. Answer: You can use an `(r,g,b)` tuple for the color, so we can just increase the red and decrease the green as we move through the loop. Obviously, you can manipulate `N` and the `from_x` and `to_x` arrays to suit your needs. import matplotlib.pyplot as plt import numpy as np fig,ax = plt.subplots(1) N = 20 from_x = np.linspace(0,0.95,N) to_x = from_x + 0.05 for i in range(N): ri = float(i)/float(N) gi = 1.-ri bi = 0. ax.axvspan(from_x[i], to_x[i], color=(ri,gi,bi)) plt.show() [![enter image description here](http://i.stack.imgur.com/FN8oB.png)](http://i.stack.imgur.com/FN8oB.png)
How to log in and auto fill values into a 'drupal form' from an 'excel file'? Question: So, there is this website where I have to log in and insert values in the _add content->person roles_ and I have to take values from an excel file. I tried entering the values in the database directly but got nowhere. The database is too randomly generated. I want to know- how to go by this problem? I think _python_ would be the best way but I am more comfortable with _java_. The images bellow will help understand the situation better- The log in from: ![log in form](http://i.stack.imgur.com/wHd8R.jpg) The form to be filled: ![log in form](http://i.stack.imgur.com/XwaOF.jpg) Answer: Try using feeds module: <https://www.drupal.org/project/feeds> Install it on you site first of course. Or look for some similar import module. Maybe this one: <https://www.drupal.org/project/datasources> If nothing succeeds then try making import script on your own. You have to parse document (would be much easier to open it from excel and export as CSV if possible <http://php.net/manual/en/function.fgetcsv.php>) and have some loop to write content into Drupal system. Use Drupal's functions for that, do not directly write to database. It's not hard as it looks like: <https://www.drupal.org/node/1388922>
Extract data from json stock file using python Question: How do I extract the data from that URL? I only want to print out all the 'value' import urllib import re import json htmltext = urllib.urlopen("http://www.bloomberg.com/markets/api/bulk-time-series/price/AXP%3AUS?timeFrame=1_MONTH").read() data = json.loads(htmltext) print data This is what the API display as a result from print url command: [{u'lastPrice': 60.85, u'price': [{u'date': u'2016-03-04', u'value': 58.29}, {u'date': u'2016-03-07', u'value': 59}, {u'date': u'2016-03-08', u'value': 59.43}, {u'date': u'2016-03-09', u'value': 59.05}, {u'date': u'2016-03-10', u'value': 58.75}, {u'date': u'2016-03-11', u'value': 59.46}, {u'date': u'2016-03-14', u'value': 59.57}, {u'date': u'2016-03-15', u'value': 59.23}, {u'date': u'2016-03-16', u'value': 59.7}, {u'date': u'2016-03-17', u'value': 60.08}, {u'date': u'2016-03-18', u'value': 61.22}, {u'date': u'2016-03-21', u'value': 61.21}, {u'date': u'2016-03-22', u'value': 60.61}, {u'date': u'2016-03-23', u'value': 60.63}, {u'date': u'2016-03-24', u'value': 60.47}, {u'date': u'2016-03-28', u'value': 60.28}, {u'date': u'2016-03-29', u'value': 60.6}, {u'date': u'2016-03-30', u'value': 60.29}, {u'date': u'2016-03-31', u'value': 61.4}, {u'date': u'2016-04-01', u'value': 61.1}], u'priceMinDecimals': 2, u'nyTradeEndTime': u'16:30:00.000', u'lastUpdateDate': u'2016-04-04', u'nyTradeStartTime': u'09:30:00.000', u'id': u'AXP:US', u'timeZoneOffset': -4, u'dateTimeRanges': {}}] Answer: You can get all the values this way. Get the first item in the data list (there's only 1 item). The get the `price` list, then iterate over all the price dictionaries and retrieve the `value` field for each one. values = [p['value'] for p in data[0]['price']]
Python 3 - Parse JSON from multiple API requests into a list and output to a file Question: How do I... 1) Parse JSON objects from API queries in Python 3 2) Parse multiple requests into a list, and 3) Output the list into a JSON file Answer: I prefer using [`requests`](http://python-requests.org/) for all API programming. Here is a one-liner that fetches the results of several API calls, puts them in a list, and writes that list to a JSON file: json.dump([requests.get(url).json() for url in URLs], fp) Here is a complete test program: import requests import json URLs = [ # Some URLs that return JSON objects 'http://httpbin.org/ip', 'http://httpbin.org/user-agent', 'http://httpbin.org/headers' ] with open('result.json', 'w') as fp: json.dump([requests.get(url).json() for url in URLs], fp, indent=2) If you are allergic to `requests` for some reason, here is equivalent Python3 code, using only the standard library. from urllib.request import urlopen import json URLs = [ # Some URLs that return JSON objects 'http://httpbin.org/ip', 'http://httpbin.org/user-agent', 'http://httpbin.org/headers' ] json_list = [] for url in URLs: resp = urlopen(url) resp = resp.read().decode(resp.headers.get_content_charset() or 'ascii') json_list.append(json.loads(resp)) with open('result.json', 'w') as fp: json.dump(json_list, fp, indent=2)
Clean up code or to find a more efficient ways to write some of this code. Question: I am looking to see if I can find a more efficient way to write this. The problem with csv reader is that when you write the output to standard out it tosses additional single quotes around it. Changing the quotes to none didn't help because it didn't retain formatting. This code works but I have a feeling that I could do it more efficiently. I am really new to python and programming. import csv import sys def printString(x): print x[0] + ",", x[1] + ",", x[2] + ",", x[3] + "," with open(sys.argv[1],"rb") as inputFile: csvInput = csv.reader(inputFile, delimiter=',') header = next(csvInput) sort = sorted(csvInput, key=lambda x:float(x[3])) printString(header) for i in sort: printString(i) Answer: Use this way: def printString(x): for field in x: print "{0},".format(field)
making windrose from my own data Question: I am trying to make a wind rose from a series of windspeed and direction values. I have an idea of how to write the raw program for doing this as shown below: from windrose import WindroseAxes from matplotlib import pyplot as plt import matplotlib.cm as cm import numpy as np ws=[2.6,2.3,2.1,2.0,2.1,2.2,2.9,2.8,2.39,1.90,1.54,1.29,0.72,0.18,1.08] wd=[207,208,215,217,213,209,203,195,187,179,164,139,117,101,280] print "WD is ",wd print "WS is ",ws ax = WindroseAxes.from_ax() ax.bar(wd,ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.show() The only issue is is how can I have the program reading my data into the arrays ws (windspeed) and wd (wind direction) in the above program. The data is in an ascii file with two columns separated by a space. The first column is wind speed and the second column is wind direction. With wind speed in the first column and wind direction in the second column. Do you know how to read this type of wind using python so that column one occupies the ws array and column two occupies the wd array in the script above? Answer: You can use `np.loadtxt`: data = np.loadtxt('data.txt') ws = data[:, 0] wd = data[:, 1]
How to store time without date in Python so it's convenient to compare? Question: I have a simple task of storing a time in server's timezone and then comparing if current time if after or before the saved time. I tried to store the time as a "Jan 1st 2008" date with the time I need. The problem is a daylight saving time gets in a way, if I save "16:00" on Jan 1st and try to compare it with "16:00" on April 1st I get an one hour difference. I want "16:00" to always mean current day's "16:00". What would be an efficient and reliable way of storing and comparing time of the day and ignoring the date? I need it to also be json-serializable, so I can easily manipulate the value in python and JS if needed. Answer: > I need it to also be json-serializable, so I can easily manipulate the value > in python and JS if needed. `"16:00"` string could be used to store the time (if you don't need seconds). > I want "16:00" to always mean current day's "16:00". To compare it with the current time: import time if time.strftime('%H:%M') < '16:00': print('before 4pm') else: print('after 4pm') `%H`, `%M` produce zero-padded decimal numbers such as `07` and therefore the string comparison works correctly. It works in the presence of DST transitions too (as long as C `localtime()` works). To parse it into time, datetime objects: from datetime import datetime four_pm_time = datetime.strptime('16:00', '%H:%M').time() four_pm = datetime.combine(datetime.now(), four_pm_time) To get a timezone-aware datetime object: import tzlocal # $ pip install tzlocal four_pm_aware = tzlocal.get_localzone().localize(four_pm, is_dst=None) [To get Unix time corresponding to 4pm (assuming `mktime()` works here)](http://stackoverflow.com/a/36462784/4279): import time unix_time = time.mktime(time.localtime()[:3] + (16, 0, 0) + (-1,)*3)
Converting Data From Serial Port to Display as Decimal in Python Question: I am starting a program that reads data from a radio receiver. The data is 6 bytes long and updates every 1 second. The program reads the serial port USB data, but the data is in some format that does not display correctly. What I do know is that it should be in an unsigned integer. Each data string comes in as 6 bytes and each byte represents a number corresponds to the data the receiver has logged. import serial t = 0 while t == 0: ser = serial.Serial('/dev/tty.SLAB_USBtoUART', 9600, bytesize=8, stopbits=1, timeout=None, xonxoff=0, rtscts=0, dsrdtr=0) s=ser.readline(6) #s=ser.read(6) print("Streams received during interval: ") print (s) print("__________") end I am expecting an output that looks like: > 0 101 0 0 91 145 but what I am getting is: > eV� I think there is something off in the data coming in and how it prints in the print statement. I just need to make sure the data is coming in correctly before I move on. Answer: That's because you are converting bytes to a string with your `'%s' % s` statement. It's showing up as whatever random ASCII character corresponds to your bytes. Instead, try printing the bytes as integers: print ' '.join([ord(ss) for ss in s])
Create and insert a strftime-object for mysql datetime-field Question: I have a database which is supposed to be moved to a new one. My idea is a python script that reads all old entries, converts them in the new format and sends them to the new database. The problem is that the date(time) is stored differently. In the old db there are 5 columns (year, month, day, hour, minute) but the new one just works with a datetime field (YYYY-MM-DD hh:mm:ss). If I try something like this in python: import time t = time.mktime((2015,11,29,14,30,0,0*,246*,-1*)) # * not sure about these values print time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t)) I even get another time than expected: 2015-11-29 13:30:00 How can I get for 180k entries the right datetime format or is this maybe already the wrong way to enter a value into a datetime field? EDIT: import MySQLdb mysql_opts = { 'host': "123.45.67.89", 'user': "user", 'pass': "password", 'db': "db"} t = time.mktime((2015, 11, 29, 14, 30, 0, 0, 0, 0)) date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) data = [date,...] mysql = MySQLdb.connect(mysql_opts['host'],mysql_opts['user'],mysql_opts['pass'],mysql_opts['db']) cursor = mysql.cursor() cursor.execute("INSERT INTO table (date, ...) VALUES(%s,...)",(data[0],...)) mysql.commit() mysql.close() If I try this I am getting this error: TypeError: not all arguments converted during string formatting What else do I have to do before I can add an entry? :S Answer: I seems like you are doing it right, but you are not printing the time in GMT: # get from old DB Y = 2015 m = 11 d = 29 H = 14 M = 30 S = 0 t = time.mktime((Y, m, d, H, M, S, 0, 0, 0)) time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) # use this to get the same time Out[1]: '2015-11-29 14:30:00'
Unable to access wikipedia API due to SSL-certificate error Question: import requests spiders = requests.get('https://en.wikipedia.org/w/api.php') print(spiders) With above code I am getting following error: Traceback (most recent call last): File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 554, in urlopen self._prepare_proxy(conn) File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 750, in _prepare_proxy conn.connect() File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 252, in connect ssl_version=resolved_ssl_version) File "C:\Python\lib\site-packages\requests\packages\urllib3\util\ssl_.py", line 305, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Python\lib\ssl.py", line 376, in wrap_socket _context=self) File "C:\Python\lib\ssl.py", line 747, in __init__ self.do_handshake() File "C:\Python\lib\ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "C:\Python\lib\ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) Using a certificate I still get an error: import requests spiders = requests.get('https://en.wikipedia.org/w/api.php',cert = 'c:\python\lib\site-packages\certifi\cacert.pem',verify = True) print(spiders) Traceback (most recent call last): File "C:/Python/Files/3.py", line 3, in <module> spiders = requests.get('https://en.wikipedia.org/w/api.php',cert = 'c:\python\lib\site-packages\certifi\cacert.pem',verify = True) File "C:\Python\lib\site-packages\requests\api.py", line 67, in get return request('get', url, params=params, **kwargs) File "C:\Python\lib\site-packages\requests\api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "C:\Python\lib\site-packages\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Python\lib\site-packages\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Python\lib\site-packages\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: [SSL] PEM lib (_ssl.c:2824) Even when I have followed some tutorial verbatim I have encountered this issue when the instructor would have access w/o issue. Any ideas? Answer: u can ignore SSL like this: import requests spiders = requests.get('https://en.wikipedia.org/w/api.php',verify = False) print(spiders) other solution: from urllib.request import Request, urlopen rq = Request('https://en.wikipedia.org/w/api.php') response = urlopen(rq).read()
Transposition Cipher in Python Question: Im currently trying to code a transposition cipher in python. however i have reached a point where im stuck. my code: key = "german" length = len(key) plaintext = "if your happy and you know it clap your hands, clap your hands" Formatted = "".join(plaintext.split()).replace(",","") split = split_text(formatted,length) def split_text(formatted,length): return [formatted[i:i + length] for i in range(0, len(formatted), length)] def encrypt(): i use that to count the length of the string, i then use the length to determine how many columns to create within the program. So it would create this: GERMAN IFYOUR HAPPYA NDYOUK NOWITC LAPYOU RHANDS CLAPYO URHAND S this is know where im stuck. as i want to get the program to create a string by combining the columns together. so it would combine each column to create: IHNNLRCUSFADOAHLRYPYWPAAH ..... i know i would need a loop of some sort but unsure how i would tell the program to create such a string. thanks Answer: you can use slices of the string to get each letter of the string in steps of 6 (length) print(formatted[0::length]) #output: ihnnlrcus Then just loop through all the possible start indices in `range(length)` and link them all together: def encrypt(formatted,length): return "".join([formatted[i::length] for i in range(length)]) note that this doesn't actually use `split_text`, it would take `formatted` directly: print(encrypt(formatted,length)) the problem with using the `split_text` you then cannot make use of tools like `zip` since they stop when the first iterator stops (so because the last group only has one character in it you only get the one group from `zip(*split)`) for i in zip("stuff that is important","a"): print(i) #output: ("s","a") #nothing else, since one of the iterators finished. In order to use something like that you would have to redefine the way zip works by allowing some of the iterators to finish and continue until all of them are done: def myzip(*iterators): iterators = tuple(iter(it) for it in iterators) while True: #broken when none of iterators still have items in them group = [] for it in iterators: try: group.append(next(it)) except StopIteration: pass if group: yield group else: return #none of the iterators still had items in them then you can use this to process the split up data like this: encrypted_data = ''.join(''.join(x) for x in myzip(*split))
Download Google Spreadsheet and save as xls Question: Am trying to write python procedure to download a spreadsheet from google spreedsheets and save it as .xls. here is my code import os import sys from getpass import getpass import gdata.docs.service import gdata.spreadsheet.service ''' get user information from the command line argument and pass it to the download method ''' def get_gdoc_information(): email ="mygmailaccount" password ="mypassword" gdoc_id = ['google_id1','googleid2','googleidn'] for doc_id in gdoc_id: try: download(doc_id, email, password) except Exception, e: raise e #python gdoc.py 1m5F5TXAQ1ayVbDmUCyzXbpMQSYrP429K1FZigfD3bvk#gid=0 def download(doc_id, email, password, download_path=None, ): print "Downloading the XLS file with id %s" % doc_id gd_client = gdata.docs.service.DocsService() #auth using ClientLogin gs_client = gdata.spreadsheet.service.SpreadsheetsService() gs_client.ClientLogin(email, password) #getting the key(resource id and tab id from the ID) resource = doc_id.split('#')[0] tab = doc_id.split('#')[1].split('=')[1] resource_id = 'spreadsheet:'+resource if download_path is None: download_path = os.path.abspath(os.path.dirname(__file__)) file_name = os.path.join(download_path, '%s.xls' % (doc_id)) print 'Downloading spreadsheet to %s...' % file_name docs_token = gd_client.GetClientLoginToken() gd_client.SetClientLoginToken(gs_client.GetClientLoginToken()) gd_client.Export(resource_id, file_name, gid=tab) gd_client.SetClientLoginToken(docs_token) print "Download Completed!" if __name__=='__main__': get_gdoc_information() Whenever I try to run it, i get a gdata error below gdata.service.RequestError: {'status': 401, 'body': '<HTML>\n<HEAD>\n<TITLE>Unauthorized</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Unauthorized</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n', 'reason': 'Unauthorized'} Am using gdata library. I have been struggling with this whole day and cant seem to figure out what's happening. Can anyone please figure out and assit? Any other minimal script that can achieve my purpose as described above is will be much appreciated. Thank you Answer: your error does suggest an login problem. Maybe you need to change your settings in your google account or try another way of a login. Try looking here: [SyntaxError using gdata-python-client to access Google Book Search Data API](http://stackoverflow.com/questions/2925985/syntaxerror-using- gdata-python-client-to-access-google-book-search-data-api/3013945#3013945) or here: [Download a spreadsheet from Google Docs using Python](http://stackoverflow.com/questions/3287651/download-a-spreadsheet- from-google-docs-using-python) I'm sorry to post this as an answer but I can't post comments yet. Regards
python re.findall vs re.sub Question: Please explain me why I get different results with using re.find and re.sub The string which I parse: GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A' Code: import re S="GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'" U=re.compile(r'.* TO \'(.*?)\'@.*') H=re.compile(r'.*\'@\'(.*?)\'.*') print(U.findall(S)) print(H.findall(S)) So I get what I want: ['testuser'] ['10.10.10.10'] So, I want to change ip address and user, so I try to use re.sub Code import re S="GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'" U=re.compile(r'.* TO \'(.*?)\'@.*') H=re.compile(r'.*\'@\'(.*?)\'.*') HOST=H.sub('another_ip',S) USER=U.sub('another_user',S) print(HOST) print(USER) But I just get this: another_ip another_user Answer: With `re.sub()` you need to specifically target which part of the string are you trying to substitute. In other words, `re.sub()` would replace everything that was matched by a regular expression (well, [strictly speaking](https://docs.python.org/2/library/re.html#re.sub), `the leftmost non-overlapping occurrence of a pattern`) - in your case you are replacing the complete string. Instead, you can match the user and the IP address specifically, for example: >>> re.sub(r"'(\w+)'@'(\d+\.\d+\.\d+\.\d+)'", "'another_user'@'another_ip'", S) "GRANT USAGE ON *.* TO 'another_user'@'another_ip' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'"
Rock Paper Scissor Python Question: I'm Learning Python and coded rock, paper and scissor game. I'm using IDLE in Ubuntu for this. The code has compiled fine but still i'm unable to get this running. IDLE is running fine in this system. PLease help me resolve this. Thanks in advance #!/usr/bin/env python2 import time import random rock = 1 paper = 2 scissors = 3 names = {rock:"rock", paper:"Paper",scissors: "Scissors"} rules = {rock: scissors, paper: rock,scissors: paper} player_score = 0 computer_score = 0 def start(): print "Start" while game(): pass scores() def game(): player = move() computer = random.randint(1,3) result(player,computer) return play_again() def move(): while True: print player = raw_input("Rock = 1 paper = 2 scissor = 3") try: player = int(player) if player in (1,2,3): return player except ValueError: pass print "Enter number" def result(player,computer): print "Computer threw {0}!".format(names[computer]) if player == computer: print ("Tie") else: if rules(player) == computer: print("You win") player_score += 1 else: print("Computer wins") computer_score += 1 def play_again(): answer = raw_input("Play Again") if answer in ("y" "Y"): return answer else: print ("Thanks") def scores(): global player_score, computer_score print "Player", player_score print "Computer", computer_score start() Answer: Dedent the last line, `start()`. The interpreter runs the upper level of the script, but the indentation makes that line part of the function `score()`.
Using a function to get column names Sqlite3 Question: I have a short question for one of my classes; it involves building a function in python that takes a sqlite database name and a table name as arguments, and returns the column names inside this table. So far I have done the following: #!/user/bin/env python import sqlite3 import pprint pp = pprint.PrettyPrinter() def print_table_columns(database_name, table_name): conn = sqlite3.connect(database_name) c = conn.cursor() c.execute('SELECT sql FROM sqlite_master WHERE type=\'table\' AND name=\'table_name\'') print c.fetchall() conn.close() Sadly, this code produces an empty list. I suspect that the SQL command inside the execute function does not take variables defined in Python, but I am not sure. Any help on this would be much appreciated. Answer: Sure, you need to _parameterize the query_ : c.execute(""" SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?""", (table_name, )) where `?` is a placeholder that `sqlite3` would fill with the query parameter (`table_name` here).
How to find the middle value of an integer without converting it to a string using Python3? Question: While solving the next [smallest palindrome problem](https://github.com/harishvc/challenges/blob/master/string-next- palindrome.py), I had to convert an integer to a string so I can reverse and find the middle value. There has to be a solution - how to find the middle value of an integer without converting it to a string using Python3? Appreciate your assistance. Thanks. Examples: 1. input=78653, result=6 2. input=7564, result=5 Answer: This is a start. It needs some tweaking: import math def mid_digit(n): # num of digits a = math.trunc(math.log(n,10)+1) # moving half of digits to the right of decimal point b = n / 10 ** round(a/2 + 0.5) # getting the left most decimal digit c = math.trunc(math.modf(b)[0] * 10) return c
Using Hive functions in Spark Job via hiveContext Question: I am using Hive 1.2 and Spark 1.4.1. The Following query runs perfectly fine via Hive CLI: hive> select row_number() over (partition by one.id order by two.id) as sk, two.id, two.name, one.name, current_date() from avant_source.one one inner join avant_source.two two on one.id = two.one_id; but when I try to use it via HiveContext in a pyspark job it gives me an error: py4j.protocol.Py4JJavaError: An error occurred while calling o26.sql. : java.lang.RuntimeException: Couldn't find function current_date Code snippet: from pyspark import HiveContext conf = SparkConf().setAppName('DFtest') sc = SparkContext(conf=conf) sqlContext = HiveContext(sc) df = sqlContext.sql("select row_number() over (partition by one.id order by two.id) as sk, two.id, two.name, one.name, current_date() from avant_source.one one inner join avant_source.two two on one.id = two.one_id") df.show() sc.stop() Is there a way to get the current date or timestamp in pyspark? I tried importing date, datetime, but it always throws an error saying function not found. I tried to use current_date in Data Frames in pyspark 1.5 Sandbox, but then also I get a different error. df = sqlContext.createDataFrame([(current_date,)],[‘d’]) df.select(date_sub(df.d,1).alias('d')).collect() Error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/mapr/spark/spark-1.5.2/python/pyspark/sql/dataframe.py", line 769, in select jdf = self._jdf.select(self._jcols(*cols)) File "/opt/mapr/spark/spark-1.5.2/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py", line 538, in __call__ File "/opt/mapr/spark/spark-1.5.2/python/pyspark/sql/utils.py", line 40, in deco raise AnalysisException(s.split(': ', 1)[1]) pyspark.sql.utils.AnalysisException: cannot resolve 'datesub(d,1)' due to data type mismatch: argument 1 requires date type, however, 'd' is of struct<> type.; Please advise. Answer: For my scenario, I used the following import datetime now = datetime.datetime.now() df = df.withColumn('eff_start', lit(now.strftime("%Y-%m-%d"))) For the error of not being able to use HiveContext for HiveQL correctly for Hive functions, it was a cluster issue, where one of the nodes on which HiveServer2 was running had too many alarms due to memory issues. That was causing the problem. It was tested successfully on a MapR Sandbox running Spark 1.5 and Hive 1.2
How to Replace variable value in string python? Question: I working on python based project where formula's are stored in dB. My script will read the formula's from a particular column and stored in list . For Eg formula[0] = "round(float(latitude[:2]) + (float(latitude[2:]) / 60)" formula[1] = "round(float(longitude[:3]) + float(longitude[3:]) / 60),6)" formula[3] = "int(float(speed)*1.852)" Through TCP socket comma separated values will be coming like "imei:1234467454545,ac alarm,160302150105,,F,094605.000,A,1301.9905,N,08014.0746,E,0.19,298.01,,0,,,,;" by coding I have split the comma-separated values and stored in list. From the stream `"1301.9905 "` is latitude, `"08014.0746"` is longitude and `"0.19"` is speed value. How can I apply the value in the formulas and store in some variable? I have tried this method latitude = "1301.9905" latitude = round(float(latitude[:2]) + (float(latitude[2:]) / 60),6) print latitude Answer: you can store the formula in the as a python template and then use `eval` to execute it. from string import Template formula = "round((float($latitude) + float($latitude))/60)" template = Template(formula) out = template.substitute(latitude="1301.995") eval(out) here i am using `eval` method to execute the function. for more info on `templates` check [here](https://docs.python.org/2/library/string.html#template-strings)
Create mocked http session with scapy python Question: How can i create a HTTP session and save the packets of it? i have got this code: import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * get='GET / HTTP/1.0\n\n' ip=IP(dst="www.google.com") port=RandNum(1024,65535) SYN=ip/TCP(sport=port, dport=80, flags="S", seq=42) SYNACK=sr1(SYN) ACK=ip/TCP(sport=SYNACK.dport, dport=80, flags="A", seq=SYNACK.ack, ack=SYNACK.seq + 1) / get reply,error=sr(ACK) but in my code i don't want to send any packets just to get the answer(simulate the situation of the sending functions of SYNACK=sr1(SYN) and reply,error=sr(ACK) without really using them).. i want to simulate the session between two ips(with their ports) and with the payload and then save everything as packets as cap file.. how can i do this? Answer: The jargon you're looking for is 'mocking'. Later versions of python unit testing have [unittest.mock](https://docs.python.org/3/library/unittest.mock.html) and there are also external libraries available that can pretend to be external sources like files, databases and websites that allow you to test your code.
Python method invovation , missing parameter Question: Hi i'm trying to implement a profiling system so that as soon as the user logs in, the student is identified and pulls information from the student model and returns it to the homepage and probably every other page within the system. It will also append the student username to the end of the URL.... hopefully I get this error: > profile() missing 1 required positional argument: 'username' Urls.py # student urls.py # Import urls and patterns aswell as student views from django.conf.urls import patterns, url from student import views urlpatterns = patterns('', url(r'^(?P<username>[a-zA-Z0-9]+)$', views.index, name='index'), url(r'^$', views.profile, name='profile')) Models.py # student models.py # Import the models db and validators # Also import user information for log in identification from django.db import models from django.core.validators import * from django.contrib.auth.models import User # Specify attributes for the student database class student(models.Model): # Specify choices for years, gender and degree type YEARS = ( ('1', '1st'), ('2', '2nd'), ('3', '3rd'), ) GENDER = ( ('M', 'Male'), ('F', 'Female'), ) DEGREE = ( ('IT', 'Information Technology'), ('CS', 'Computer Science'), ) # Attributes for the student model specified here user = models.OneToOneField(User) student_ID = models.CharField(unique=True, max_length=9, validators=[RegexValidator(regex='^[0-9]{9,9}$', message='Must be 9 unique numbers', code='nomatch')]) first_name = models.CharField(max_length=128) middle_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) gender = models.CharField(max_length=1, choices=GENDER) year = models.CharField(max_length=1, choices=YEARS) degree = models.CharField(max_length=2, choices=DEGREE) photo = models.ImageField(upload_to="profile_pictures", null=True, blank=True) def __str__(self): return self.student_ID Views.py # student views.py # Import rendering and httpresponse # Also import student model from django.shortcuts import render from django.http import HttpResponse from student.models import student from extra_curricular.models import extra_curricular from module.models import module from skill.models import skill from django.contrib.auth.models import User # Information box displayed on each page def index(request, username): user = User.objects.get(username=username) person = student.objects.get(user=user) return render(request, 'student/home.html', {"person":person}) #Profile page information def profile(request, username): user = User.objects.get(username=username) person = student.objects.get(user=user) experience = extra_curricular.objects.get(user=user) module = module.objects.get(user=user) skill = skill.objects.get(user=user) return render(request, 'student/profile.html', {"person":person}, {"experience":experience}, {"module":module}, {"skill":skill}) Home.html {% block content %} <div class = "StudentInfoMain"> </div> <div id="Options"> <ul> <li><a href="/student/">Home</a></li> <li><a href="/extra_curricular/add_extra_curricular/">Add Information</a></li> <li><a href="#">View User Profile</a></li> <li><a href="#">Checklist</a></li> <li><a href="/skill/add_skill/">My Skills</a></li> <li><a href="/alumni/Find_Alumni/">Contact Alumni</a></li> </ul> </div> <div class = "Homebanner"> <p>{{ user.username }}</p> <p>{{ person.student_ID }}</p> <p>{{ person.first_name}}</p> <p>{{ person.last_name }}</p> <p>{{ person.year }}</p> <p>{{ person.degree }}</p> </div> <div id = "Homebody"> <p>Hello {{person.first_name}</p> <p>Welcome to your E-Profile</p> <br> <p>This application is intended as an aid to you during your employment endeavours.</p> <p>It can be used during the process of building a curriculum vitae</p> <p>You may add information of experiences you have had during your educational career</p> <br> <p>For any further information: </p> <br> </div> <footer> </footer> {% endblock %} Answer: def profile(request, username): views.profile takes an extra argument along with the request which you haven't passed. url(r'^$', views.profile, name='profile')
python - Substrings which contain only 'a', 'b' or 'c' Question: I was coding for [this problem.](https://www.hackerearth.com/problem/algorithm/substring/) > Maggu has just joined play school. His teacher taught him A,a,B,b,C,c. He is > much fascinated with these letters and now he is looking only for those > strings which contains these letters only. But as i said he is a little guy > he cant calculate the number of such sub-strings alone. Find the number of > such strings. def substrings(string): for size in range(1, len(string)+1): for index in range(len(string)-size+1): yield string[index:index+size] l = [] for x in range(int(raw_input())): l.append(raw_input().lower()) not_ = 'defghijklmnopqrstuvwxyz' for string in l: count = 0 for substr in substrings(string): if all(letter not in substr for letter in not_): count = count + 1 print(count) I realized that we can reduce the problem to lower case. I've wrote the code but it is not efficient for large strings. And by large I mean exceptionally large strings. I have realized that it is the `substrings` function that is taking up a lot of time. How may I reduce the time consumption of the `substrings` function? Can I replace it with some other code? Thanks. Answer: The reason why this is exponential is because you iterate over the same string for different window lengths (up to len(string)). This is a job for regular expressions, which will simply make one pass over your string to find any sequences that contain the letters a, b, c, A, B, and C in succession at least once. After you have found these sequences, you can calculate their arithmetic progression to count how many substrings each of those contain. To understand why we have to use arithmetic progression, consider we have found the sequence 'abc' somewhere in the big string. The actual substrings of this sequence are 'a', 'ab', 'abc', 'b', 'bc', and 'c'. Basically, for a string of length n, we can construct n substrings starting from the first letter, n-1 substrings starting from the second letter, ..., and 1 substring starting from the last letter. import re def count_substrings(string): found = re.findall('[a-cA-C]+', string) count = 0 for f in found: length = len(f) count += length * (length + 1) / 2 return count For the example shown in the link >>> strings = ['AXa', 'ABC', 'AXBC', 'AaBbCc', 'XxYyZz'] >>> for s in strings: ... print(count_substrings(s)) 2 6 4 21 0 * * * If you want to implement what `re.findall()` does yourself, you can try the following. found = [] substring = '' for s in string: if s in 'abcABC': substring += s else: # if we had a sequence going, it just ended, so add it to our found list if substring: found.append(substring) substring = '' # make sure to append the last sequence we had been working on if substring: found.append(substring)
Search word in python Question: I have text file, I am searching for specific word "Belief". I want the word to be shown in red colour if it was found. searchfile = open("demo.txt", "r") text=input("Enter search word :") for line in searchfile: if text in line: print(line) searchfile.close() Answer: You can get colors as shown [here](http://stackoverflow.com/questions/287871/print-in-terminal-with- colors-using-python) If you are not using Windows you could try `termcolor` to do something like this: from termcolor import colored text=input("Enter search word :") with open("demo.txt", "r") as searchfile: for line in searchfile: if text in line: print(colored(text,'red').join(line.split(text))) Example: s = "123 321 123 321 123" print(colored("321",'red').join(s.split("321"))) With output: [![enter image description here](http://i.stack.imgur.com/McqsP.png)](http://i.stack.imgur.com/McqsP.png) If you do use windows, you could still run the same code as above, as long as you add the following two lines at the beginning of your script: from colorama import init init() Both libraries are pip-installable and lightweight.
Multiple .replace() ?? and understanding the "u" which gets added to record from excel file (Python) Question: I need some help with this code: import pyexcel as pe import pyexcel.ext.xls import pyexcel.ext.xlsx def randStrings(excelFile1,excelFile2): getNameList = pe.get_sheet(file_name=excelFile1) randName = sum([i for i in getNameList],[]) getCompanyList = pe.get_sheet(file_name=excelFile2) randCompany = sum([i for i in getCompanyList],[]) randStrings.name = random.choice(randName) randStrings.combinedString = random.choice(randName) + "@" + random.choice(randCompany).lower().replace(" ","").replace("'","").replace("/","").replace(".","").replace(",","") +".com" return randStrings.name, randStrings.combinedString randStrings("names.xlsx","companys.xlsx") data = {'user_name':randStrings.name,'user_email': randStrings.combinedString} print data my output is : {'user_name': u'duky', 'user_email': u'[email protected]'} Need help or advice for two things : 1.Does anyone have a idea or can explain on why there is 'u' character when getting a record from the excel sheet?? and how to remove this from the output? 2. As you can I've done a extra long .replace() to get rid of any gremlins within the excel . Is there a short or more clean way to do this? like a python reg ex or something. I haven't found any examples dealing with multiple replacements for formating. Cheers Answer: The u' in front of your records means that they are encode as unicode. >>> a=u'test' >>> a u'test' >>> type(a) <type 'unicode'> >>> b="b" >>> b 'b' >>> type(b) <type 'str'> >>>
Logging values of variable with kivy.logger Question: I want to log the value of a variable using kivy.logger in file. I added the following lines to my code: from kivy.logger import Logger Logger.debug('EZS-2G: element: %s', str(element)) the following line appears in my IDE (Atom): [DEBUG ] [EZS-2G ] element: tab_0_obj_sensor but the log file under C:\Users\username.kivy\logs says only: [DEBUG ] EZS-2G: %s * How could I write the correct value into the logfile instead of %s? * How could I change the folder of the log files? After the packaging (creating a "myapp/myapp.exe") I want to read the logs in the myapp/logs folder, instead of the "C:\Users\username.kivy\logs" folder? OS: Win7 ; Python: 3.4 ; Kivy: 1.9 Answer: * try `'EZS-2G: element: {}'.format(element)` * change `log_dir` in the config, check [Logger configuration](https://kivy.org/docs/api-kivy.logger.html?highlight=logger#logger-configuration)
Interrupt a blocking evdev reading Question: I have a module that captures all reads from a barcode scanner. My problem is that I can not close it properly. After sending a KeyboardInterrupt or SystemExit signal, it stops only when I scan a barcode. I tried to add this method to the BarcodeScanner class, but it still doesn't work: def interrupt(self): """Envoi la demande d'arrêt.""" super(BarcodeScanner, self).interrupt() self.device.write(ecodes.EV_KEY, ecodes.KEY_ESC, 0) self.device.write(ecodes.EV_SYN, ecodes.SYN_REPORT, 0) How can I do that? **interruptable.py** #!/usr/bin/env python3 # -*-coding:Utf-8 -* class Interruptable: """Classe intégrant une boucle sans fin pouvant être stoppée proprement.""" interruptables = [] def __init__(self): """Crée un objet interruptible.""" self._interrupted = False Interruptable.interruptables.append(self) def interrupt(self): """Envoi la demande d'arrêt.""" self._interrupted = True def reset(self): """Permet le redémarrage d'un service.""" self._interrupted = False def interrupted(self): """Verifie si la demande d'arrêt à déjà été envoyée.""" return self._interrupted **barcode_scanner.py** #!/usr/bin/env python3 # -*-coding:Utf-8 -* from evdev import InputDevice, ecodes, list_devices, categorize import signal, sys import threading from time import sleep from tymsoft.interruptable import Interruptable class BarcodeScanner(Interruptable): """TODO""" def __init__(self, device_name='Bar Code', layout='AZERTY_FR'): self.modifiers = { # 0: None, 29: u'LCTRL', 42: u'LSHFT', 54: u'RSHFT', 56: u'LALT', 97:u'RCTRL', 100: u'RALT' 0: 0, 29: 1, 42: 2, 54: 3, 56: 4, 97: 5, 100: 6 } self.layouts = { 'AZERTY_FR': { # [NORMAL, LCTRL, LSHFT, RSHFT, LALT, RCTRL, RALT] 2: [u'&', u'', u'1', u'1', u'', u'', u''], 3: [u'é', u'', u'2', u'2', u'', u'', u'~'], 4: [u'"', u'', u'3', u'3', u'', u'', u'#'], 5: [u'\'', u'', u'4', u'4', u'', u'', u'{'], 6: [u'(', u'', u'5', u'5', u'', u'', u'['], 7: [u'-', u'', u'6', u'6', u'', u'', u'|'], 8: [u'è', u'', u'7', u'7', u'', u'', u'`'], 9: [u'_', u'', u'8', u'8', u'', u'', u'\\'], 10: [u'ç', u'', u'9', u'9', u'', u'', u'^'], 11: [u'à', u'', u'0', u'0', u'', u'', u'@'], 12: [u')', u'', u'°', u'°', u'', u'', u']'], 13: [u'=', u'', u'+', u'+', u'', u'', u'}'], 15: [u'\t', u'', u'', u'', u'', u'', u''], 16: [u'a', u'', u'A', u'A', u'', u'', u''], 17: [u'z', u'', u'Z', u'Z', u'', u'', u''], 18: [u'e', u'', u'E', u'E', u'', u'', u'€'], 19: [u'r', u'', u'R', u'R', u'', u'', u''], 20: [u't', u'', u'T', u'T', u'', u'', u''], 21: [u'y', u'', u'Y', u'Y', u'', u'', u''], 22: [u'u', u'', u'U', u'U', u'', u'', u''], 23: [u'i', u'', u'I', u'I', u'', u'', u''], 24: [u'o', u'', u'O', u'O', u'', u'', u''], 25: [u'p', u'', u'P', u'P', u'', u'', u''], 26: [u'^', u'', u'¨', u'¨', u'', u'', u''], 27: [u'$', u'', u'£', u'£', u'', u'', u'¤'], 28: [u'\n', u'', u'', u'', u'', u'', u''], 30: [u'q', u'', u'Q', u'Q', u'', u'', u''], 31: [u's', u'', u'S', u'S', u'', u'', u''], 32: [u'd', u'', u'D', u'D', u'', u'', u''], 33: [u'f', u'', u'F', u'F', u'', u'', u''], 34: [u'g', u'', u'G', u'G', u'', u'', u''], 35: [u'h', u'', u'H', u'H', u'', u'', u''], 36: [u'j', u'', u'J', u'J', u'', u'', u''], 37: [u'k', u'', u'K', u'K', u'', u'', u''], 38: [u'l', u'', u'L', u'L', u'', u'', u''], 39: [u'm', u'\n', u'M', u'M', u'', u'', u''], 40: [u'ù', u'', u'%', u'%', u'', u'', u''], 41: [u'²', u'', u'', u'', u'', u'', u''], 43: [u'*', u'', u'µ', u'µ', u'', u'', u''], 44: [u'w', u'', u'W', u'W', u'', u'', u''], 45: [u'x', u'', u'X', u'X', u'', u'', u''], 46: [u'c', u'', u'C', u'C', u'', u'', u''], 47: [u'v', u'', u'V', u'V', u'', u'', u''], 48: [u'b', u'', u'B', u'B', u'', u'', u''], 49: [u'n', u'', u'N', u'N', u'', u'', u''], 50: [u',', u'', u'?', u'?', u'', u'', u''], 51: [u';', u'', u'.', u'.', u'', u'', u''], 52: [u':', u'', u'/', u'/', u'', u'', u''], 53: [u'!', u'', u'§', u'§', u'', u'', u''], 57: [u' ', u'', u' ', u' ', u'', u'', u''], 86: [u'<', u'', u'>', u'>', u'', u'', u''], 96: [u'\n', u'', u'', u'', u'', u'', u''] }, 'QWERTY_US': { # [NORMAL, LCTRL, LSHFT, RSHFT, LALT, RCTRL, RALT] 2: [u'1', u'', u'!', u'!', u'', u'', u''], 3: [u'2', u'', u'@', u'@', u'', u'', u''], 4: [u'3', u'', u'#', u'#', u'', u'', u''], 5: [u'4', u'', u'$', u'$', u'', u'', u''], 6: [u'5', u'', u'%', u'%', u'', u'', u''], 7: [u'6', u'', u'^', u'^', u'', u'', u''], 8: [u'7', u'', u'&', u'&', u'', u'', u''], 9: [u'8', u'', u'*', u'*', u'', u'', u''], 10: [u'9', u'', u'(', u'(', u'', u'', u''], 11: [u'0', u'', u')', u')', u'', u'', u''], 12: [u'-', u'', u'_', u'_', u'', u'', u''], 13: [u'=', u'', u'+', u'+', u'', u'', u''], 15: [u'\t', u'', u'', u'', u'', u'', u''], 16: [u'q', u'', u'Q', u'Q', u'', u'', u''], 17: [u'w', u'', u'W', u'W', u'', u'', u''], 18: [u'e', u'', u'E', u'E', u'', u'', u''], 19: [u'r', u'', u'R', u'R', u'', u'', u''], 20: [u't', u'', u'T', u'T', u'', u'', u''], 21: [u'y', u'', u'Y', u'Y', u'', u'', u''], 22: [u'u', u'', u'U', u'U', u'', u'', u''], 23: [u'i', u'', u'I', u'I', u'', u'', u''], 24: [u'o', u'', u'O', u'O', u'', u'', u''], 25: [u'p', u'', u'P', u'P', u'', u'', u''], 26: [u'[', u'', u'{', u'{', u'', u'', u''], 27: [u']', u'', u'}', u'}', u'', u'', u''], 28: [u'\n', u'', u'', u'', u'', u'', u''], 30: [u'a', u'', u'A', u'A', u'', u'', u''], 31: [u's', u'', u'S', u'S', u'', u'', u''], 32: [u'd', u'', u'D', u'D', u'', u'', u''], 33: [u'f', u'', u'F', u'F', u'', u'', u''], 34: [u'g', u'', u'G', u'G', u'', u'', u''], 35: [u'h', u'', u'H', u'H', u'', u'', u''], 36: [u'j', u'', u'J', u'J', u'', u'', u''], 37: [u'k', u'', u'K', u'K', u'', u'', u''], 38: [u'l', u'', u'L', u'L', u'', u'', u''], 39: [u';', u'', u':', u':', u'', u'', u''], 40: [u'\'', u'', u'"', u'"', u'', u'', u''], 41: [u'`', u'', u'~', u'~', u'', u'', u''], 43: [u'\\', u'', u'|', u'|', u'', u'', u''], 44: [u'z', u'', u'Z', u'Z', u'', u'', u''], 45: [u'x', u'', u'X', u'X', u'', u'', u''], 46: [u'c', u'', u'C', u'C', u'', u'', u''], 47: [u'v', u'', u'V', u'V', u'', u'', u''], 48: [u'b', u'', u'B', u'B', u'', u'', u''], 49: [u'n', u'', u'N', u'N', u'', u'', u''], 50: [u'm', u'\n', u'M', u'M', u'', u'', u''], 51: [u',', u'', u'<', u'<', u'', u'', u''], 52: [u'.', u'', u'>', u'>', u'', u'', u''], 53: [u'/', u'', u'?', u'?', u'', u'', u''], 57: [u' ', u'', u' ', u' ', u'', u'', u''], 96: [u'\n', u'', u'', u'', u'', u'', u''] } } self.eol = [(0, 28), (0, 96), (29, 39)] self.layout = layout self.device = None devices = map(InputDevice, list_devices()) for device in devices: if device_name in device.name: self.device = InputDevice(device.fn) print('Lecteur de codes-barres : ' + device.name) break self._listeners = [] Interruptable.__init__(self) self.device.grab() def start_capture(self): """TODO""" def run(): barcode = '' modifier = 0 keycode = 0 for event in self.device.read_loop(): if not self.interrupted(): if event.type == ecodes.EV_KEY: data = categorize(event) if data.keystate == 1: if data.scancode in self.modifiers: modifier = data.scancode elif data.scancode in self.layouts[self.layout]: keycode = data.scancode elif event.type == ecodes.EV_SYN: if (modifier, keycode) in self.eol: if len(barcode) > 0: for listener in self._listeners: listener(barcode) barcode = '' elif keycode != 0: barcode += self.layouts[self.layout][keycode][self.modifiers[modifier]] modifier = 0 keycode = 0 else: self.device.ungrab() break thread = threading.Thread(target=run, name='barcode_scanner') thread.start() def register_listener(self, callback): self._listeners.append(callback) Answer: I solved the issue by replacing the read_loop() method by a loop of select()+read(). In this way, I could put a timeout on the select. #!/usr/bin/env python3 # -*-coding:Utf-8 -* from evdev import InputDevice, ecodes, list_devices, categorize from select import select import signal, sys import threading from time import sleep from tymsoft.interruptable import Interruptable class BarcodeScanner(Interruptable): """TODO""" def __init__(self, device_name='Bar Code', layout='AZERTY_FR'): self.modifiers = { # 0: None, 29: u'LCTRL', 42: u'LSHFT', 54: u'RSHFT', 56: u'LALT', 97:u'RCTRL', 100: u'RALT' 0: 0, 29: 1, 42: 2, 54: 3, 56: 4, 97: 5, 100: 6 } self.layouts = { 'AZERTY_FR': { # [NORMAL, LCTRL, LSHFT, RSHFT, LALT, RCTRL, RALT] 2: [u'&', u'', u'1', u'1', u'', u'', u''], 3: [u'é', u'', u'2', u'2', u'', u'', u'~'], 4: [u'"', u'', u'3', u'3', u'', u'', u'#'], 5: [u'\'', u'', u'4', u'4', u'', u'', u'{'], 6: [u'(', u'', u'5', u'5', u'', u'', u'['], 7: [u'-', u'', u'6', u'6', u'', u'', u'|'], 8: [u'è', u'', u'7', u'7', u'', u'', u'`'], 9: [u'_', u'', u'8', u'8', u'', u'', u'\\'], 10: [u'ç', u'', u'9', u'9', u'', u'', u'^'], 11: [u'à', u'', u'0', u'0', u'', u'', u'@'], 12: [u')', u'', u'°', u'°', u'', u'', u']'], 13: [u'=', u'', u'+', u'+', u'', u'', u'}'], 15: [u'\t', u'', u'', u'', u'', u'', u''], 16: [u'a', u'', u'A', u'A', u'', u'', u''], 17: [u'z', u'', u'Z', u'Z', u'', u'', u''], 18: [u'e', u'', u'E', u'E', u'', u'', u'€'], 19: [u'r', u'', u'R', u'R', u'', u'', u''], 20: [u't', u'', u'T', u'T', u'', u'', u''], 21: [u'y', u'', u'Y', u'Y', u'', u'', u''], 22: [u'u', u'', u'U', u'U', u'', u'', u''], 23: [u'i', u'', u'I', u'I', u'', u'', u''], 24: [u'o', u'', u'O', u'O', u'', u'', u''], 25: [u'p', u'', u'P', u'P', u'', u'', u''], 26: [u'^', u'', u'¨', u'¨', u'', u'', u''], 27: [u'$', u'', u'£', u'£', u'', u'', u'¤'], 28: [u'\n', u'', u'', u'', u'', u'', u''], 30: [u'q', u'', u'Q', u'Q', u'', u'', u''], 31: [u's', u'', u'S', u'S', u'', u'', u''], 32: [u'd', u'', u'D', u'D', u'', u'', u''], 33: [u'f', u'', u'F', u'F', u'', u'', u''], 34: [u'g', u'', u'G', u'G', u'', u'', u''], 35: [u'h', u'', u'H', u'H', u'', u'', u''], 36: [u'j', u'', u'J', u'J', u'', u'', u''], 37: [u'k', u'', u'K', u'K', u'', u'', u''], 38: [u'l', u'', u'L', u'L', u'', u'', u''], 39: [u'm', u'\n', u'M', u'M', u'', u'', u''], 40: [u'ù', u'', u'%', u'%', u'', u'', u''], 41: [u'²', u'', u'', u'', u'', u'', u''], 43: [u'*', u'', u'µ', u'µ', u'', u'', u''], 44: [u'w', u'', u'W', u'W', u'', u'', u''], 45: [u'x', u'', u'X', u'X', u'', u'', u''], 46: [u'c', u'', u'C', u'C', u'', u'', u''], 47: [u'v', u'', u'V', u'V', u'', u'', u''], 48: [u'b', u'', u'B', u'B', u'', u'', u''], 49: [u'n', u'', u'N', u'N', u'', u'', u''], 50: [u',', u'', u'?', u'?', u'', u'', u''], 51: [u';', u'', u'.', u'.', u'', u'', u''], 52: [u':', u'', u'/', u'/', u'', u'', u''], 53: [u'!', u'', u'§', u'§', u'', u'', u''], 57: [u' ', u'', u' ', u' ', u'', u'', u''], 86: [u'<', u'', u'>', u'>', u'', u'', u''], 96: [u'\n', u'', u'', u'', u'', u'', u''] }, 'QWERTY_US': { # [NORMAL, LCTRL, LSHFT, RSHFT, LALT, RCTRL, RALT] 2: [u'1', u'', u'!', u'!', u'', u'', u''], 3: [u'2', u'', u'@', u'@', u'', u'', u''], 4: [u'3', u'', u'#', u'#', u'', u'', u''], 5: [u'4', u'', u'$', u'$', u'', u'', u''], 6: [u'5', u'', u'%', u'%', u'', u'', u''], 7: [u'6', u'', u'^', u'^', u'', u'', u''], 8: [u'7', u'', u'&', u'&', u'', u'', u''], 9: [u'8', u'', u'*', u'*', u'', u'', u''], 10: [u'9', u'', u'(', u'(', u'', u'', u''], 11: [u'0', u'', u')', u')', u'', u'', u''], 12: [u'-', u'', u'_', u'_', u'', u'', u''], 13: [u'=', u'', u'+', u'+', u'', u'', u''], 15: [u'\t', u'', u'', u'', u'', u'', u''], 16: [u'q', u'', u'Q', u'Q', u'', u'', u''], 17: [u'w', u'', u'W', u'W', u'', u'', u''], 18: [u'e', u'', u'E', u'E', u'', u'', u''], 19: [u'r', u'', u'R', u'R', u'', u'', u''], 20: [u't', u'', u'T', u'T', u'', u'', u''], 21: [u'y', u'', u'Y', u'Y', u'', u'', u''], 22: [u'u', u'', u'U', u'U', u'', u'', u''], 23: [u'i', u'', u'I', u'I', u'', u'', u''], 24: [u'o', u'', u'O', u'O', u'', u'', u''], 25: [u'p', u'', u'P', u'P', u'', u'', u''], 26: [u'[', u'', u'{', u'{', u'', u'', u''], 27: [u']', u'', u'}', u'}', u'', u'', u''], 28: [u'\n', u'', u'', u'', u'', u'', u''], 30: [u'a', u'', u'A', u'A', u'', u'', u''], 31: [u's', u'', u'S', u'S', u'', u'', u''], 32: [u'd', u'', u'D', u'D', u'', u'', u''], 33: [u'f', u'', u'F', u'F', u'', u'', u''], 34: [u'g', u'', u'G', u'G', u'', u'', u''], 35: [u'h', u'', u'H', u'H', u'', u'', u''], 36: [u'j', u'', u'J', u'J', u'', u'', u''], 37: [u'k', u'', u'K', u'K', u'', u'', u''], 38: [u'l', u'', u'L', u'L', u'', u'', u''], 39: [u';', u'', u':', u':', u'', u'', u''], 40: [u'\'', u'', u'"', u'"', u'', u'', u''], 41: [u'`', u'', u'~', u'~', u'', u'', u''], 43: [u'\\', u'', u'|', u'|', u'', u'', u''], 44: [u'z', u'', u'Z', u'Z', u'', u'', u''], 45: [u'x', u'', u'X', u'X', u'', u'', u''], 46: [u'c', u'', u'C', u'C', u'', u'', u''], 47: [u'v', u'', u'V', u'V', u'', u'', u''], 48: [u'b', u'', u'B', u'B', u'', u'', u''], 49: [u'n', u'', u'N', u'N', u'', u'', u''], 50: [u'm', u'\n', u'M', u'M', u'', u'', u''], 51: [u',', u'', u'<', u'<', u'', u'', u''], 52: [u'.', u'', u'>', u'>', u'', u'', u''], 53: [u'/', u'', u'?', u'?', u'', u'', u''], 57: [u' ', u'', u' ', u' ', u'', u'', u''], 96: [u'\n', u'', u'', u'', u'', u'', u''] } } self.eol = [(0, 28), (0, 96), (29, 39)] self.layout = layout self.device = None devices = map(InputDevice, list_devices()) for device in devices: if device_name in device.name: self.device = InputDevice(device.fn) print('Lecteur de codes-barres : ' + device.name) break self._listeners = [] Interruptable.__init__(self) self.device.grab() def start_capture(self): """TODO""" def run(): barcode = '' modifier = 0 keycode = 0 while not self.interrupted(): select([self.device], [], [], 0.25) try: for event in self.device.read(): if event.type == ecodes.EV_KEY: data = categorize(event) if data.keystate == 1: if data.scancode in self.modifiers: modifier = data.scancode elif data.scancode in self.layouts[self.layout]: keycode = data.scancode elif event.type == ecodes.EV_SYN: if (modifier, keycode) in self.eol: if len(barcode) > 0: for listener in self._listeners: listener(barcode) barcode = '' elif keycode != 0: barcode += self.layouts[self.layout][keycode][self.modifiers[modifier]] modifier = 0 keycode = 0 except BlockingIOError: pass self.device.ungrab() thread = threading.Thread(target=run, name='barcode_scanner') thread.start() def register_listener(self, callback): self._listeners.append(callback)
Python - Pymediainfo Module [Error 126] The specified module could not be found Question: The error I'm receiving is this: Traceback (most recent call last): File "C:\Users\Me\test3.py", line 4, in <module> media_info = MediaInfo.parse("video.mp4") File "C:\Python27\lib\site-packages\pymediainfo-2.0-py2.7.egg\pymediainfo\__init__.py", line 70, in parse lib = windll.MediaInfo File "C:\Python27\lib\ctypes\__init__.py", line 435, in __getattr__ dll = self._dlltype(name) File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found Pymediainfo has been the only module to have caused this error for me. To see if the problem was related to pip, I reinstalled it through the zip file found [here](https://github.com/sbraz/pymediainfo) to no avail. Here is the code causing the error: from pymediainfo import MediaInfo # sample code from pymediainfo docs media_info = MediaInfo.parse("video.mp4") for track in media_info.tracks: if track.track_type == 'Video': print track.bit_rate, track.bit_rate_mode, track.codec If you need any more info, let me know. Answer: I guess you forgot to add the dll path for Mediainfo.dll. import os os.environ['PATH'] = os.path.dirname('file/path/to/Mediainfo.dll') + ';' + os.environ['PATH']
Compare some text with difflib and openpyxl Python Question: I want to find some words in some cells of a certain column. Those words (use to compare) are stocked in another sheet. I'm trying to use a loop to choose all the cells from this column. I got this code : import difflib import openpyxl from openpyxl import load_workbook table = "C:\Users\Myname\Documents\Python Scripts\TRY.xlsx" table = load_workbook(table) table.get_sheet_names() # [u'Compared', u'To'] work_sheet = table['Compared'] compare_sheet = table['To'] row_max = sum(1 for row in work_sheet) # count the number of rows print ( row_max) # 8 liste = range(1,row_max+1) print liste for i in liste: a = 'A' b = 'B' index = a + `i` comp = b + `i` column1 = ''.join(["'", index,"'"]) # Ref to the Cell which will be compared column2 = ''.join(["'",comp,"'"]) # Ref to the word I want to find print (column1) print (column2) diff = difflib.SequenceMatcher(None,work_sheet[{}].format(column1),compare_sheet[{}].value.format(column2)).ratio() print diff # ERROR # File "C:\Users\Myname\AppData\Local\Continuum\Anaconda2\lib\site-packages\openpyxl-2.3.4-py2.7.egg\ # openpyxl\utils\__init__.py", line 39, in coordinate_from_string # match = COORD_RE.match(coord_string.upper()) I've looked at this line 39 in the file "__ init__.py" and I have : def coordinate_from_string(coord_string): """Convert a coordinate string like 'B12' to a tuple ('B', 12)""" match = COORD_RE.match(coord_string.upper()) if not match: msg = 'Invalid cell coordinates (%s)' % coord_string raise CellCoordinatesException(msg) column, row = match.groups() row = int(row) if not row: msg = "There is no row 0 (%s)" % coord_string raise CellCoordinatesException(msg) return (column, row) but if I do it manually, it works : diff = difflib.SequenceMatcher(None, work_sheet['A2'].value, compare_sheet['B2'].value).ratio() print diff # 0.133333333333 You can see the table here : <https://docs.google.com/spreadsheets/d/1Mckc6YXeWQQ0CrnLKFqH5jeUMUn9CjvW_pTYs1rvw1A/edit?usp=sharing> Can someone explains me where does this error come from ? (The whole traceback : Traceback (most recent call last): File "<ipython-input-14-ed4b6265ee5a>", line 43, in <module> diff = difflib.SequenceMatcher(None,work_sheet[{}].format(column1),compare_sheet[{}].value.format(column2)).ratio() File "C:\Users\Myname\AppData\Local\Continuum\Anaconda2\lib\site-packages\openpyxl-2.3.4-py2.7.egg\openpyxl\worksheet\worksheet.py", line 338, in __getitem__ row, column = coordinate_to_tuple(key) File "C:\Users\Myname\AppData\Local\Continuum\Anaconda2\lib\site-packages\openpyxl-2.3.4-py2.7.egg\openpyxl\utils\__init__.py", line 162, in coordinate_to_tuple col, row = coordinate_from_string(coordinate) File "C:\Users\Myname\AppData\Local\Continuum\Anaconda2\lib\site-packages\openpyxl-2.3.4-py2.7.egg\openpyxl\utils\__init__.py", line 39, in coordinate_from_string match = COORD_RE.match(coord_string.upper()) ) Answer: As was pointed out, you don't show the code that causes the traceback, and you don't show the traceback -- you should copy and paste. Your code has lots of problems. I edit it below import difflib # line below never used # import openpyxl from openpyxl import load_workbook table = "C:\Users\Myname\Documents\Python Scripts\TRY.xlsx" table = load_workbook(table) table.get_sheet_names() # [u'Compared', u'To'] work_sheet = table['Compared'] compare_sheet = table['To'] # is there not an easier way to find out how many rows? row_max = sum(1 for row in work_sheet) # count the number of rows print ( row_max) # 8 # remove these lines # liste = range(1,row_max+1) # print liste # for i in liste: for i in range(1, row_max+1): # a = 'A' # b = 'B' # what do you think index and comp are after these two lines? # index = a + `i` # comp = b + `i` index = 'A' + str(i) comp = 'B' + str(i) column1 = ''.join(["'", index,"'"]) # Ref to the Cell which will be compared column2 = ''.join(["'",comp,"'"]) # Ref to the word I want to find print (column1) print (column2) diff = difflib.SequenceMatcher(None,work_sheet[{}].format(column1),compare_sheet[{}].value.format(column2)).ratio() print diff # ERROR # match = COORD_RE.match(coord_string.upper()) # #AttributeError: 'dict' object has no attribute 'upper'
How can I crawl only a particular domain using Python? Question: I need to start with a domain and extract all links from the site, then continue on and extract the links from those links. However, I am only supposed to traverse the links that are part of the given domain. I'm using BeautifulSoup. The only way I can think to do this is to test whether the href is in the form href='www.someotherdomain.com' or of the form href = 'page1/page2'. The former would indicate that the link points to a new domain and the latter would indicate that the link points to a page within the same domain. So I've created a function called has_domain to check to see if the link has its own domain already. The code looks like this: def has_domain(url): if 'www.' in url: return True else: return False The problem is, not every link outside the seed domain starts with 'www.' Is there an easier way to check to see if a link points to a new domain? Answer: You can use urlparse to grab the hostname and then check if it's in a list or compare it directly to a string. Here's an example of comparing it to a list of domains, notice it treats the "www" variation as a different domain name. from urlparse import urlparse url_list = ["example.com", "www.example.com"] def has_domain(url): p = urlparse(url) if p.hostname in url_list: return True else: return False print has_domain("http://www.example.com")
Python BeautifulSoup can't read div tag Question: I'm trying to get products for a project i'm working on from this page:[lazada](http://www.lazada.co.id/catalog/?q=note%202) [page ispection](http://i.stack.imgur.com/lR24T.png) using : from bs4 import BeautifulSoup import urllib import re r = urllib.urlopen("http://www.lazada.co.id/catalog/?q=note+2").read() soup = BeautifulSoup(r,"lxml") letters = soup.findAll("span",class_=re.compile("product-card__name")) print type(letters) print letters[0] When I do this I am getting error Traceback (most recent call last): File "C:/Python27/project/testaja.py", line 9, in print letters[0] IndexError: list index out of range . Any thoughts on this? Answer: I think you may have hit their page too much, navigate there in a browser and see what the page returns on your network. Also, you can modify your code so you can check the page response header to make sure that the page returned properly before trying to scrape it. I modified your code to show an example of this below: from bs4 import BeautifulSoup import urllib import re r = urllib.urlopen("http://www.lazada.co.id/catalog/?q=note+2") header_code = r.getcode() if header_code == 200: html = r.read() soup = BeautifulSoup(html, "lxml") letters = soup.findAll("span", {"class" : re.compile("product-card__name")}) for letter in letters: print letter else: print("oops, something went wonky. Page response was: %s"% header_code)
Error finding current time in Python Question: I am trying to implement this time class to find the current time. I am getting wrong time. Can someone please take a look what am I doing wrong here? import time import datetime class Time(): def __init__(self): currentTime = time.time() totalSeconds = int(currentTime) self.__second = totalSeconds % 60 totalMinutes = totalSeconds // 60 self.__minute = totalMinutes %60 totalHours = totalMinutes// 60 self.__hour = totalHours % 12 def getSecond(self): return self.__second def getMinute(self): return self.__minute def getHour(self): return self.__hour def main(): t = Time() print("Current Time is : ", t.getHour(), ":", t.getMinute(), ":", t.getSecond()) print(datetime.datetime.now().time()) print(time.ctime()) main() Answer: Your code always deals with UTC times, but you are comparing the result with time in your time zone. Try this: def main(): t = Time() print("Current Time is : ", t.getHour(), ":", t.getMinute(), ":", t.getSecond()) print(datetime.datetime.utcnow().time()) print(time.asctime(time.gmtime()))
3D histograms and Contour plots Python Question: I have a problem with contourf function of matplotlib. I have a txt data file from which I am importing my data. I have columns of data (pm1 and pm2) and I am performing a 2D histogram. I want to plot this data as a 3D histogram and as a contour plot to see where is located the maximum values. This is my code: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') rows = np.arange(200,1300,10) hist, xedges, yedges = np.histogram2d (pm1_n, pm2_n, bins = (rows, rows) ) elements = (len(xedges) - 1) * (len(yedges) - 1) xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1]) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(elements) dx = 0.1 * np.ones_like(zpos) dy = dx.copy() dz = hist.flatten() #####The problem is here##### #ax.contourf(xpos,ypos,hist) #ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average') plt.show() I can plot the 3d bar graph but I am not able to plot the contour one, If I place `hist` in the contourf function I get the error: `Length of x must be number of columns in z` and if I place `dz` I get `Input z must be a 2D array` I also have tried using xedges and yexges but this doesn't solve the problem. I think that the problem is related with the shape of the return of the function histogram2D. But I don't know how to solve it. I would also like to perform a 3D bar plot with a colorcode changing form the minimum to the maximum value. Is there anyway to make this? Thank you Answer: Perhaps I don't understand what exactly you are trying to do since I don't know what your data looks like, but it seems wrong to have your `contourf` plot sharing the same axis as your `bar3d` plot. If you add an axis without the 3D projection to a new figure, you should be able to make a `contourf` plot just fine using `hist`. An example using data from a random, normal distribution: import numpy as np import matplotlib.pyplot as plt n_points = 1000 x = np.random.normal(0, 2, n_points) y = np.random.normal(0, 2, n_points) hist, xedges, yedges = np.histogram2d(x, y, bins=np.sqrt(n_points)) fig2D = plt.figure() ax2D = fig2D.add_subplot(111) ax2D.contourf(hist, interpolation='nearest', extent=(xedges[0], xedges[-1], yedges[0], yedges[-1])) plt.show() returns an image like [this](http://i.stack.imgur.com/u2JZ0.png). As for your second question, regarding a color-coded 3D bar plot, how about this (using the same data as above but with 1/10 the size): import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.colors as colors n_points = 100 x = np.random.normal(0, 2, n_points) y = np.random.normal(0, 2, n_points) hist, xedges, yedges = np.histogram2d(x, y, bins=np.sqrt(n_points)) # Following your data reduction process xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1]) length, width = 0.4, 0.4 xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(n_points) dx = np.ones(n_points) * length dy = np.ones(n_points) * width dz = hist.flatten() # This is where the colorbar customization comes in dz_normed = dz / dz.max() normed_cbar = colors.Normalize(dz_normed.min(), dz_normed.max()) # Using jet, but should work with any colorbar color = cm.jet(normed_cbar(dz_normed)) fig3D = plt.figure() ax3D = fig3D.add_subplot(111, projection='3d') ax3D.bar3d(xpos, ypos, zpos, dx, dy, dz, color=color) plt.show() I get [this image](http://i.stack.imgur.com/D9Pst.png).
python Selenium options drop down Question: I am new to python. I have a code in R that I am trying to replace with a python script. I am running into issues getting python to select a value from a drop down menu. This is the code in R that worked: remDr$findElement(using = 'xpath', "//select[@id = 'groupby1']/option[@value = 'ReportDate']")$clickElement() This is the HTML code: select style="" class="dropdown" name="groupby1" id="groupby1" accesskey="" waffle_affected_fields="" option value="ReportData">Report Date</option> here are a couple things I tried after searching how to do this in python and I keep running into errors. find_element_by_xpath("//select[@id='groupby1']/option[@value='ReportDate']").click() NameError: name 'find_element_by_xpath' is not defined Select(driver.find_element_by_css_selector("select#groupby1")).select_by_value('ReportDate').click() NameError: name 'Select' is not defined Any help is appropriated! Answer: These functions are properties of your `webdriver` instance. You need to do something like this: from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.python.org") driver.find_element_by_xpath("//select[@id='groupby1']/option[@value='ReportDate']").click() See the [getting started page](http://selenium-python.readthedocs.org/getting- started.html) for examples.
Python regexp \n issue Question: This searched ok: >>> re.search(r'(.*?)\r\n(.+?)\r\n', 'aaa\r\r\nbbb\r\n').groups() ('aaa\r', 'bbb') But when I replace one of three `b` to `\n` it not searched: >>> re.search(r'(.*?)\r\n(.+?)\r\n', 'aaa\r\r\nb\nc\r\n').groups() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'groups' But I want to parse in second case: ('aaa\r', 'b\nc') Answer: You need the [DOTALL](https://docs.python.org/2/library/re.html#re.DOTALL) flag: import re re.search(r'(.*?)\r\n(.+?)\r\n', 'aaa\r\r\nb\nc\r\n', flags=re.DOTALL).groups() result: ('aaa\r', 'b\nc')
Performance Issues With Natural Language Processing in MATLAB Question: For a class, I'm processing raw text documents (our examples include novels that can be downloaded from the Gutenberg project) and turning them into a dictionary data structure. For each word, I need to know which paragraph(s) it occurs in, and how many times in each paragraph. The procedure can be divided roughly as 1. Break document into words, removing whitespace, commas, periods, etc. 2. For each document, iterate over the words. Look up in dictionary. If the word exists, update its entry. If it doesn't exist, create a new entry. I'm doing this MATLAB because the rest of my work is in MATLAB and I didn't want to have to deal with another language/environment. It turns out MATLAB has some pretty good string processing functions. However, I'm disturbed by how slow my code is running. The first part I mentioned above is not a problem; I use a `parfor` loop and it goes pretty fast. The second part is where my problem is. My initial attempt at creating this dictionary was to use structs, a MATLAB built-in data type. The idea was to create a struct called `dictionary`, whose field names are the actual words, e.g., `dictionary.the` or `dictionary.gnome` for the words 'the' and 'gnome.' This worked provided the word was a valid field name (it couldn't be a contraction, for instance). But it ran slow, so I sought a different solution. My next attempt was to use a `containers.Map`, which is MATLAB's equivalent of a hash map or dictionary object. (One of my coworkers informed me that MATLAB is somewhat inefficient at looking up field names of structs, whereas the hash table has O(1) lookup time.) However, making this substitution actually _slowed down_ my performance! At this point, I feel I've some pretty substantial attempts at optimizing my code and am starting to wonder if MATLAB is really a sensible choice here. I'm basically trying to figure out whether the slowness is a product of MATLAB or of me being a terrible programmer (normally MATLAB is quite fast when it comes to linear algebra, arrays, and matrices). Rather than have someone read over my code, I'd greatly appreciate whatever feedback the community has to offer on either of the following: * Does anyone do this type of thing (i.e., language processing) in MATLAB or a similar language, such as Python? If so, I'd like to try to benchmark some of my timings. (I've got a MacBook, 2.8 GHz processor, and I'm currently getting about 10-20K words per second.) * Is it possible I'd get better results if I switched to a compiled language like Java or C++? Ballpark estimate, what kind of improvement? Answer: ### My idiosyncratic opinion: If your project can be nicely split between (1) text, data processing and (2) mathematical analysis, I'd do all of the former in Java or Python. (Note: I'm not an NLP guy.) MATLAB is either amazingly fast (eg. matrix operations using BLAS/LAPACK libraries) or shocking slow depending on _exactly_ what you are doing. There's no high performance HashMap solution in Matlab. Compared to what you can do in C++ or Java, using containers.Map is NOT fast. (I've heard people advocating using the struct, fieldname hack as a trick to get faster map performance in Matlab.) ### Quick and dirty, horribly imprecise test: Inserting 1 million randomly generated, unique strings into a containers.Map on my machine takes me about 30 seconds: tic(); for i=1:1000000 m(x{i}) = i; end toc(); Elapsed time is 38.781537 seconds. On the other hand, invoking the java virtual machine and running the code below takes my machine less than 2 seconds: HashMap<String, Double> hm = new HashMap<String, Double>(); Random r = new Random(); for(long i = 0; i < 1000000; i++) { hm.put(Double.toString(r.nextDouble()), r.nextDouble()); } mgunn@odysseus:~/MATLAB/delme/container_test$ time java ctest 1.697u 0.151s 0:00.91 202.1% 0+0k 0+1io 0pf+0w Accessing Java objects from MATLAB has a lot of overhead as well... tic(); h = java.util.HashMap; for i=1:1000000 h.put(x{i},i); end toc(); Elapsed time is 53.177989 seconds. ### Additional comments For maximum performance, it's hard to beat highly optimized c/c++ code. Unless you're extremely familiar with c/c++ though (and even then), you'll end up having headaches with memory management etc.... For academic coding, excellent vs. OK performance generally isn't so much an issue. Getting the code correct is more important than speed. Java or Python are easier languages to code in, with Java tending to have better performance of the two (but I'm not an expert here).
Python. Using CSV to read a file. Syntax Error Question: The following script shows syntax error at line "with open..." #!/usr/bin/python import fileinput; import csv; def read_csv_file ( file_name ): with open('file.csv', 'r') as my_csv_file: reader = csv.reader(my_csv_file) for row in reader: print ( row ) read_csv_file(); Answer: Your code: with open('file.csv', 'r') as my_csv_file: reader = csv.reader(my_csv_file) for row in reader: print ( row ) has incorrect indentation. It should be: with open('file.csv') as my_csv_file: # the 'r' mode is implicit reader = csv.reader(my_csv_file) for row in reader: # this line shouldn't have been indented print(row) Additionally, the `#!/usr/bin/python` will run the script with Python 2, not Python 3. Your system may have a very old version of Python 2 (2.4 or previous) that doesn't recognize the [`with`](https://www.python.org/dev/peps/pep-0343/) context manager. If you _must_ have a shebang, make it `#!/usr/bin/env python3.5` or something similar. Or, if you're not planning on setting the script as executable and running it as `./scriptname.py` or whatever, just get rid of it entirely. One more thing - don't name your file `csv.py`, as that will conflict with the `csv` module. Avoid naming files after any modules on your system. `csv_test.py` would be a better alternative, for example.
How to mock a BulkWriteException in python? Question: I need to get the information contained in the exception. This is the code I use. try: result = yield user_collection.insert_many(content, ordered=False) except BulkWriteError as e: print (e) And in my test when I get into the except with this line, self.insert_mock.side_effect = [BulkWriteError('')] it returns me > batch op errors occurred instead of a MagicMock or a Mock. How can I mock the `BulkWriteError` and give it a default `return_value` and see it when I use `print(e)`? Answer: Something like this should allow you to test your print was called correctly. import builtins # mockout print class BulkWriteErrorStub(BulkWriteError): ''' Stub out the exception so you can bypass the constructor. ''' def __str__: return 'fake_error' @mock.patch.object('builtins', 'print') def testRaisesBulkWrite(self, mock_print): ... self.insert_mock.side_effect = [BuilkWriteErrorStub] with self.assertRaises(...): mock_print.assert_called_once_with('fake_error') I haven't tested this so feel free to edit it if I made a mistake.
Indentation error in Python 2.7 Question: I'm getting an indentation error in this line of code (it's a comment with all spaces, no tabs), hope you can help me with this :) import os import socket import connection from constants import * """ get_file_listing lists the files in the directory. """ # geting IndentationError: unexpected indent at this line's 5th column def get_file_listing(connection,): files = os.listdir(connection.directory) answer = str(CODE_OK) + " " + error_messages[CODE_OK] + EOL for f in files: path = os.path.join(connection.directory, f) if os.path.isfile(path): answer += f + EOL answer += EOL return answer Answer: You have 2 indentation errors. First one is your comment between """ """ tags. It is normal string so it has to match indentation rules. Use # instead. Second one is line where you define your function. It needs to match indentation before. import os import socket import connection from constants import * """ get_file_listing lists the files in the directory. """ # geting IndentationError: unexpected indent at this line's 5th column def get_file_listing(connection,): files = os.listdir(connection.directory) answer = str(CODE_OK) + " " + error_messages[CODE_OK] + EOL for f in files: path = os.path.join(connection.directory, f) if os.path.isfile(path): answer += f + EOL answer += EOL return answer
What does Python string.maketrans("","") Question: string.maketrans("","") gives \x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13 \x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>? @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90 \x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2 \xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4 \xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9 \xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde \xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed \xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff What does this mean? And how does it help in removing punctuation in a string with the following call: import string myStr.translate(string.maketrans("",""), string.punctuation) Answer: I'll take some liberties, since Python 2 muddles the line being strings and bytes. There are 256 bytes, ranging from 0 to 255. You can get their byte representation by using `chr()`. So, all the bytes from 0 to 255 look like this >>> ''.join(map(chr, range(256))) '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\ x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:; <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80 \x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93 \x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6 \xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9 \xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc \xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf \xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2 \xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' [`string.maketrans(from, to)`](https://docs.python.org/2/library/string.html#string.maketrans) creates a string of 256 characters, where the characters in `from` will be replaced by `to`. For example, `string.maketrans('ab01', 'AB89')` will return the string from above, but `a` will be replaced by `A`, `b` by `B`, `0` by `8` and `1` by `9`. >>> string.maketrans('ab01', 'AB89') '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\ x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./8923456789:; <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ABcdefghijklmnopqrstuvwxyz{|}~\x7f\x80 \x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93 \x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6 \xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9 \xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc \xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf \xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2 \xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' Effectively, `string.maketrans('', '') == ''.join(map(chr, range(256)))`. This serves as a map, which when provided to [`str.translate()`](https://docs.python.org/2/library/string.html#string.translate), it can be used to replace multiple characters with one pass over your string. For the example map above, all characters will remain the same, except from all `a` turning into `A`, `b` into `B`, etc. If you do `myStr.translate(string.maketrans('', ''))`, you simply don't change anything in `myStr`. Finally, `translate()` has one additional argument, `deletechars`. If you pass a string for that argument, `translate()` will translate all characters according to the mapping you provide, but it will ignore, any characters in `deletechars`. So, putting it all together, `myStr.translate(string.maketrans('', ''), string.punctuation)` does not change any character in the string, but in the process will ignore any character in `string.punctuation`. Effectively, you have removed the punctuation in the output string.
Using Python Tkinter on Beaglebone: Display Flicker Question: Below is the code for displaying data on a monitor using Python and Tkinter on BeagleBone. It works great, but the text which displays the data flickers. Any ideas why? #!/usr/bin/python import alsaaudio as aa import audioop import Tkinter as tk import tkFont import threading import Queue started = False class Display(object): def __init__(self, parent, queue): self.parent = parent self.queue = queue self._geom = '200x200+0+0' parent.geometry("{0}x{1}+0+0".format( parent.winfo_screenwidth(), parent.winfo_screenheight())) parent.overrideredirect(1) parent.title('Listen') parent.configure(background='#000000') parent.displayFont = tkFont.Font(family="Unit-Bold", size=150) self.process_queue() def process_queue(self): try: scaled_vol = self.queue.get(0) self.print_message(scaled_vol) except Queue.Empty: pass self.parent.after(100, self.process_queue) def print_message(self, messageString): print 'message', messageString self.message = tk.Message( self.parent, text=messageString, bg="#000000", font=self.parent.displayFont, fg="#777777", justify="c") self.message.place(relx=.5, rely=.5, anchor="c") def setup_audio(queue, stop_event): data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, 'hw:1') data_in.setchannels(2) data_in.setrate(44100) data_in.setformat(aa.PCM_FORMAT_S16_LE) data_in.setperiodsize(256) while not stop_event.is_set(): # Read data from device l, data = data_in.read() if l: # catch frame error try: max_vol = audioop.rms(data, 2) scaled_vol = max_vol // 4680 print scaled_vol if scaled_vol <= 3: # Too quiet, ignore continue total_vol += scaled_vol / 10.0 if started and total_vol > 200.0: started = False elif started: queue.put(scaled_vol) except audioop.error, e: if e.message != "not a whole number of frames": raise e def main(): root = tk.Tk() queue = Queue.Queue() window = Display(root, queue) stop_event = threading.Event() audio_thread = threading.Thread(target=setup_audio, args=[queue, stop_event]) audio_thread.start() try: root.mainloop() finally: stop_event.set() audio_thread.join() pass if __name__ == '__main__': main() The monitor is 1920 x 1080. It is the only monitor I have to check it on. Answer: For completeness the version using `configure()`: #!/usr/bin/python import alsaaudio as aa import audioop import Tkinter as tk import tkFont import threading import Queue started = False class Display(object): def __init__(self, parent, queue): self.parent = parent self.queue = queue self._geom = '200x200+0+0' parent.geometry("{0}x{1}+0+0".format( parent.winfo_screenwidth(), parent.winfo_screenheight())) parent.overrideredirect(1) parent.title('Listen') parent.configure(background='#000000') parent.displayFont = tkFont.Font(family="Unit-Bold", size=150) self.create_message() self.process_queue() def process_queue(self): try: scaled_vol = self.queue.get(0) self.message.configure(scaled_vol) except Queue.Empty: pass self.parent.after(100, self.process_queue) def create_message(self): self.message = tk.Message( self.parent, text=messageString, bg="#000000", font=self.parent.displayFont, fg="#777777", justify="c") self.message.place(relx=.5, rely=.5, anchor="c") def setup_audio(queue, stop_event): data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, 'hw:1') data_in.setchannels(2) data_in.setrate(44100) data_in.setformat(aa.PCM_FORMAT_S16_LE) data_in.setperiodsize(256) while not stop_event.is_set(): # Read data from device l, data = data_in.read() if l: # catch frame error try: max_vol = audioop.rms(data, 2) scaled_vol = max_vol // 4680 print scaled_vol if scaled_vol <= 3: # Too quiet, ignore continue total_vol += scaled_vol / 10.0 if started and total_vol > 200.0: started = False elif started: queue.put(scaled_vol) except audioop.error, e: if e.message != "not a whole number of frames": raise e def main(): root = tk.Tk() queue = Queue.Queue() window = Display(root, queue) stop_event = threading.Event() audio_thread = threading.Thread(target=setup_audio, args=[queue, stop_event]) audio_thread.start() try: root.mainloop() finally: stop_event.set() audio_thread.join() pass if __name__ == '__main__': main()
django module import error - python 2.7 vs python 3.4 Question: I have installed django1.9 with python 2.7. But now I want to use it with python3.4. Hence I have modified symbolic link of python to python 3.4 like below. sudo ln -s /usr/bin/python3.4 /usr/bin/python Because same django works with python 2.7 and 3.4 as well so it should work. But now if I run ./mange.py runserver I am getting below error. **But with Python 2.7 the same code works properly.** from Helpers import views ImportError: No module named 'Helpers' Please let me know whats wrong there? Below are the project structure. myproject ├── myproject │ ├── settings.py │ ├── __init__.py │ ├── urls.py │ ├── wsgi.py │ └─── Helpers │ ├── views.py │ └── __init__.py └── manage.py Urls.py is like below. from django.conf.urls import url from Helpers import views urlpatterns = [ url(r'^$', views.index, name='index') ] setting.py contains below relevant information. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myproject', ] # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Look for modules here as well. sys.path.insert(0, os.path.join(BASE_DIR, "Helpers")) Any idea? Answer: Python 3 has changed the import policy. Take a look at [this question](http://stackoverflow.com/questions/12172791/changes-in-import- statement-python3). Instead of adding `Helpers` directory to `sys.path`, add it's parent: sys.path.insert(0, os.path.join(BASE_DIR, 'myproject')) Or like @albar mentioned - use relative import: from .Helpers import views
Main axis are not shown when using grid Question: I want to plot two graphs into the same figure with two different y-axis. In addition to it, I would like to add a grid and then save the plot as pdf. **My problem** is that - while the grid is drawn correctly - the main axis are not shown anymore. How can they be plotted as well? I am using `matplotlib 1.5.1` and `Python 2.7.11`. Here is the plot: [![enter image description here](http://i.stack.imgur.com/nwlYx.png)](http://i.stack.imgur.com/nwlYx.png) And here is the code I am using: import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages('myplot.pdf') x = np.linspace(0.1, 10, 100) y1 = np.exp(x) y2 = np.log(x) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y1, '-ro', markersize=5, label='y1') ax1.set_ylim(-0.1, 1.1 * max(y1)) ax1.set_ylabel('y1', fontsize=20) ax1.legend(loc='upper left') ax1.grid(ls='dotted', c='k') ax1.patch.set_facecolor('white') ax2 = ax1.twinx() ax2.grid(False) ax2.plot(x, y2, 'b-', label='y2') ax2.set_ylim(-0.1, 1.1 * max(y2)) ax2.set_ylabel('y2', fontsize=20) ax2.legend(loc='upper right') plt.xlim([-0.5, 1.05 * max(x)]) ax1.set_xlabel('x', fontsize=20) pp.savefig(fig) pp.close() plt.close(fig) Answer: It works for me with the plot correctly showing the axis like on the png added here under. Same output for the following: * `Python 3.4.4, iPython, Jupyter notebook, matplotlib 1.5.1` * `Python 2.7.11, iPython, Jupyter notebook, matplotlib 1.5.?` [![enter image description here](http://i.stack.imgur.com/GIGac.png)](http://i.stack.imgur.com/GIGac.png) The code used is this one - same as the one posted except for the plt.show() that I added to produce the png image. import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages('myplot.pdf') x = np.linspace(0, 10, 100) y1 = np.exp(x) y2 = np.log(x) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y1, '-ro', markersize=5, label='y1') ax1.set_ylim(-0.1, 1.1 * max(y1)) ax1.set_ylabel('y1', fontsize=20) ax1.legend(loc='upper left') ax1.grid(ls='dotted', c='k') ax1.patch.set_facecolor('white') ax2 = ax1.twinx() ax2.grid(False) ax2.plot(x, y2, 'b-', label='y2') ax2.set_ylim(-0.1, 1.1 * max(y2)) ax2.set_ylabel('y2', fontsize=20) ax2.legend(loc='upper right') plt.xlim([-0.5, 1.05 * max(x)]) ax1.set_xlabel('x', fontsize=20) #plt.show() pp.savefig(fig) pp.close() plt.close(fig) If you are using an ipython kernel, there might be some residual settings from previous work interfering with the rendering? Have you tried with a fresh kernel?
Changing pixel color value in PIL Question: I need to change pixel color of an image in python. Except for the pixel value (255, 0, 0) red I need to change every pixel color value into black (0, 0, 0). I tried the following code but it doesn't helped. from PIL import Image im = Image.open('A:\ex1.jpg') for pixel in im.getdata(): if pixel == (255,0,0): print "Red coloured pixel" else: pixel = [0, 0, 0] Answer: See this wikibook: <https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels> Modifying that code to fit your problem: pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): if pixels[i,j] == (255, 0, 0): pixels[i,j] = (0, 0 ,0)
Most efficient (and pythonic) way to count False values in 2D numpy arrays? Question: I am trying to count `False` value in an `np.array` like this: import numpy as np a = np.array([[True,True,True],[True,True,True],[True,False,False]]) I usually use this method: number_of_false=np.size(a)-np.sum(a) Is there a better way? Answer: Use [`count_nonzero`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.count_nonzero.html#numpy- count-nonzero) to count non-zero (e.g. not `False`) values: >>> np.size(a) - np.count_nonzero(a) 2
aws depoylment issue while restarting nginx Question: I am using favfile(<https://ashokfernandez.wordpress.com/2014/03/11/deploying- a-django-app-to-amazon-aws-with-nginx-gunicorn-git/comment- page-1/#comment-100>) to deploy a django app. But stuck somewhere.Please help, a link has been provided for fabfile. Restarting nginx [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] sudo: /etc/init.d/nginx restart [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: Restarting nginx: nginx. [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] sudo: source /home/ubuntu/.virtualenvs/bhuv/bin/activate && python /home/ubuntu/webapps/bhuv/manage.py collectstatic -v 0 --noinput [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: Traceback (most recent call last): [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/home/ubuntu/webapps/bhuv/manage.py", line 11, in <module> [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: execute_from_command_line(sys.argv) [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/home/ubuntu/.virtualenvs/bhuv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: utility.execute() [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/home/ubuntu/.virtualenvs/bhuv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: settings.INSTALLED_APPS [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/home/ubuntu/.virtualenvs/bhuv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: self._setup(name) [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/home/ubuntu/.virtualenvs/bhuv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: self._wrapped = Settings(settings_module) [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/home/ubuntu/.virtualenvs/bhuv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: mod = importlib.import_module(self.SETTINGS_MODULE) [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: __import__(name) [ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com] out: ImportError: No module named prod Fatal error: sudo() received nonzero return code 1 while executing! Requested: source /home/ubuntu/.virtualenvs/bhuv/bin/activate && python /home/ubuntu/webapps/bhuv/manage.py collectstatic -v 0 --noinput Executed: sudo -S -p 'sudo password:' -u "ubuntu" /bin/bash -l -c "cd /home/ubuntu/webapps && source /home/ubuntu/.virtualenvs/bhuv/bin/activate && python /home/ubuntu/webapps/bhuv/manage.py collectstatic -v 0 --noinput" Aborting. Disconnecting from ec2-52-62-197-135.ap-southeast-2.compute.amazonaws.com... done. Answer: Did you follow the steps correctly in [Deploying a Django App to Amazon AWS (with Nginx + Gunicorn + Git)](https://ashokfernandez.wordpress.com/2014/03/11/deploying-a-django-app- to-amazon-aws-with-nginx-gunicorn-git/)? The file `settings/prod.py` is missing. Go read the section `Setting up Our Django Project`. Did you run `sudo pip requirements.txt`? prod.py for your server Django settings
Python: How to generate a random phone number? Question: Not a duplicate of [Making random phone number xxx-xxx- xxxx](http://stackoverflow.com/questions/26226801/making-random-phone-number- xxx-xxx-xxxx) My project uses [python-phonenumbers](https://github.com/daviddrysdale/python- phonenumbers) and [django-phonenumber- field](https://github.com/stefanfoulis/django-phonenumber-field) for phone number validation. Within the project are vast lists of custom validation rules, for which naive approach like this will not be sufficient: >>> import functools >>> import random >>> a = functools.partial(random.randint, 0, 9) >>> gen = lambda: "+{}-{}{}{}-{}{}{}-{}{}{}{}".format(a(), a(), a(), a(), a(), a(), a(), a(), a(), a(), a()) >>> gen() '+2-758-702-0180' # Obviously wrong >>> gen() '+1-911-555-0180' # Obviously wrong, it has 911 in it So, without resorting to a brute-force while loop that has no upper bound, and without introducing an upper bound for such trivial problems, what better ways are there to generate valid phone numbers accepted by the validator itself? from phonenumber_field.validators import validate_international_phonenumber from django.core.exceptions import ValidationError def generate_valid_number(): while True: # While loops are not desired, even with an upper bound! try: number = gen() validate_international_phonenumber(number) return number except ValidationError: pass Answer: I think the answer that davidn gave to [this question](http://stackoverflow.com/questions/16135069/python-validation- mobile-number) should work especially since you're already using python- phonenumbers > I would recommend to use the phonenumbers package which is a python port of > Google's libphonenumber which includes a data set of mobile carriers now: > > > import phonenumbers > from phonenumbers import carrier from > phonenumbers.phonenumberutil import number_type > > number = "+49 176 1234 5678" > carrier._is_mobile(number_type(phonenumbers.parse(number))) > > > This will return True in case number is a mobile number or False otherwise. > Note that the number must be a valid international number or an exception > will be thrown. You can also use phonenumbers to parse phonenumber given a > region hint.
Python argparse check choices before type Question: I'm trying to enable a user to pass in a function name. For some reason it seems that argparse performs the type check/conversion BEFORE it checks the choices. Is this a bug? Best thing to do? import argparse def foo(): return 'foo' def bar(): return 'bar' parser = argparse.ArgumentParser() functions = {f.__name__:f for f in [foo, bar]} parser.add_argument("function", type=lambda f: functions.get(f), help="which function", choices=functions) args = parser.parse_args() print(args.function()) This throws: $ python blah.py foo usage: blah.py [-h] {foo,bar} blah.py: error: argument function: invalid choice: <function foo at 0x7f65746dd848> (choose from 'foo', 'bar') Answer: Yes, during parsing the `type` then `choices` order is clear and intentional (and not just incidental). When preparing to assign `arg_strings` to the `namespace` it calls `_get_values`, which does: def _get_values(self, action, arg_strings) .... (various nargs tests) value = self._get_value(action, arg_string) self._check_value(action, value) return value where `_get_value` applies the `action.type` function, and `_check_value` tests value not in action.choices For parsing `choices` only has to respond to the `in` (`__contains__`) expression. So `choices` have to reflect values after conversion. If `type` is `int`, then `choices=[1,2,3]` is correct, `['1','2','3']` is not. There are some (largely unresolved) bug issues over the display of the choices. Long lists, e.g. `range(100)` work in parsing, but don't display nicely. And display also requires that `choices` be iterable (e.g. a list, tuple, dictionary). This display issue affects the usage, the help and the error messages (each formats `choices` slightly differently). `metavar` is your most powerful tool for replacing an undesirable `choices` list. I'd have to run a test case to see whether it solves things for all 3 situations.
Issues converting larger HTML files to docx in pypandoc (pandoc) Question: My question is related to [How to increase heap memory in pandoc execution?](http://stackoverflow.com/questions/30704736/how-to-increase-heap- memory-in-pandoc-execution), but adds a Python-specific component. Background: I'm trying to generate scientific reports automatically. I've written data to an HTML file, and I'd like to use Pandoc.exe (a file conversion program) to convert to a .docx Word Document. I've got the process to work for a smaller HTML file with an image, table, ect. That file was 307KB. The problem starts when I try to convert a larger file (~4.5MB) with multiple graphs embedded. I've been using `pypandoc` to convert, like this: import pypandoc PANDOC_PATH = r"C:\Program Files\RStudio\bin\pandoc" infile = savepath + os.sep + 'Results ' + name + '.html' outfile = savepath + os.sep + 'Results ' + name + '.docx' output = pypandoc.convert(source=infile, format='html', to='docx', \ outputfile=outfile, extra_args=["+RTS", "-K64m", "-RTS"]) But I get a variety of errors. Usually: RuntimeError: Pandoc died with exitcode "2" during conversion: b"Stack space overflow: current size 33692 bytes.\nUse `+RTS -Ksize -RTS' to increase it.\n" or if I crank the value of -Ksize up to 256m, something like this: RuntimeError: Pandoc died with exitcode "1" during conversion: b'pandoc: out of memory\r\n' * * * **Can someone explain what is happening, here, and some way I can get around this difficulty?** One solution I've thought about is making my images a lot smaller. I've just been scaling down the (80 - 500KB) originals like this, where the width and the height of each image is dependent on it's original dimensions: data_uri = base64.b64encode(open(formats[graph][0], 'rb').read()).decode('utf-8') img_tag = ('<img src="data:image/jpg;base64,{0}" height='+formats[graph][2][0]+' width='+formats[graph][2][1]+'>').format(data_uri) Thanks for your help Answer: Thanks very much to help from [user2407038](http://stackoverflow.com/users/2407038/user2407038) on this one! Two fixes finally allowed me to convert my larger HTML file to a docx file with `pypandoc`: The first, as suggested, was > increasing the maximum size of the heap, e.g. add -M2GB to extra_args That is: `output = pypandoc.convert(source=infile, format='html', to='docx', outputfile=outfile, extra_args=["-M2GB", "+RTS", "-K64m", "-RTS"])` * * * After increasing the heap size, I still had a second problem, so I wasn't sure if the solution worked. Python returned an error message like this: > RuntimeError: Pandoc died with exitcode "1" during conversion: b"pandoc: > Cannot decode byte '\x91': Data.Text.Internal.Encoding.Fusion.streamUtf8: > Invalid UTF-8 stream\n" Which was fixed by changing how the html file was opened in the first place. Setting the `encoding` keyword argument to `'utf8'` allows for the conversion to work: report = open(savepath + os.sep + 'Results ' + name + '.html', 'w', encoding='utf8')
Python child logger should report back to root logger instead of applying its own logging configs Question: As mentioned here <http://stackoverflow.com/a/4150322/1526342>. When logging to child logger, it will pass on the message to its parent, and its parent will pass the message to the root logger. Now considering the following example import logging import logging.handlers child_logger = logging.getLogger(__name__) f = logging.Formatter( fmt='%(asctime)s; %(name)s; % (filename)s:%(lineno)d:%(message)s', datefmt="%Y-%m-%d %H:%M:%S") handler = logging.handlers.RotatingFileHandler('/tmp/info.log', encoding='utf8', maxBytes=500000000, backupCount=5) handler.setFormatter(f) child_logger.setLevel(logging.INFO) child_logger.addHandler(handler) child_logger.info('1 + 1 is %d', 1+1) `child_logger` should have reported back to the root logger instead of printing the output to the child_logger's log file. I'm confused. Answer: As shown in [this logging flow chart](https://docs.python.org/3/howto/logging.html#logging-flow), loggers pass log records both to own handlers _and_ to parent logger objects. Try adding a handler to the parent logger, you'll see the log record is being processed there as well.
Jupyter error: "No module named jupyter_core.paths" Question: Trying to open Jupyter Notebook (OSX 10.11.4) I get the following error: $ jupyter-notebook Traceback (most recent call last): File "/usr/local/bin/jupyter-notebook", line 7, in <module> from notebook.notebookapp import main File "/Users/geotheory/Library/Python/2.7/lib/python/site-packages/notebook/__init__.py", line 25, in <module> from .nbextensions import install_nbextension File "/Users/geotheory/Library/Python/2.7/lib/python/site-packages/notebook/nbextensions.py", line 23, in <module> from jupyter_core.paths import jupyter_data_dir, jupyter_path, SYSTEM_JUPYTER_PATH ImportError: No module named jupyter_core.paths This used to work. Any idea how to diagnose? Answer: I have encountered similar issue. Basically, I solved it by uninstall python2.7 and re-install newer python & IPython versions. Details on how to effectively uninstall python2.7 via Mac OS command line is here: [How to uninstall Python 2.7 on a Mac OS X 10.6.4?](http://stackoverflow.com/questions/3819449/how-to-uninstall- python-2-7-on-a-mac-os-x-10-6-4) Re-install desired version of IPython via command line. In my case, I also needed to re-install Jupyter via: pip install jupyter Good luck.
out of memory panic while accessing a function from a shared library Question: I'm trying to build a sample shared object library using Go. The code compiles (using the command `go build -o libsample.so -buildmode=c-shared .`), a shared object library is built successfully - but while accessing the exported method via JNA(from Java) or ctypes (from python), I am getting a panic. The code I wrote in Go is: // package name: libsample.so package main import "C" import "fmt" //export Hello func Hello(s string) { fmt.Println("Hello " + s + "!") } func main() { } While accessing this method `Hello` from Java: import com.sun.jna.*; public class sample { public interface GoSO extends Library { GoSO INSTANCE = (GoSO) Native.loadLibrary("sample" ,GoSO.class); void Hello(String s); } public static void main(String[] args) { GoSO.INSTANCE.Hello("World"); } } or from Python: #!/usr/bin/python import ctypes lib = ctypes.CDLL("./libsample.so") lib.Hello("World") I get the following error: runtime: out of memory: cannot allocate 140042998120448-byte block (1048576 in use) fatal error: out of memory runtime stack: runtime.throw(0x7f5e434bfe50, 0xd) /usr/local/go/src/runtime/panic.go:530 +0x92 runtime.largeAlloc(0x7f5e4d27dc8d, 0xc800000003, 0xc82003cf08) /usr/local/go/src/runtime/malloc.go:768 +0xdf runtime.mallocgc.func3() /usr/local/go/src/runtime/malloc.go:664 +0x35 runtime.systemstack(0x7f5e4e4d3ab8) /usr/local/go/src/runtime/asm_amd64.s:291 +0x72 runtime.mstart() /usr/local/go/src/runtime/proc.go:1048 goroutine 17 [running, locked to thread]: runtime.systemstack_switch() /usr/local/go/src/runtime/asm_amd64.s:245 fp=0xc82003cb50 sp=0xc82003cb48 runtime.mallocgc(0x7f5e4d27dc8d, 0x0, 0x3, 0x0) /usr/local/go/src/runtime/malloc.go:665 +0x9fe fp=0xc82003cc28 sp=0xc82003cb50 runtime.rawstring(0x7f5e4d27dc8d, 0x0, 0x0, 0x0, 0x0, 0x0) /usr/local/go/src/runtime/string.go:284 +0x72 fp=0xc82003cc70 sp=0xc82003cc28 runtime.rawstringtmp(0x0, 0x7f5e4d27dc8d, 0x0, 0x0, 0x0, 0x0, 0x0) /usr/local/go/src/runtime/string.go:111 +0xb9 fp=0xc82003cca8 sp=0xc82003cc70 runtime.concatstrings(0x0, 0xc82003ce38, 0x3, 0x3, 0x0, 0x0) /usr/local/go/src/runtime/string.go:49 +0x1bf fp=0xc82003cde0 sp=0xc82003cca8 runtime.concatstring3(0x0, 0x7f5e434ba9d0, 0x6, 0x7f5e48155490, 0x7f5e4d27dc86, 0x7f5e434ba560, 0x1, 0x0, 0x0) /usr/local/go/src/runtime/string.go:63 +0x6c fp=0xc82003ce30 sp=0xc82003cde0 main.Hello(0x7f5e48155490, 0x7f5e4d27dc86) /home/vagrant/go/src/github.com/venkatramachandran/lib-sample/sample.go:9 +0x72 fp=0xc82003cec8 sp=0xc82003ce30 main._cgoexpwrap_9f7405a93e67_Hello(0x7f5e48155490, 0x7f5e4d27dc86) github.com/venkatramachandran/lib-sample/_obj/_cgo_gotypes.go:48 +0x2d fp=0xc82003cee0 sp=0xc82003cec8 runtime.call32(0x0, 0x7f5e4e4d3ae8, 0x7f5e4e4d3b70, 0x10) /usr/local/go/src/runtime/asm_amd64.s:472 +0x40 fp=0xc82003cf08 sp=0xc82003cee0 runtime.cgocallbackg1() /usr/local/go/src/runtime/cgocall.go:267 +0x110 fp=0xc82003cf40 sp=0xc82003cf08 runtime.cgocallbackg() /usr/local/go/src/runtime/cgocall.go:180 +0xd9 fp=0xc82003cfa0 sp=0xc82003cf40 runtime.cgocallback_gofunc(0x0, 0x0, 0x0) /usr/local/go/src/runtime/asm_amd64.s:716 +0x5d fp=0xc82003cfb0 sp=0xc82003cfa0 runtime.goexit() /usr/local/go/src/runtime/asm_amd64.s:1998 +0x1 fp=0xc82003cfb8 sp=0xc82003cfb0 goroutine 18 [syscall, locked to thread]: runtime.goexit() /usr/local/go/src/runtime/asm_amd64.s:1998 +0x1 Aborted (core dumped) What is going wrong? If I create method with an `int` or a `float` as a parameter, this error does not occur. Answer: **Reason:** The reason behind this is that your go function `Hello` expects a `golang` String, but python and Java passed `C style` string. **Solution:** Since you have compiled your golang library using `buildmode=c-shared`. Python `ctypes` package and java JNI views it as a plain c method. And passes a c style string which is really just an array of characters terminated by `NULL`. But in your code, function `Hello` expects a golang string, which has different format than typical c style string. Hence this error. It can be solved by declaring `s` as `*C.char`. Corrected program is as follows: // package name: libsample.so package main import "C" import "fmt" //export Hello func Hello(s *C.char) { fmt.Println("Hello " + C.GoString(s) + "!") } func main() { }
Python os.walk and symlinks Question: While fixing one user's [answer on AskUbuntu](http://askubuntu.com/a/754931/295286) , I've discovered a small issue. The code itself is straightforward : os.walk , recursively get sum of all files in the directory. But it breaks on symlinks : $ python test_code2.py $HOME Traceback (most recent call last): File "test_code2.py", line 8, in <module> space += os.stat(os.path.join(subdir, f)).st_size OSError: [Errno 2] No such file or directory: '/home/xieerqi/.kde/socket-eagle' Question then is, how do I tell python to ignore those files and avoid summing them ? **Solution** : As suggested in the comments , I've added `os.path.isfile()` check and now it works perfectly and gives correct size for my home directory $> cat test_code2.py #! /usr/bin/python import os import sys space = 0L # L means "long" - not necessary in Python 3 for subdir, dirs, files in os.walk(sys.argv[1]): for f in files: file_path = os.path.join(subdir, f) if os.path.isfile(file_path): space += os.stat(file_path).st_size sys.stdout.write("Total: {:d}\n".format(space)) $> python test_code2.py $HOME Total: 76763501905 Answer: As already mentioned by Antti Haapala in a comment, The script does not break on symlinks, but on _broken symlinks_. One way to avoid that, taking the existing script as a starting point, is using `try/except`: #! /usr/bin/python2 import os import sys space = 0L # L means "long" - not necessary in Python 3 for root, dirs, files in os.walk(sys.argv[1]): for f in files: fpath = os.path.join(root, f) try: space += os.stat(fpath).st_size except OSError: print("could not read "+fpath) sys.stdout.write("Total: {:d}\n".format(space)) As a side effect, it gives you information on possible broken links.
Python MySql query silently failing Question: I've got a MySql database (running using the stock Docker image) and it contains a table defined like this: CREATE TABLE `Edits` ( `id` int(11) NOT NULL AUTO_INCREMENT, `context` varchar(255) NOT NULL, `field` varchar(255) NOT NULL, `value` text, `username` varchar(255) DEFAULT NULL, `requested` datetime DEFAULT NULL, PRIMARY KEY (`id`,`context`,`field`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1 I'm connecting to it in a WSGI application, and my connection code looks like this: import contextlib import MySQLdb mysql = MySQLdb.connect(host = 'host', db = 'db') def _cursor(): mysql.ping(True) return contextlib.closing(mysql.cursor()) def _exec(sql, params = None): with _cursor() as c: c.execute(sql, params) def save_edits(id, context, field, value, username): return _exec('REPLACE INTO Edits SET id = %(id)s, context = %(context)s, field = %(field)s, value = %(value)s, username = %(username)s, requested = UTC_TIMESTAMP()', { 'id': id, 'context': context, 'field': field, 'value': value, 'username': username, }) When I call the `save_edits` function, it doesn't throw an exception, but it fails to update the database. Furthermore, attempting to run the query `REPLACE INTO Edits SET id = 1, context = 'x', field = 'y', value = 'z', username = 'foo', requested = UTC_TIMESTAMP();` through a `mysql` shell afterwards fails with an `ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction` error. If I wait about 5 minutes, however, that error goes away and I can run the `REPLACE INTO` query against the MySql database again. What's going on? How can I fix this error? Answer: It turns out that `autocommit` is `false` by default, and closing the cursor without closing the connection will keep the transaction open. I changed the method to: def _exec(sql, params = None): with _cursor() as c: c.execute(sql, params) mysql.commit() And that fixed the problem.
wrap boost::optional using boost::python Question: Is there a way to wrap `boost::optional<T>` type object to expose it via `boost::python::class_` (used from `BOOST_PYTHON_MODULE`) struct Foo { boost::optional<int> bar; }; BOOST_PYTHON_MODULE(module_name) { class_<Foo>("Foo") .def_readwrite("bar", &Foo::bar); } What I expect in Python is AttributeError in this case import module_name f = module_name.Foo() print f.bar as the value of `bar` hasn't been set yet. And `TypeError` when import module_name f = module_name.Foo() f.bar = "string" `bar` is of `int` type. The other related problem is to export, in the same fashion, classes' objects of `boost::python::indexing_suite` container types. Is the problem solvable using `boost::python` api? Answer: You need an [exception translator](http://www.boost.org/doc/libs/1_48_0/libs/python/doc/v2/exception_translator.html) and [python converters](https://misspent.wordpress.com/2009/09/27/how-to- write-boost-python-converters/). **Exception translator** namespace bp = boost::python; // Custom exceptions struct AttributeError: std::exception { const char* what() const throw() { return "AttributeError exception"; } }; struct TypeError: std::exception { const char* what() const throw() { return "TypeError exception"; } }; // Set python exceptions void translate(const std::exception& e) { if(dynamic_cast<const AttributeError*>(&e)) PyErr_SetString(PyExc_AttributeError, e.what()); if(dynamic_cast<const TypeError*>(&e)) PyErr_SetString(PyExc_TypeError, e.what()); } BOOST_PYTHON_MODULE(module_name) { // Exception translator bp::register_exception_translator<AttributeError>(&translate); bp::register_exception_translator<TypeError>(&translate); ... } **To-python converter** template <typename T> struct to_python_optional { static PyObject* convert(const boost::optional<T>& obj) { if(obj) return bp::incref(bp::object(*obj).ptr()); // raise AttributeError if any value hasn't been set yet else throw AttributeError(); } }; BOOST_PYTHON_MODULE(module_name) { ... bp::to_python_converter<boost::optional<int>, to_python_optional<int> >(); ... } **From-python converter** template<typename T> struct from_python_optional { static void* convertible(PyObject *obj_ptr) { try { return typename bp::extract<T>::extract(obj_ptr) ? obj_ptr : 0 ; } // Without try catch it still raises a TypeError exception // But this enables to custom your error message catch(...) { throw TypeError(); } } static void construct( PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { const T value = typename bp::extract<T>::extract(obj_ptr); assert(value); void* storage = ( (bp::converter::rvalue_from_python_storage<boost::optional<T> >*) data)->storage.bytes; new (storage) boost::optional<T>(value); data->convertible = storage; } from_python_optional() { bp::converter::registry::push_back( &convertible, &construct, bp::type_id<boost::optional<T> >()); } }; BOOST_PYTHON_MODULE(module_name) { ... from_python_optional<int>(); ... } Moreover you can't use converters with `def_readwrite` [(see this FAQ)](http://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/faq.html#topythonconversionfailed), you have to use `add_property`. BOOST_PYTHON_MODULE(module_name) { ... bp::class_<Foo>("Foo") .add_property("bar", bp::make_getter(&Foo::bar, bp::return_value_policy<bp::return_by_value>()), bp::make_setter(&Foo::bar, bp::return_value_policy<bp::return_by_value>())); } Thus you'll get those outputs in your Python interpreter : >>> import module_name >>> f = module_name.Foo() >>> print f.bar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: AttributeError exception >>> f.bar="string" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: TypeError exception
Please point out my mistake in the following program Question: Here m trying to extract a list of blacklist IP from a specific site and trying to make an excel sheet of the following fields : IP , date ...... New updated code is : import xlwt import urllib def Bl(): link = 'https://www.dshield.org/ipsascii.html?limit=100' p = urllib.urlopen(link) text = p.readlines() wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') sheet.write(0,0,'Blacklist IP') sheet.write(0,1,'Reports') sheet.write(0,2,'abcd') sheet.write(0,3,'date') sheet.write(0,4,'Date') row = 1 #counter for rows. col = 0 #counter for columns. x = 0 #counter for printing the n'th element in the string w. for line in text: li = line.strip() w = line.split() if not li.startswith("#"): sheet.write(row,col,w[0]) sheet.write(row,1,w[1]) sheet.write(row,2,w[2]) sheet.write(row,3,w[3]) sheet.write(row,4,w[4]) row = row + 1 wbk.save('new.xls') Bl() Answer: I believe it should be this, though my python isn't great: import xlwt import urllib link = 'https://www.dshield.org/ipsascii.html?limit=100' p = urllib.urlopen(link) text = p.readlines() wbk = xlwt.Workbook() sheet = wbk.add_sheet('Blacklist IP') row = 1 #counter for rows. col = 0 #counter for columns. #x = 0 #counter for printing the n'th element in the string w. for line in text: li = line.strip() w = line.split() print "The line " + line + " was split into " + len(w) + " size" for i in range(0,len(w)-1): if not li.startswith("#") and not li.isspace(): sheet.write(row,col,w[i]) #x = x + 1 col = col + 1 if col > 256: print "Line of " + li print "Row: " + row print "Col: " + col raise ValueError('Too many columns, can\'t insert ' + w) row = row + 1 wbk.save('new.xls') Reasoning is that I believe you should be changing column every time you write a value, since that appears to be causing your current error. I also believe You should be changing row after each line, not just at the end of the code which then appears superfluous [Edit update after user feedback]
How to stream images to the browser with Django Question: Forgive me if I am using these terms incorrectly, I'm pretty new to the concept of streaming and I haven't found many resources in Googling that talked about the best use cases for streaming. What I have right now: Browser makes a requests for an image to a Django endpoint var img = new Image(); img.src = 'http://www.example.com/api/images/51234/ img.onload = function() { $('#my-img').attr('src', this.src); } Django turns around makes another request to a service for an image import requests def get_image(request, img_id): response = requests.get("http://api.myexample.net/album/123/img/{0}".format(img_id)) return HttpResponse(res.content, mimetype="image/jpeg") My understanding of this process is that Django will read all of the binary information for this image into memory before turning around to deliver the response to the browser. Is there a way I can stream it directly down to the browser rather than waiting for the image to be delivered completely to Python? I have read the documentation for the [StreamingHTTPResponse](https://docs.djangoproject.com/en/1.9/ref/request- response/#django.http.StreamingHttpResponse) class but all the examples show simply reading a file off of the server's disk and passing it to a StreamingHTTPResponse, not getting it from another service. Answer: You dont have to get download image content using `requests.get`. Lets say: def viewFunc(request): image_url = 'some.image.url.jpg' you can pass the url to your html file simply via context. return render(request, 'some_html.html', {'image_url':image_url}) Then in html use like : <img src="{{image_url}}" id="image_id"> Or if you are using ajax: return HttpResponse(json.dumps({'image_url':image_url})) Then in html: success : function(response){ var image_url = response.image_url; $('#image_id').attr('src',image_url); } This way django will only pass the url to image view and the image will render from frontend. There is no need to download image using requests.get since all the browsers are capable of generating image from image tag.
CUDA-Python: How to launch CUDA kernel in Python (Numba 0.25)? Question: could you please help me understand how to write CUDA kernels in Python? AFAIK, **numba.vectorize** can be performed on _cuda, cpu, parallel(multi- cpus)_ , based on **target**. But _target='cuda'_ requires to set up CUDA kernels. The main issue is that many examples, answers in Internet are related to **deprecated** NumbaPro library, so it's hard to follow to such as **not- updated** [WIKIs](http://numba.pydata.org/numba-doc/0.13/CUDAJit.html), especially if you're newbie. I have: * latest Anaconda (v2) * latest Numba (v0.25) * latest CUDA toolkit (v7) Here is the error I'm getting: > numba.cuda.cudadrv.driver.CudaAPIError: [1](http://numba.pydata.org/numba- > doc/0.13/CUDAJit.html) Call to cuLaunchKernel results in CU > DA_ERROR_INVALID_VALUE import numpy as np import time from numba import vectorize, cuda @vectorize(['float32(float32, float32)'], target='cuda') def VectorAdd(a, b): return a + b def main(): N = 32000000 A = np.ones(N, dtype=np.float32) B = np.ones(N, dtype=np.float32) start = time.time() C = VectorAdd(A, B) vector_add_time = time.time() - start print "C[:5] = " + str(C[:5]) print "C[-5:] = " + str(C[-5:]) print "VectorAdd took for % seconds" % vector_add_time if __name__ == '__main__': main() Answer: The code, as posted, is correct and will run on a Python 2 Numbapro/Accelerate system without error. It was likely that the particular system being used to run the code wasn't very large in capacity and was hitting a display driver watchdog or free memory error with 32 million element vectors. Reducing the size of the input data allowed the code to run correctly. [This answer assembled from comments and added as a community wiki entry to get this question off the unanswered list]
Python: copy and paste files based on paths in two csvs Question: I have two csv files, one with a list of paths for source files, the second, a list of paths for where to copy the files to. Both files have the same number of elements and each source file is only copied once. How would I load the .csv files (Pandas? Numpy? csv.reader?), and how would I copy all of the items in the best possible way? I am able to get the following to work if `src` and `dest` each refer to one path. import pandas as pd srcdf = pd.read_csv('src.csv') destdf = pd.read_csv('dest.csv') from shutil import copyfile copyfile(src,dest) There are no headers or columns in my files. It's just a vector of comma- separated values. The comma-separated values in my `src` csv file are look like: /Users/johndoe/Downloads/50.jpg, /Users/johndoe/Downloads/51.jpg, In my `dest` csv file are like: /Users/johndoe/Downloads/newFolder/50.jpg, /Users/johndoe/Downloads/newFolder/51.jpg, Answer: Assuming your CSV is just a list of paths with a single path on each row, you could do something like this: import csv from shutil import copyfile def load_paths(filename): pathdict = {} with open(filename) as csvfile: filereader = csv.reader(csvfile, delimiter=' ') a = 0 for row in filereader: pathdict[a] = ''.join(row) a += 1 csvfile.close() return pathdict srcpaths = load_paths('srcfile.csv') dstpaths = load_paths('dstfile.csv') for a in range(len(srcpaths)): copyfile(srcpaths[a],dstpaths[a])
Cannot add comment to SQL db in python Flask app Question: I am new to programming and have setup a small website with a comments section on pythonanywhere.com, relaying heavily on their tutorial. But when I post a comment in the form, the comment is not added to the database and for some reason the program redirects me to the index page (the intention is to redirect to stay on the same page) Any suggestions as to what I might be doing wrong would be greatly appreciated! The pyhthon code: import random from flask import Flask, request, session, redirect, url_for, render_template, flash from flask.ext.sqlalchemy import SQLAlchemy from werkzeug.routing import RequestRedirect app = Flask(__name__) app.config["DEBUG"] = True SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format( username="username", password="password", hostname="hostname", databasename="majaokholm$majaokholm", ) app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI app.config["SQLALCHEMY_POOL_RECYCLE"] = 299 db = SQLAlchemy(app) class Comment(db.Model): __tablename__ = "comments" id = db.Column(db.Integer, primary_key=True) content = db.Column(db.String(4096)) @app.route("/") def index(): return render_template("index_page.html") @app.route('/post', methods=["GET", "POST"]) def post(): if request.method == "GET": return render_template("post_page.html", comments=Comment.query.all()) comment = Comment(content=request.form["contents"]) db.session.add(comment) db.session.commit() return redirect(url_for('post')) and the form from the HTML template: <form action="." method="POST"> <textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea> <input type="submit" value="Post comment"> </form> Thanks a lot in advance! Answer: Currently, the `action="."` in the form actually points to the root of the current directory, which for `/post` happens to be just `/` and thus points to the `index`. It's always better to use `action="{{ url_for('your_target_view') }}"` instead.
Django rest framework extended user profile Question: I recently discovered DRF and I'm lost with the quantity of views, viewsets and other possibilities. I have a Python3/Django 1.8 application with an extended user profile: from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class Profile(models.Model): GENDER = ( ('male', _('MALE')), ('female', _('FEMALE')), ) user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(default='', max_length=500, null=True, blank=True) gender = models.CharField(max_length=10, choices=GENDER, null=True, blank=True) city = models.CharField(default='', max_length=30, null=True, blank=True) country = models.CharField(default='', max_length=30, null=True, blank=True) I would like to allow external mobile applications connected with oauth2/token Bearer to **get the current connected user's profile** through the api and **editing it** using those routes: GET or PUT /api/profile GET or PUT /api/user My first intention was using only one route for manipulate both models (through /api/profile) but I failed and I'm not sure if it's a good practice to mix two models behind one route. I tried lot of things. My last attempt was to get the profile like this: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'password', 'email', 'groups') password = serializers.CharField(write_only=True) class UserViewSet(viewsets.ModelViewSet): @list_route(methods=['get', 'post'], permission_classes=[permissions.IsAuthenticated]) def profile(self, request): u = User.objects.filter(pk=request.user.pk)[0] p = Profile.objects.filter(user=u)[0] return Response({"id": u.id, "first_name": u.first_name, "last_name": u.last_name, "email": u.email, "city": p.city, "country": p.country, "bio": p.bio}) permission_classes = [permissions.IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) Problem is: I'm failed trying to implement the same thing for PUT requests. Furthermore I would like to do the security and defensive coding part on the API side and in this situation I don't even using the serializers. Could you guys help me to find the right thing to do? Do you have any tips, suggestions? Cheers Answer: I think this is what you want: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('bio', 'gender', 'city', 'country') class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('url', 'username', 'password', 'email', 'groups', 'profile') Or if you want it flat: class UserSerializer(serializers.ModelSerializer): bio = serializers.CharField(source='profile.bio') gender = serializers.CharField(source='profile.gender') #same for the others class Meta: model = User fields = ('url', 'username', 'password', 'email', 'groups', 'bio', 'gender') I didn't test it, but should be close to what you want, or close to it at least.
How to set picture display location in ipython/jupyter notebook cell? Question: I try to plot multiple pictures in the ipython cell for comparison. Here is what I have got from the below nodes [![enter image description here](http://i.stack.imgur.com/NsX7d.png)](http://i.stack.imgur.com/NsX7d.png) import numpy as np from matplotlib import pylab x = np.linspace(1.0,13.0,10) y = np.sin(x) pylab.plot(x,y) show() x = np.linspace(1.0,13.0,20) y = np.sin(x) pylab.plot(x,y) show() x = np.linspace(1.0,13.0,30) y = np.sin(x) pylab.plot(x,y) show() How can I plot these pictures as the following direction? Answer: The short answer is that at this moment you can't... unless you make one figure of 3 subplots. **Like this maybe:** import numpy as np import matplotlib.pyplot as plt %matplotlib inline f, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(20,5)) x = np.linspace(1.0,13.0,10) y = np.sin(x) ax1.plot(x,y) x = np.linspace(1.0,13.0,20) y = np.sin(x) ax2.plot(x,y) x = np.linspace(1.0,13.0,30) y = np.sin(x) ax3.plot(x,y) plt.show() [![enter image description here](http://i.stack.imgur.com/e53hf.png)](http://i.stack.imgur.com/e53hf.png)
IndexError: list assignment index out of range in python 2.7.11 Question: I was just solving a problem using python, and my codes are: from math import sin,pi import numpy import numpy as np import pylab N=20 x = np.linspace(0,1, N) def v(x): return 100*sin(pi*x) #set up initial condition u0 = [0.0] # Boundary conditions at t= 0 for i in range(1,N): u0[i] = v(x[i]) And I would want to plot the results by updating v(x) in `range(0, N)` after. it looks simple but perhaps you guys could help since it gives me an error, like Traceback (most recent call last): File "/home/universe/Desktop/Python/sample.py", line 13, in <module> u0[i] = v(x[i]) IndexError: list assignment index out of range Answer: You could change `u0[i] = v(x[i])` to `u0.append(v(x[i]))`. But you should write more elegantly as u0 = [v(xi) for xi in x] Indices `i` are bug magnets.
Continue the script if an element is not found using selenium in Python Question: I am having a trouble trying to figure out how to continue the script if an element is not found using selenium in Python. This code cycles through reports, finds the refresh button and then clicks on the download the button. The only problem is, that some reports do not have a refresh button. So, I would like the script to continue if the button is not found. I am still new to python/selenium so that is why I am posting the entire code. I need to know what to slip in to make this work! Thanks in advance for the help with this head banging problem This is where selenium will try to click the refresh button browser.find_element_by_css_selector("#ctl00_PlaceHolderMain_ReportViewer1_HtmlOutputReportResults2_updateFilters_TitleAnchor").click() The complete code: import time import os import os.path import glob import shutil from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import MoveTargetOutOfBoundsException from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException files = glob.glob('/Users/me/Desktop/AUTOREPORTS/*') for f in files: os.remove(f) open('/Users/me/Desktop/AUTOREPORTS/report.csv', "w") for x in range(1, 73): while True: try: fp = webdriver.FirefoxProfile('C:/Users/me/Documents/FirefoxProfile') browser = webdriver.Firefox(fp) browser.get('https://websitething.com/') time.sleep(8) browser.find_element_by_id("ctl00_PlaceHolderMain_login_UserName").clear() browser.find_element_by_id("ctl00_PlaceHolderMain_login_UserName").send_keys("usr") browser.find_element_by_id("ctl00_PlaceHolderMain_login_password").clear() browser.find_element_by_id("ctl00_PlaceHolderMain_login_password").send_keys("paswd") browser.find_element_by_id("ctl00_PlaceHolderMain_login_login").click() #gets user to reporting front end ReportMgr= browser.find_element_by_partial_link_text('Report Manager') ReportMgr.click() time.sleep(5) CustomReport= browser.find_element_by_partial_link_text('Custom Report') CustomReport.click() time.sleep(5) ProgramManagement= browser.find_element_by_partial_link_text('Program Management') ProgramManagement.click() ProgramManagement= browser.find_element_by_partial_link_text('Program Management').send_keys(Keys.ARROW_LEFT) #pulls reports browser.find_element_by_partial_link_text('Program Management').click() time.sleep(60) browser.find_element_by_partial_link_text('Program Management').send_keys(Keys.ARROW_DOWN * x, Keys.ENTER) time.sleep(60) browser.find_element_by_css_selector("#ctl00_PlaceHolderMain_ReportViewer1_HtmlOutputReportResults2_updateFilters_TitleAnchor").click() time.sleep(60) browser.find_element_by_css_selector("#ctl00_PlaceHolderMain_ReportViewer1_HtmlOutputReportResults2_CSVButton_ImageAnchor > img").click() fname = "Report(%s).csv" % (x) os.chdir('/Users/me/Desktop/AUTOREPORTS') time.sleep(60) #browser.find_element_by_partial_link_text('Program Management').click() #time.sleep(30) browser.quit() except: browser.quit() continue else: break Answer: Use a [`try` / `except` block to handle the exception](https://docs.python.org/2/tutorial/errors.html#handling-exceptions) and continue. try: browser.find_element_by_css_selector("#ctl00_PlaceHolderMain_ReportViewer1_HtmlOutputReportResults2_updateFilters_TitleAnchor").click() except NoSuchElementException: # do stuff Note that Florent B.'s answer will find multiple elements on the page instead of one. So depending on what you need to find, and how many of them there are, it may cause minor performance issues. If you actually need to find multiple elements, his solution will work just fine, but for OP's question best practices dictate that we use the method designed to handle the task at hand instead of the method designed to handle multiples of the same task. It's like greedy matching vs lazy matching with regex. If you only need the first match, write a lazy pattern and it will be more efficient, even if writing the greedy pattern still works out technically.
Python/Tkinter: why does the .get method of IntVar shows same value when clicking different radiobuttons? Question: ## Brief overview of the program: 1. When launching script, the dialog window is appearing and asking you to select directory path (class `MyApp`) 2. When selected - one needs to push the "Start Monitoring" button. This action withdraws the main window (`root`) and initializes the container class `FrameContainer` consisting of two frames, namely `PageOne` and `PageTwo` (see corresponding classes). 3. Button `Back Home` on `Page One` should destroy the instance of the class `FrameContainer` and show the dialog window again. This action is achieved using methods `update()` and `deiconify()`. 4. Selection of any of the radio buttons on `Page One` should change the value of variable `rb_indx` \- it is achieved using the `get()` method of `IntVar`. * * * ## Problems: * Radio buttons are initialized in wrong way. The `var.set(1)` should highlight the 'var1' button, however in my case are highlighted `var2` and `var3`. * The `get()` method of `IntVar` does not update the value of the variable `rb_indx` when selecting a radio button. `print rb_indx` always gives 1 * When closing `PageOne` window by the [x] (in corner of the screen), the dialog window is not appearing, however is expected... * * * ## The code: # -*- coding: utf-8 -*- try: # Python2 import Tkinter as Tk from Tkinter import IntVar from tkFileDialog import askdirectory except ImportError: # Python3 import tkinter as Tk from tkinter import IntVar from tkinter.filedialog import askdirectory LARGE_FONT=("Verdana", 12) ######################################################################## class FrameContainer(Tk.Tk): def __init__(self, parent): self.original_frame = parent Tk.Tk.__init__ (self) container = Tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight =1) self.frames = {} for F in (PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(PageOne) def show_frame (self, cont): frame=self.frames[cont] frame.tkraise() def onClose(self): self.destroy() self.original_frame.show() class PageOne(Tk.Frame): def __init__(self, parent, controller): Tk.Frame.__init__(self, parent) label = Tk.Label(self, text="Page One", font=LARGE_FONT) label.pack(pady=10, padx=10) button1=Tk.Button(self, text="Back to Home", command=lambda: controller.onClose()) button1.pack() button2=Tk.Button(self, text="Page Two", command=lambda: controller.show_frame(PageTwo)) button2.pack() def get_button_indx(): global rb_indx rb_indx=var.get() print rb_indx var.set(1) names_tuple = ('var1', 'var2', 'var3') for col_numb in range (1,len(names_tuple)+1): radio = Tk.Radiobutton(self, text=names_tuple[col_numb-1], variable=var, value=col_numb, command=get_button_indx) radio.pack() class PageTwo(Tk.Frame): def __init__(self, parent, controller): Tk.Frame.__init__(self, parent) label = Tk.Label(self, text="Page Two", font=LARGE_FONT) label.pack(pady=10, padx=10) button1=Tk.Button(self, text="Back to Home", command=lambda: controller.onClose()) button1.pack() button2=Tk.Button(self, text="Page One", command=lambda: controller.show_frame(PageOne)) button2.pack() class MyApp(object): def __init__(self, parent): self.root = parent self.root.title("Start page") self.frame = Tk.Frame(parent) self.frame.pack() def choosedir(): global path_usr_var path_usr_var = askdirectory() print path_usr_var button1 = Tk.Button(self.frame, text="Select Directory", command=choosedir) button1.pack(pady=10, padx=10) button2 = Tk.Button(self.frame, text="Start Monitoring", command=self.openFrame) button2.pack(pady=10, padx=10) def hide(self): self.root.withdraw() def openFrame(self): self.hide() firstFrame = FrameContainer(self) def show(self): self.root.update() self.root.deiconify() ######################################################################## if __name__ == "__main__": root = Tk.Tk() root.geometry("800x600") var = IntVar() app = MyApp(root) root.mainloop() Answer: The problem is that you're creating more than one instance of `Tk`. An app must have exactly one instance of `Tk`.What is happening is that `var` belongs to the first instance, but you are associating it with radio buttons that belong to the second instance. If you need multiple windows, create a single root window and then create instances of `Toplevel` for all additional windows.
Module not being set up properly Question: New-ish to python, but I though I had everything set up right. When I run `python -m unittest test.unit.test_oyez_case`, I get `AttributeError: 'module' object has no attribute 'test_oyez_case'` Sorry this is a frequent question, none of the responses were helpful to me Here's my file structure: ├── README.md └── test ├── __init__.py ├── __init__.pyc ├── integration │   └── __init__.py └── unit ├── __init__.py ├── __init__.pyc ├── mocks │   ├── __init__.py │   ├── __init__.pyc │   ├── responses.py │   └── responses.pyc ├── test_oyez_case.py └── test_oyez_case.pyc Here's `test/unit/test_oyez_case.py`: import json import unittest import responses from mocks import responses as api_responses from puppy_scotus.oyez_case import OyezCase class TestOyezCase(unittest.TestCase): . . . if __name__ == '__main__': unittest.main() Answer: Try to run it using a commandline like `python test_oyez_case.py`. It could be that one of your other imports is incorrect. ;-)
Loading, querying SQL Compact (SQLCE) 4.0 database files through Python Question: I am trying to load table from a compact sql database (.sdf file format) into Python (3.5.1). Here is what I have been playing around with: import adodbapi file="C:\\TS\\20160406_sdfPyt\\HC.sdf" connstr = 'Provider=Microsoft.SQLSERVER.CE.OLEDB.4.0;Data Source=%s;' %file conn = adodbapi.connect(connstr) This throws up error messages Traceback (most recent call last): File "C:\Users\TS\AppData\Local\Programs\Python\Python35\lib\site-packages\adodbapi\adodbapi.py", line 112, in connect co.connect(kwargs) File "C:\Users\TS\AppData\Local\Programs\Python\Python35\lib\site-packages\adodbapi\adodbapi.py", line 274, in connect self.connector.Open() # Open the ADO connection File "<COMObject ADODB.Connection>", line 3, in Open File "C:\Users\TS\AppData\Local\Programs\Python\Python35\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Service Components', 'Format of the initialization string does not conform to the OLE DB specification.', None, 0, -2147217805), None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#32>", line 1, in <module> conn = adodbapi.connect(connstr) File "C:\Users\TS\AppData\Local\Programs\Python\Python35\lib\site-packages\adodbapi\adodbapi.py", line 116, in connect raise api.OperationalError(e, message) adodbapi.apibase.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Service Components', 'Format of the initialization string does not conform to the OLE DB specification.', None, 0, -2147217805), None), 'Error opening connection to "Provider=Microsoft.SQLSERVER.CE.OLEDB.4.0;Data Source==C:\\TSrinivas\\20160406_sdfPyt\\HC.sdf;"') I tried including SSCE:Max Database Size=3999;Persist Security Info=True; etc. in the connection string after searching online but with no luck. Could someone help me with the right connection string, or if I am doing anything else wrong here? Edit: changed '==' to '=' in connstr Answer: I reinstalled SQLCE 3.5 (firxt x86 and then x64) from <https://www.microsoft.com/en-us/download/details.aspx?id=5783> and changed the connection string to connstr = """Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\TSrinivas\\20160406_sdfPyt\\HazardCache.sdf;""" This works on a 4.0 database! I had tried this earlier but it had not worked, but somehow the re-installation did the job. I used adodbapi.
Python: How to get the next day of unix timestamps at 00:00 and 23:59? Question: I have a matrix like this in my code with unix timestamps: event_sequences = [ [1368136883, 1368137089], #The first event is never empty [1368214777, 1368214966], [], .... There are the perfect number of days (empty arrays) in the gaps between the existing events. [], [1368747495, 1368747833], [1368830501, 1368831869] ] for each event in event_sequences I know its start and its end (start = `event_sequences[n][0]` and end = `event_sequences[n][1]`). As you can see there are some events that are empty and the approach I have to take is to set the start and the end of these empty events as 00:00 and 23:59 of the day after the last event recorded. Like [ [start, end], [start, end], [the day after the last event at 00:00, the day after the last event at 23:59] ] The start and end of the empty events also need to be unix timestamps. How can I do that in python? Answer: The following should do the trick. A few questions/things to be aware of though: * This will fail if the first element in `event_sequences` is an empty list * Should there be gaps in days in `event_sequences`? For example, you'll see in the output below that there's a gap in your sequence between 5/12/2013 and 5/16/2013, even after the blank entries are filled. * In the case here where you have two consecutive blank entries, I assumed you wanted the second blank entry to be the day after the first blank entry Code: from datetime import datetime, timedelta import time event_sequences = [ [1368136883, 1368137089], [1368214777, 1368214966], [], [], [1368747495, 1368747833], [1368830501, 1368831869] ] #take the last_day recorded date as a datetime object from the event_sequences and return a 2-element list #with the unix timestamps for 00:00 and 23:59 def getNextDay(last_day): next_day = last_day + timedelta(days=1) next_day_start = next_day.replace(hour=0,minute=0,second=0) next_day_end = next_day.replace(hour=23,minute=59,second=0) return [int(next_day_start.strftime("%s")), int(next_day_end.strftime("%s"))] def fillEmptyDates(event_list): new_event_list = [] #note: this will fail if the first element in the list of event_sequences is blank last_day = int(time.time()) for x in event_sequences: if len(x) == 0: next_day = getNextDay(last_day) last_day = datetime.utcfromtimestamp(next_day[1]) else: next_day = x last_day = datetime.utcfromtimestamp(next_day[1]) new_event_list.append(next_day) return new_event_list new_event_sequence = fillEmptyDates(event_sequences) print new_event_sequence #[[1368136883, 1368137089], [1368214777, 1368214966], [1368230400, 1368316740], [1368316800, 1368403140], [1368747495, 1368747833], [1368830501, 1368831869]] for event in new_event_sequence: print str(datetime.utcfromtimestamp(event[0]))+ ' and '+str(datetime.utcfromtimestamp(event[1])) #2013-05-09 22:01:23 and 2013-05-09 22:04:49 #2013-05-10 19:39:37 and 2013-05-10 19:42:46 #2013-05-11 00:00:00 and 2013-05-11 23:59:00 #2013-05-12 00:00:00 and 2013-05-12 23:59:00 #2013-05-16 23:38:15 and 2013-05-16 23:43:53 #2013-05-17 22:41:41 and 2013-05-17 23:04:29
python script for enquiring the version of multiple operating systems Question: I am new to python, looking to write a script which would ssh to about 1000 hosts from a jump server and Output should contain the hostname and version of the operating system. Redhat 5.0 or 6,0 etc and I have list of all the hosts and so the script can keep getting hostname from the hosts list. Is it possible using paramiko and platform modules ??.. I would really appreciate if someone could give a rough frame for getting me started. or similar script. Answer: The `socket` and `platform` can do this. import socket import platform print socket.gethostname() print platform.platform()
Python CGI script doesn't run Question: I'm trying to run a simple python cgi script on apache webserver. But the output when I try access (<http://localhost/cgi-bin/environment_key.py>), it's just the python code... the file doesn't run. I tried other solutions that I found in the stackoverflow to fix this, but it doesn't work yet. I changed the httpd.conf, but nothing. This is my python file: #!/usr/bin/env python import os print "Content-type: text/html\r\n\r\n" print "<font size=+1>Environment</font><\br>"; for param in os.environ.keys(): print "<b>%20s</b>: %s<\br>" % (param, os.environ[param]) And my httpd.conf. # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/access_log" # with ServerRoot set to "/usr/local/apache2" will be interpreted by the # server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log" # will be interpreted as '/logs/access_log'. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile. # ServerRoot "/usr" # # Mutex: Allows you to set the mutex mechanism and mutex file directory # for individual mutexes, or change the global defaults # # Uncomment and change the directory if mutexes are file-based and the default # mutex file directory is not on a local disk or is not appropriate for some # other reason. # # Mutex default:/private/var/run # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # #Listen 12.34.56.78:80 Listen 80 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule authn_file_module libexec/apache2/mod_authn_file.so #LoadModule authn_dbm_module libexec/apache2/mod_authn_dbm.so #LoadModule authn_anon_module libexec/apache2/mod_authn_anon.so #LoadModule authn_dbd_module libexec/apache2/mod_authn_dbd.so #LoadModule authn_socache_module libexec/apache2/mod_authn_socache.so LoadModule authn_core_module libexec/apache2/mod_authn_core.so LoadModule authz_host_module libexec/apache2/mod_authz_host.so LoadModule authz_groupfile_module libexec/apache2/mod_authz_groupfile.so LoadModule authz_user_module libexec/apache2/mod_authz_user.so #LoadModule authz_dbm_module libexec/apache2/mod_authz_dbm.so #LoadModule authz_owner_module libexec/apache2/mod_authz_owner.so #LoadModule authz_dbd_module libexec/apache2/mod_authz_dbd.so LoadModule authz_core_module libexec/apache2/mod_authz_core.so #LoadModule authnz_ldap_module libexec/apache2/mod_authnz_ldap.so LoadModule access_compat_module libexec/apache2/mod_access_compat.so LoadModule auth_basic_module libexec/apache2/mod_auth_basic.so #LoadModule auth_form_module libexec/apache2/mod_auth_form.so #LoadModule auth_digest_module libexec/apache2/mod_auth_digest.so #LoadModule allowmethods_module libexec/apache2/mod_allowmethods.so #LoadModule file_cache_module libexec/apache2/mod_file_cache.so #LoadModule cache_module libexec/apache2/mod_cache.so #LoadModule cache_disk_module libexec/apache2/mod_cache_disk.so #LoadModule cache_socache_module libexec/apache2/mod_cache_socache.so #LoadModule socache_shmcb_module libexec/apache2/mod_socache_shmcb.so #LoadModule socache_dbm_module libexec/apache2/mod_socache_dbm.so #LoadModule socache_memcache_module libexec/apache2/mod_socache_memcache.so #LoadModule watchdog_module libexec/apache2/mod_watchdog.so #LoadModule macro_module libexec/apache2/mod_macro.so #LoadModule dbd_module libexec/apache2/mod_dbd.so #LoadModule dumpio_module libexec/apache2/mod_dumpio.so #LoadModule echo_module libexec/apache2/mod_echo.so #LoadModule buffer_module libexec/apache2/mod_buffer.so #LoadModule data_module libexec/apache2/mod_data.so #LoadModule ratelimit_module libexec/apache2/mod_ratelimit.so LoadModule reqtimeout_module libexec/apache2/mod_reqtimeout.so #LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so #LoadModule request_module libexec/apache2/mod_request.so #LoadModule include_module libexec/apache2/mod_include.so LoadModule filter_module libexec/apache2/mod_filter.so #LoadModule reflector_module libexec/apache2/mod_reflector.so #LoadModule substitute_module libexec/apache2/mod_substitute.so #LoadModule sed_module libexec/apache2/mod_sed.so #LoadModule charset_lite_module libexec/apache2/mod_charset_lite.so #LoadModule deflate_module libexec/apache2/mod_deflate.so #LoadModule xml2enc_module libexec/apache2/mod_xml2enc.so #LoadModule proxy_html_module libexec/apache2/mod_proxy_html.so LoadModule mime_module libexec/apache2/mod_mime.so #LoadModule ldap_module libexec/apache2/mod_ldap.so LoadModule log_config_module libexec/apache2/mod_log_config.so #LoadModule log_debug_module libexec/apache2/mod_log_debug.so #LoadModule log_forensic_module libexec/apache2/mod_log_forensic.so #LoadModule logio_module libexec/apache2/mod_logio.so LoadModule env_module libexec/apache2/mod_env.so #LoadModule mime_magic_module libexec/apache2/mod_mime_magic.so #LoadModule expires_module libexec/apache2/mod_expires.so LoadModule headers_module libexec/apache2/mod_headers.so #LoadModule usertrack_module libexec/apache2/mod_usertrack.so ##LoadModule unique_id_module libexec/apache2/mod_unique_id.so LoadModule setenvif_module libexec/apache2/mod_setenvif.so LoadModule version_module libexec/apache2/mod_version.so #LoadModule remoteip_module libexec/apache2/mod_remoteip.so LoadModule proxy_module libexec/apache2/mod_proxy.so LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so LoadModule proxy_ftp_module libexec/apache2/mod_proxy_ftp.so LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so LoadModule proxy_fcgi_module libexec/apache2/mod_proxy_fcgi.so LoadModule proxy_scgi_module libexec/apache2/mod_proxy_scgi.so #LoadModule proxy_fdpass_module libexec/apache2/mod_proxy_fdpass.so LoadModule proxy_wstunnel_module libexec/apache2/mod_proxy_wstunnel.so LoadModule proxy_ajp_module libexec/apache2/mod_proxy_ajp.so LoadModule proxy_balancer_module libexec/apache2/mod_proxy_balancer.so LoadModule proxy_express_module libexec/apache2/mod_proxy_express.so #LoadModule session_module libexec/apache2/mod_session.so #LoadModule session_cookie_module libexec/apache2/mod_session_cookie.so #LoadModule session_dbd_module libexec/apache2/mod_session_dbd.so LoadModule slotmem_shm_module libexec/apache2/mod_slotmem_shm.so #LoadModule slotmem_plain_module libexec/apache2/mod_slotmem_plain.so #LoadModule ssl_module libexec/apache2/mod_ssl.so #LoadModule dialup_module libexec/apache2/mod_dialup.so LoadModule lbmethod_byrequests_module libexec/apache2/mod_lbmethod_byrequests.so LoadModule lbmethod_bytraffic_module libexec/apache2/mod_lbmethod_bytraffic.so LoadModule lbmethod_bybusyness_module libexec/apache2/mod_lbmethod_bybusyness.so #LoadModule lbmethod_heartbeat_module libexec/apache2/mod_lbmethod_heartbeat.so LoadModule unixd_module libexec/apache2/mod_unixd.so #LoadModule heartbeat_module libexec/apache2/mod_heartbeat.so #LoadModule heartmonitor_module libexec/apache2/mod_heartmonitor.so #LoadModule dav_module libexec/apache2/mod_dav.so LoadModule status_module libexec/apache2/mod_status.so LoadModule autoindex_module libexec/apache2/mod_autoindex.so #LoadModule asis_module libexec/apache2/mod_asis.so #LoadModule info_module libexec/apache2/mod_info.so #LoadModule cgi_module libexec/apache2/mod_cgi.so #LoadModule dav_fs_module libexec/apache2/mod_dav_fs.so #LoadModule dav_lock_module libexec/apache2/mod_dav_lock.so #LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so LoadModule negotiation_module libexec/apache2/mod_negotiation.so LoadModule dir_module libexec/apache2/mod_dir.so #LoadModule imagemap_module libexec/apache2/mod_imagemap.so #LoadModule actions_module libexec/apache2/mod_actions.so #LoadModule speling_module libexec/apache2/mod_speling.so #LoadModule userdir_module libexec/apache2/mod_userdir.so LoadModule alias_module libexec/apache2/mod_alias.so #LoadModule rewrite_module libexec/apache2/mod_rewrite.so LoadModule php5_module libexec/apache2/libphp5.so LoadModule hfs_apple_module libexec/apache2/mod_hfs_apple.so <IfModule unixd_module> # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # It is usually good practice to create a dedicated user and group for # running httpd, as with most system services. # User _www Group _www </IfModule> # 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # <VirtualHost> definition. These values also provide defaults for # any <VirtualHost> containers you may define later in the file. # # All of these directives may appear inside <VirtualHost> containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. [email protected] # ServerAdmin [email protected] # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # #ServerName www.example.com:80 # # Deny access to the entirety of your server's filesystem. You must # explicitly permit access to web content directories in other # <Directory> blocks below. # <Directory /> Options +FollowSymLinks +ExecCGI AddHandler cgi-script .cgi .pl AllowOverride None Require all granted </Directory> # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/Library/WebServer/Documents" <Directory "/Library/WebServer/Documents"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks MultiViews ExecCGI # MultiviewsMatch Any # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # AllowOverride FileInfo AuthConfig Limit # AddHandler cgi-script .cgi .pl AllowOverride All Allow from all Order allow,deny # # Controls who can get stuff from this server. # # Require all granted </Directory> # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # <IfModule dir_module> DirectoryIndex index.html index.cgi </IfModule> # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <FilesMatch "^\.([Hh][Tt]|[Dd][Ss]_[Ss])"> Require all denied </FilesMatch> # # Apple specific filesystem protection. # <Files "rsrc"> Require all denied </Files> <DirectoryMatch ".*\.\.namedfork"> Require all denied </DirectoryMatch> # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog "/private/var/log/apache2/error_log" # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn <IfModule log_config_module> # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a <VirtualHost> # container, they will be logged here. Contrariwise, if you *do* # define per-<VirtualHost> access logfiles, transactions will be # logged therein and *not* in this file. # CustomLog "/private/var/log/apache2/access_log" common # # If you prefer a logfile with access, agent, and referer information # (Combined Logfile Format) you can use the following directive. # #CustomLog "/private/var/log/apache2/access_log" combined </IfModule> <IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a <Directory> section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1" </IfModule> <IfModule cgid_module> # # ScriptSock: On threaded servers, designate the path to the UNIX # socket used to communicate with the CGI daemon of mod_cgid. # #Scriptsock cgisock </IfModule> # # "/Library/WebServer/CGI-Executables" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "/Library/WebServer/CGI-Executables"> AllowOverride All Options None Order allow,deny Allow from all AddHandler cgi-script .cgi .py Options +FollowSymLinks +ExecCGI Require all granted </Directory> <IfModule mime_module> # # TypesConfig points to the file containing the list of mappings from # filename extension to MIME-type. # TypesConfig /private/etc/apache2/mime.types # # AddType allows you to add to or override the MIME configuration # file specified in TypesConfig for specific file types. # #AddType application/x-gzip .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # AddHandler cgi-script .cgi .py # For type maps (negotiated resources): #AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # #MIMEMagicFile /private/etc/apache2/magic # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # MaxRanges: Maximum number of Ranges in a request before # returning the entire resource, or one of the special # values 'default', 'none' or 'unlimited'. # Default setting is to accept 200 Ranges. #MaxRanges unlimited # # EnableMMAP and EnableSendfile: On systems that support it, # memory-mapping or the sendfile syscall may be used to deliver # files. This usually improves server performance, but must # be turned off when serving from networked-mounted # filesystems or if support for these functions is otherwise # broken on your system. # Defaults: EnableMMAP On, EnableSendfile Off # #EnableMMAP off #EnableSendfile on TraceEnable off # Supplemental configuration # # The configuration files in the /private/etc/apache2/extra/ directory can be # included to add extra features or to modify the default configuration of # the server, or you may simply copy their contents here and change as # necessary. # Server-pool management (MPM specific) Include /private/etc/apache2/extra/httpd-mpm.conf # Multi-language error messages #Include /private/etc/apache2/extra/httpd-multilang-errordoc.conf # Fancy directory listings Include /private/etc/apache2/extra/httpd-autoindex.conf # Language settings #Include /private/etc/apache2/extra/httpd-languages.conf # User home directories #Include /private/etc/apache2/extra/httpd-userdir.conf # Real-time info on requests and configuration #Include /private/etc/apache2/extra/httpd-info.conf # Virtual hosts #Include /private/etc/apache2/extra/httpd-vhosts.conf # Local access to the Apache HTTP Server Manual #Include /private/etc/apache2/extra/httpd-manual.conf # Distributed authoring and versioning (WebDAV) #Include /private/etc/apache2/extra/httpd-dav.conf # Various default settings #Include /private/etc/apache2/extra/httpd-default.conf # Configure mod_proxy_html to understand HTML4/XHTML1 <IfModule proxy_html_module> Include /private/etc/apache2/extra/proxy-html.conf </IfModule> # Secure (SSL/TLS) connections #Include /private/etc/apache2/extra/httpd-ssl.conf # # Note: The following must must be present to support # starting without SSL on platforms with no /dev/random equivalent # but a statically compiled-in mod_ssl. # <IfModule ssl_module> SSLRandomSeed startup builtin SSLRandomSeed connect builtin </IfModule> Include /private/etc/apache2/other/*.conf # # uncomment out the below to deal with user agents that deliberately # violate open standards by misusing DNT (DNT *must* be a specific # end-user choice) # #<IfModule setenvif_module> #BrowserMatch "MSIE 10.0;" bad_DNT #</IfModule> #<IfModule headers_module> #RequestHeader unset DNT env=bad_DNT #</IfModule> Thanks. Answer: For running python script with httpd in theory You need to check that this is exist: in httpd.conf : Include conf.modules.d/*.conf LoadModule wsgi_module modules/mod_wsgi.so IncludeOptional conf.d/*.conf # -------------------- End of file Then You can try to create youvirtualhost.conf in /etc/httpd/conf.d/ And add something like this: <VirtualHost www.youdomainname.com or *:80> ServerAdmin [email protected] ServerName www.youdomainname.com ServerAlias www.youdomainname.com WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup %{GLOBAL} Alias /wsgi-scripts/ /web/wsgi-scripts/ <Location /wsgi-scripts> SetHandler wsgi-script Options +ExecCGI </Location> <Directory /You/directory/Path> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /You/directory/Path/wsgi.py </VirtualHost> Or add this and something from youvirtualhost.conf to end of Your httpd.conf : WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup %{GLOBAL} Alias /wsgi-scripts/ /web/wsgi-scripts/ <Location /wsgi-scripts> SetHandler wsgi-script Options +ExecCGI </Location> Also You can visit <http://serverfault.com/q/281487> and <https://modwsgi.readthedocs.org/en/develop/>
how to extract python data frame from JSON string Question: I've got the following JSON string in a txt file and I'm trying to extract a data frame from the 'visualLogs' variable. I can read the JSON string in and I can access the visualLogs list, but I have failed all day long to convert this into a 9 column data frame of floating point numbers { "visualScore" : 0, "selfReportingResults" : 5, "voiceScore" : "No Data", "selfReportScore" : 0, "subject" : "Baseline for patient: 108", "email" : "[email protected]", "visualLogs" : [ "time,anger,contempt,disgust,engagement,joy,sadness,surprise,valence\r22.61086,0.00633,0.19347,0.56258,0.18005,0.00223,0.0165,0.31969,0.0\r22.81096,0.00478,0.19439,0.45847,0.09747,0.00188,0.02188,0.22043,0.0\r" ], "askedQuestions" : [ "What is your name?", "How old are you?", "What tim is it?" ], "voiceCompleteResults" : { "status" : "fail" } } with open(f4lJasonFileName) as data_file: feelDat = json.load(data_file) x = feelDat['visualLogs'][0] # Ultimately there will be more than one of these All of my attempts to convert x to a data frame have failed. I've achieved getting a 1 column data frame of text values, but that's not what I need. I've replaced those '\r' characters with commas, which ends up getting the one column text data frame, but I want 9 columns with the labels and then rows of floating points. Answer: Once you have loaded the json, you need to split on \r then on the commas: import pandas as pd spl = d["visualLogs"][0].split("\r") df = pd.DataFrame([v for v in map(lambda x: x.split(","), spl[1:]) if v[0]], columns=spl[0].split(",")) Probably easier to understand broken into parts: import pandas as pd # split into lines creating an iterator so we don't have to slice. spl = iter(d["visualLogs"][0].rstrip().split("\r")) # split first line to get the column names. columns = next(spl).split(",") # split remaining lines into individual rows, removing empty row. rows = [v for v in (sub_str.split(",") for sub_str in spl) if len(v) > 1] df = pd.DataFrame(data=rows, columns=columns) We could also just `spl = iter(d["visualLogs"][0].split())` as there is no other whitespace. Or use _read_csv_ using a _StringIO_ object: import pandas as pd spl = d["visualLogs"][0] from io import StringIO df = pd.read_csv(StringIO(spl)) Which gives you: time anger contempt disgust engagement joy sadness \ 0 22.61086 0.00633 0.19347 0.56258 0.18005 0.00223 0.01650 1 22.81096 0.00478 0.19439 0.45847 0.09747 0.00188 0.02188 surprise valence 0 0.31969 0 1 0.22043 0
Python, How to organize a big function that relies on many external data to work Question: Question: How to organize a big function that relies on many external data to work. should I declare a class and contain those external data? or should I keep the big function and its data in one file? Or there are better ways of doing it?what's the most computationally efficient way? what's the most pythonic, recommended way? I have a log file to parse, and the log file contains many formats of strings. I wrote a parseLine(inputStr) function to deal with all possible formats. The parseLine() function requires many precompiled regexes, and a quite big dictionary for lookups. I kept the parseLine() function in a file parseLineFile.py My parseLineFile.py looks like: regex0 = re.compile('foo') regex1 = re.compile('bar') # and many more regexes set0 = {'f', '0'} set1 = {'b', 'a'} # could be a big set contains 10s of strings # and many more sets def parseLine(inputString, inputDictionary, inputTimeCriteria): # pseduo code: # use regex0 to extract date info in inputString # check if date within inputTimeCriteria # use more of previous declared regexes and sets to extract more info, # branch out to different routines to use more regexes and sets to extract more info # finally use inputDictionary to look up the meaning of extracted info # return results in some data structure In my Main code, I import parseLineFile.py build myDictionary, decide mytimeCriteria and then use parseLine() to parse a file line by line. I feel that my question is ... not stack-overflow-ic, but if you are to leave a comment of how I should ask a narrower/specific question, that's great! but please also at least mention how you would approach my problem. Answer: It's hard to specifically tell you what you should do for this specific function, but some tips in regards to organizing big functions: First, identify what conditionals can be moved to their own function. For example, let's say you have this code: if 'foo' in inputString: line = regex() line = do_something_else() elif 'bar' in inputString line = regex() line = do_something_a_little_different() You can easily see one abstraction you could do here, and that's to move the functionality in each `if` block to its own function, so you would create `parseFoo` and `parseBar` functions which take a line, and return an expected value. The main benefit of this is now you have extremely simple functions to unit test with! Other things I watch out for are: * Are you do many nesting of conditionals? Extract into a function and `return` early, to reduce nesting * If you're repeating yourself with different inputs, extract into a function * Mentally scan the function a day later and see if I still get it quite easily. If not, extract into smaller bits. Anyways, more input from you would be ideal but I hope that helps to get you started!
why will multiprocess spawn multi threads in every process? Question: I am using python [`multiprocessing`](https://docs.python.org/2/library/multiprocessing.html), here is a simple example: from multiprocessing import Pool import time import signal def process(_id): time.sleep(2) return _id def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) def main(): pool = Pool(1, init_worker) for res in pool.imap(process, range(1000)): print res if __name__ == "__main__": main() this runs ok, what confused me is that: # ps -eLaf | grep test_multi cuidehe 4119 4118 4119 2 4 11:06 pts/25 00:00:00 python test_multi.py cuidehe 4119 4118 4121 0 4 11:06 pts/25 00:00:00 python test_multi.py cuidehe 4119 4118 4122 0 4 11:06 pts/25 00:00:00 python test_multi.py cuidehe 4119 4118 4123 0 4 11:06 pts/25 00:00:00 python test_multi.py cuidehe 4120 4119 4120 0 1 11:06 pts/25 00:00:00 python test_multi.py aw you can see, I just forked one process, its pid is `4120`, so I think the pid `4119` is the main process, but **why 4 threads?** one thing to point out is that, **not always 4 threads** , for example: pool = Pool(1, init_worker) cursor = parse_db["jd_raw"].find({"isExpired": 0}, {"jdJob.jobPosition": 1, "jdJob.jobDesc": 1, "jdFrom": 1}, no_cursor_timeout=True).\ batch_size(15) for res in pool.imap(process, cursor): pass this time is 6 : cuidehe 4522 2655 4522 21 6 11:28 pts/25 00:00:00 python test_multi_mongo.py cuidehe 4522 2655 4525 0 6 11:28 pts/25 00:00:00 python test_multi_mongo.py cuidehe 4522 2655 4527 0 6 11:28 pts/25 00:00:00 python test_multi_mongo.py cuidehe 4522 2655 4528 54 6 11:28 pts/25 00:00:01 python test_multi_mongo.py cuidehe 4522 2655 4529 46 6 11:28 pts/25 00:00:00 python test_multi_mongo.py cuidehe 4522 2655 4530 0 6 11:28 pts/25 00:00:00 python test_multi_mongo.py cuidehe 4526 4522 4526 28 1 11:28 pts/25 00:00:00 python test_multi_mongo.py And also, not only `main process` will spawn child threads, **but also child process will spawn child threads** , so **why multiprocess still needs to spawn child threads?** Answer: The `multiprocessing` module uses three separate threads to manage a `Pool` in the background while your main program can continue. See `multiprocessing/pool.py` in your Python installation.
python garbage collection after start process using multiprocess Question: I test the gc behavior that python perform after start process using multiprocess: from multiprocessing import Process import time class A(object): def __del__(self): print 'deleting' def f(name): import gc gc.collect() print 'hello', name print [map(lambda s: str(s)[:64], gc.get_referrers(o)) for o in gc.get_objects() if isinstance(o, A)] time.sleep(123) def main(): a=A() p = Process(target=f, args=('bob',)) p.start() p.join() if __name__ == '__main__': try: main() except: print 'sdfsdf!' Output: hello bob [["[[], {'__setattr__': <slot wrapper '__setattr__' of 'object' obj", '<frame object at 0xb87570>', '<frame object at 0xbd7f80>']] I want to close file descriptor by executing `__del__`. When the subprocess starts, it enters the `f` function and the `A` instance `a` would no longer be reachable. But the `__del__` is not executed so that means the `a` object is still not freed. The output shows that it seems to be held by the frame object. So I tried another way using Exception to clean the stack to try to free the unreachable object and execute `__del__` function: from multiprocessing import Process import time import sys class GcHelp(Exception): def __init__(self, func): self.func = func super(GcHelp, self).__init__(func.__name__) class A(object): def __del__(self): print 'deleting' def f(): print 'target function' def raiser(): raise GcHelp(f) def main(): a=A() p = Process(target=raiser, args=()) p.start() p.join() if __name__ == '__main__': try: main() except GcHelp as e: sys.exc_clear() e.func() except: print 'sdfsdf!' Output: Process Process-1: Traceback (most recent call last): File "/usr/lib64/python2.7/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib64/python2.7/multiprocessing/process.py", line 114, in run self._target(*self._args, **self._kwargs) File "gc1.py", line 19, in raiser raise GcHelp(f) GcHelp: f It seems that the multiprocess have ready clean the stack and take over all exception handling.But parent frame does not exist any more. But why the frame is still there in the first code example? Obviously it still holding the `a` and the object is not freed at all. Is there some way to perform this kind of gc in python? Thanks a lot. Answer: Why would you want to close the file? Assuming this is a linuxy system, a forked environment is, well, forking weird. If you close the file in the child, it will flush any data still in the buffers... but that same data will be flushed again in the parent, resulting in duplicated data. import multiprocessing as mp fd = None def worker(): # child closes file, flushing "1" fd.close() def doit(): global fd fd = open('deleteme', 'w') fd.write('1') p = mp.Process(target=worker) p.start() p.join() # parent closes file, flushing "1" fd.close() # lets see what we got print(open('deleteme').read()) doit() This script prints `11` because the child and parent file objects both wrote `1`. It gets far crazier if either side calls `flush` or `seek`. _"it enters the f function and the A instance a would no longer be reachable."_ That's not true in general. First, the only reason that the child worker function exits the process when it returns is that the `multiprocessing` module called it from a function that ensures exit. In the general case, a forked function can return and execute its parent code. So, from python's perspective, that `a` is still reachable. Further, your worker could call a function that itself touches `a`. There is no way for python to know that. It would be incredibly expensive for python to clean up all "unreferencable" objects after a fork. And incredibly dangerous as those objects can change the system in many ways.
Python Matplotlib - saved images getting overwritten while using for loop Question: I am having one big list which has six small list's. These six small lists are used as the slice values while generating a pie chart using matplotlib. f_c = [[4, 1, 0, 1, 0], [4, 1, 0, 1, 0], [4, 1, 0, 1, 0], [4, 0, 2, 0, 0], [4, 0, 2, 0, 0], [4, 1, 0, 0, 1]] I have another one list which has the labels titles = ['Strongly Agree', 'Agree', 'Neutral', 'Disagree', 'Strongly Disagree'] Now, I am using a for loop to save the generated pie-charts. The code is as follows: for i, j in zip(f_c, lst): pie(i, labels=titles, shadow=True) savefig(j + '.png') 'lst' is a list that is having file names, and is used to save the the pie charts. I am able to generate the pie charts, but the charts and labels are getting overwritten. Only the first figure is coming correctly, rest of the figures are getting overwritten. When I did it manually all the figures were generating correctly, but if I put it in a loop it is not getting saved correctly (it's getting overwritten). The following are the generated images (only 3): ![Figure 1](https://s28.postimg.org/6jzgrv0wp/Q_1.png), ![Figure 2](https://s28.postimg.org/dbpvuppw9/Q_2.png), ![Figure 3](https://s28.postimg.org/capn5l8wp/Q_3.png) What might be the problem? Kindly help me with this. I am new to matplotlib. Answer: It's a good idea to clear the figure you're working with before trying to generate a new figure, just to be clear that you are starting from a blank slate. You clear with with `plt.clf()`, which stands for "clear figure". Not directly related to your question, but it's also a good idea in Python to not do `from matplotlib import *`, because it might overwrite other methods you have locally. Using meaningful variable names also help. Something like this will work: import matplotlib.pyplot as plt for fig, fig_name in zip(fig_data, fig_names): plt.clf() plt.pie(fig, labels=titles, shadow=True) plt.savefig(fig_name + '.png')
How to Multithread functions in Python? Question: I have made 2 functions in Python that have loop command. For making process faster, i wanted to multithread them. For example: def loop1(): while 1 < 2: print "something" def loop2(): while 5 > 4: print "something1" How can i run both of those, so it can loop something like this this: something something1 something something1 I have tried this: import threading from threading import Thread def loop1(): print "Something" def loop2(): print "Something1" if __name__ == '__main__': Thread(target = loop1).start() Thread(target = loop2).start() But it gave me HTML error and just started running loop1. Full Code: import mechanize import itertools import string import threading from threading import Thread br = mechanize.Browser() br.set_handle_equiv(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) response = br.open("http://arkhamnetwork.org/community/login/") br.addheaders = [("User-agent","Mozilla/5.0")] def loop1(): br.open("http://arkhamnetwork.org/community/login") start = 1 end = 2 for length in range(start, end+1): for c in itertools.combinations_with_replacement(string.ascii_letters + string.digits, length): br.select_form(nr=4) br.set_all_readonly(False) br.form['password'] = ''.join(c) print "test",br.form['password'] br.method = "POST" response = br.submit() if response.geturl()=="http://arkhamnetwork.org/community/": print "test ",''.join(x) break def loop2(): br.open("http://arkhamnetwork.org/community/login") start1 = 2 end1 = 3 for length in range(start1, end1+1): for c in itertools.combinations_with_replacement(string.ascii_letters + string.digits, length): br.select_form(nr=4) br.set_all_readonly(False) br.form['password'] = ''.join(c) print "test",br.form['password'] br.method = "POST" response = br.submit() if response.geturl()=="http://arkhamnetwork.org/community/": print "test",''.join(x) break if __name__ == '__main__': Thread(target = loop1).start() Thread(target = loop2).start() # NOTE: i'm not trying to attack anyone or any site with this, I'm just testing out code for educational purposes. The Error it gave me: [test] Trying a Exception in thread Thread-2: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) File "just.py", line 39, in loop2 br.select_form(nr=4) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 506, in select_form for form in self.forms(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 418, in forms if not self.viewing_html(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 443, in viewing_html raise BrowserStateError("not viewing any document") BrowserStateError: not viewing any document and it kept looping 1. Answer: # Found out solution: from multiprocessing import Process def loop1(): while 1 < 2: print "something" def loop2(): while 5 > 4: print "something1" if __name__=='__main__': p1 = Process(target = loop1) p1.start() p2 = Process(target = loop2) p2.start() This code will run multipe functions together. Not entirely sure why thread version didn't work, but i think it is converting function to thread, and is not made for multi-threading.
Tkinter - Sorting the checkboxes and printing if they're clicked Question: I'm learning Tkinter and have two questions. [1st one answered in the comment section] 1 - Why do the items in the dictionary are not printed in the correct order? If you delete the "grid" part from the Button, you may see that they are not ordered. 2 - Why the button is not shown? I want to make a button just below the checkboxes, which will print out "1" for each clicked checkboxes. [This link](http://stackoverflow.com/questions/8536518/how-do-i-create- multiple-checkboxes-from-a-list-in-a-for-loop-in-python-tkinter) was my reference. Below is my code: from Tkinter import * master = Tk() def read(): print dict[mini].get() dict = {"first": 0, "second": 0, "third": 0} for mini in dict: dict[mini] = Variable() l = Checkbutton(master, text=mini, variable=dict[mini]) l.grid(sticky=W, pady=4) l.pack() Button(master, text='Show', command=read).grid(row=len(dict) + 1, sticky=W, pady=4) master.mainloop() Edit: Spelling Answer: The button does not show because the program errors out at the `pack` statement. Remove the `pack()` and the button shows. You can not mix `grid` and `pack` in the same container. (from what Curly Joe said in the comments). The `Tkinter` variable declared in `my_dict` are not initialized nor assigned and therefore cannot be used; the dictionary of Variable()s is never changed. from Tkinter import * from collections import OrderedDict master = Tk() def read(): try: print my_dict[mini] except KeyError: pass my_dict = OrderedDict() my_dict["first"] = 0 my_dict["second"] = 0 my_dict["third"] = 0 for mini in my_dict.keys(): my_dict[mini] = Variable() chkbtn = Checkbutton(master, text=mini, variable=my_dict[mini]) chkbtn.grid(sticky=W, pady=4) Button(master, text='Show', command=read).grid(row=len(my_dict) + 1, sticky=W, pady=4) master.mainloop() Finally, do not use `i`, `l`, or `o` as single character variable names as it can be difficult to tell which is a letter and which is a number; also do not use the name of `builtins` for your `variables` or `method` names.
Capture cout from c++ by subprocess in my pythonscript Question: in my django python script i run my .cpp program. I want to capture my standard output (cout) in c++ by subprocess in python. In c++ I tried to make a stream which buffers all of my couts and return it in main(), but the only value I can return in main function is integer. So my question is: is there any other possibility to capture c++ couts by python to value in any other way? Thanks in advance! I tried using popen by: command = 'g++ -std=c++0x mutualcepepe.cpp -D "bomba = ' + str(strT) + '"' process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) output = process.communicate() print output Other possibility which I used before, was to invoke line below, which gives me output file containing couts from c++. os.system('g++ -std=c++0x mutualcepepe.cpp -D "bomba = ' + str(strT) + '" -o mutualout') Answer: In Python3, the simplest way to grab `stdout` from a subprocess is to use `subprocess.getoutput`: import subprocess output = subprocess.getoutput('ls ./my_folder') print(output) This method has been replaced in Python3.5 and the recommended way is now: result = subprocess.run(['ls', './my_folder'], stdout=subprocess.PIPE) print(result) print(result.stdout) You may want to turn the `stdout` to a string as well: result_string = result.stdout.decode('utf-8')
Overwriting/clearing previous console line Question: My problem is, that I want to be able to overwrite/clear previous printed line in python console. This question has been asked many times ([Python - Remove and Replace Printed items](http://stackoverflow.com/questions/5290994/python- remove-and-replace-printed-items) for example), however with the very same code that is (the answer marked as correct, for me prints out nothing at all): for i in range(10): print("Loading" + "." * i) time.sleep(1) sys.stdout.write("\033[F") # Cursor up one line sys.stdout.write("\033[K") # Clear to the end of line I get the output (In python IDLE) : Loading [F[KLoading. [F[KLoading.. [F[KLoading... [F[KLoading.... [F[KLoading..... [F[KLoading...... [F[KLoading....... [F[KLoading........ [F[KLoading......... [F[KLoading.......... [F[K Any ideas? I googled a lot, nothing works really. It either prints out nothing or just does not overwrite. If that helps, I am running windows 8.1 and Python 3.51. Running the code trough cmd doesn't affect anything. Also, adding `sys.stdout.flush()` does not help. Answer: You need to run your program form the command line, not from within IDLE. Then, this should work: import sys import time for i in range(10): sys.stdout.write("\r" + "Loading" + "." * i) time.sleep(1) sys.stdout.flush() print() The `\r` goes to beginning of the line. So you have to make sure the string you print is at least as long as the one before. Otherwise, you will see parts of the previous print.
Scikit-image: cannot import name 'label' Question: I have some scripts that use `skimage.measure.label`. On my old laptop (Debian 7, Python 2) these scripts worked perfectly. Recently, when I got a new laptop, I moved to Debian 8 and Python 3. Now these scripts cannot import `skimage.measure.label`: File "image_converter.py", line 8, in <module> from skimage.measure import label ImportError: cannot import name 'label' All of the other imports are working fine: from skimage import data from skimage.filter import threshold_otsu from skimage.segmentation import clear_border from skimage.morphology import closing, square from skimage.measure import regionprops from skimage.color import label2rgb import skimage.io as ski_io `pip3 list` says: (...) scikit-image (0.9.3) (...) Python version is 3.4.3. What has happened there? Has scikit-image (re-)moved `measure.label`? In the **official documentation** it is still listed: [skimage.measure.label](http://scikit- image.org/docs/dev/api/skimage.measure.html#skimage.measure.label) Answer: There is indeed no function `label` in module `measure` for release 0.9 (see <http://scikit-image.org/docs/0.9.x/api/skimage.measure.html>). Basically, you should update your version of `skimage`. The most recent version is 0.12.3. Python 3.4 is officially tested against, so you shouldn't expect any troubles with compatibility.
Python error 'int' object has no attribute 'shape' Question: Using the example below, `sklearn` with Python 3.5: from sklearn import tree features = [[140,1], [130,1], [150,0], [155,0]] labels = [0,0,1,1] clf = tree.DecisionTreeClassifier() clf.fit(features, labels) print(clf.predict(155,0)) I get the error following error. I don't understand why I received this error, could someone explain? Traceback (most recent call last): File "ml.py", line 7, in <module> print(clf.predict(155,0)) File "/Users/user/Documents/hello/env/lib/python3.5/site-packages/sklearn/tree/tree.py", line 404, in predict X = self._validate_X_predict(X, check_input) File "/Users/user/Documents/hello/env/lib/python3.5/site-packages/sklearn/tree/tree.py", line 371, in _validate_X_predict n_features = X.shape[1] AttributeError: 'int' object has no attribute 'shape' Answer: If you read the docs for [DecisionTreeClassifier.predict](http://scikit- learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.predict), you can see you are passing the wrong data: **predict(X, check_input=True)** > Predict class or regression value for X. For a classification model, the > predicted class for each sample in X is returned. For a regression model, > the predicted value based on X is returned. Parameters: X : array-like or sparse matrix of shape = [n_samples, n_features]
Python Sql Outputs Question: When running the following code: import sqlite3 conn = sqlite3.connect('example3.db') c = conn.cursor() c.execute(''' SELECT name FROM sqlite_master WHERE type="table" ORDER BY name; ''') print c.fetchall() conn.commit() conn.close() The results are shown are in tuples. [(u'courses',),(u'gradingscheme',),(u'students',),(u'topstudent',)] I want to be able to show the results in a column format instead. How would I go about doing that? Answer: I'm no sqlite programmer but you might try something like #print c.fetchall() row = c.fetchall() for r in row: print r
Why do some Python packages have repetitive directory names? Question: The question of what the directory structure of a Python project has been asked a number of times on Stack Overflow (e.g. [here](http://stackoverflow.com/questions/193161/what-is-the-best-project- structure-for-a-python-application), [here](http://stackoverflow.com/questions/35879872/what-is-a-very-simple-way- to-structure-a-python-project) and [here](http://stackoverflow.com/questions/35738408/how-do-i-structure-my- python-project-to-allow-named-modules-to-be-imported-from)) And many answers are given. But one thing that doesn't seem to be clear in any of those answers is why some projects have repetitive directories. For example, in [this article](http://as.ynchrono.us/2007/12/filesystem-structure- of-python-project_21.html) which is often cited, the suggested layout is: <root>/ |-- Twisted/ | |-- __init__.py | |-- README | |-- setup.py | |-- twisted/ | | |-- __init__.py | | |-- main.py | | |-- test/ | | | |-- __init__.py | | | |-- test_main.py | | | |-- test_other.py | | |-- bin/ | | | |-- myprogram In this example, `/Twisted/twisted/main.py` is the main file But then on the other hand you have advice [like this](http://docs.python- guide.org/en/latest/writing/structure/): > Many developers are structuring their repositories poorly due to the new > bundled application templates. <root>/ |-- samplesite/ | |-- manage.py | |-- samplesite/ | | |-- settings.py | | |-- wsgi.py | | |-- sampleapp/ | | |-- models.py > Dont do this. > > Repetitive paths are confusing for both your tools and your developers. > Unnecessary nesting doesnt help anybody. Let's do it properly: <root>/ |-- manage.py |-- samplesite/ | |-- settings.py | |-- wsgi.py | |-- sampleapp/ | |-- models.py My question is not necessarily "which way is better?", since there may be pros or cons to each way. Instead, my question is, if I go with the more simplified second style, what will I lose? Is there a good reason to have a `/<root>/Twisted/twisted/main.py` directory structure rather than just `/<root>/twisted/main.py` ? Does it make it easier somehow to share my application or make the `import` process smoother? Something else? Answer: I believe the most common layout of python projects is something like this: project/ |-- setup.py |-- bin/ |-- docs/ ... |-- examples/ ... |-- package/ |-- __init__.py |-- module1.py |-- module2.py |-- subpackage/ ... |-- tests/ ... Where the project is the name of the project and the package is the name of the top level import, for example scikits-learn and sklearn. The package has everything that python should be able to import, and you import using the package name. For example `from package import thing` or `from package.module1 import thing`. The project has the package and any supporting things like docs, examples and installation scripts. Notice that there is typically no `__init__.py` in project because project is not python importable. It is common for the project and package to have the same name, but not required.
pip gmane can't import Question: I have already install the gmane, for sure i have run the upgrade. pip install gmane --upgrade And then it show me those: > 'Requirement already up-to-date: gmane in ./lib/python2.7/site-packages' >>> import gmane It's shows me these errors: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/root/code/site/local/lib/python2.7/site-packages/gmane/__init__.py", line 26, in <module> from .networkEvolution import NetworkEvolution File "/root/code/site/local/lib/python2.7/site-packages/gmane/networkEvolution.py", line 9, in <module> from .pca import * File "/root/code/site/local/lib/python2.7/site-packages/gmane/pca.py", line 79 def __init__(self,*metrics,final_dimensions=2,draw=False): ^ SyntaxError: invalid syntax Anyone help? Answer: I have review the error, found the error 'syntax error'.So i have write a very simple sample to confirm it. class MyGmane: def __init__(self,*meteris ,final_dimensions=2,draw=False): pass if __name__ == '__main__': mg = MyGmane() I got the following error: python $python q.py File "q.py", line 2 def __init__(self,*meteris ,final_dimensions=2,draw=False): ^ SyntaxError: invalid syntax After i change the order inside the init method like below: def __init__(self,final_dimensions=2,draw=False,*meteris): And then it work,so I have modify this file (line 79) > "/root/code/site/local/lib/python2.7/site-packages/gmane/pca.py" It's also > work, so i guess there are maybe have a bug on 'game'!
Difference between dir(string) and dir(someString) in Python? Question: I just start learning programming with python. As I learn if I want to list all string modules I wrote: import string print dir(string) Result: > ['Formatter', 'Template', '_TemplateMetaclass', '**builtins** ', '**doc** ', > '**file** ', '**name** ', '**package** ', '_float', '_idmap', '_idmapL', > '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', > 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', > 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', > 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', > 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', > 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', > 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', > 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] But what's about this: someString = "someValues" print dir(someString) Result: > ['**add** ', '**class** ', '**contains** ', '**delattr** ', '**doc** ', > '**eq** ', '**format** ', '**ge** ', '**getattribute** ', '**getitem** ', > '**getnewargs** ', '**getslice** ', '**gt** ', '**hash** ', '**init** ', > '**le** ', '**len** ', '**lt** ', '**mod** ', '**mul** ', '**ne** ', > '**new** ', '**reduce** ', '**reduce_ex** ', '**repr** ', '**rmod** ', > '**rmul** ', '**setattr** ', '**sizeof** ', '**str** ', '**subclasshook** ', > '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', > 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', > 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', > 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', > 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', > 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', > 'upper', 'zfill'] Why the result is different? Answer: At a Python console: >>> import string >>> type(string) <type 'module'> >>> type("someValues") <type 'str'> >>> help(dir) > dir([object]) -> list of strings > > If called without an argument, return the names in the current scope. Else, > return an alphabetized list of names comprising (some of) the >attributes of > the given object, and of attributes reachable from it. If the object > supplies a method named **dir** , it will be used; otherwise the default > dir() logic is used and returns: > > > for a module object: the module's attributes. > for a class object: its attributes, and recursively the attributes > of its bases. > for any other object: its attributes, its class's attributes, and > recursively the attributes of its class's base classes. > Thus, `dir(string)` returns the attributes of the [`string`](https://docs.python.org/2/library/string.html) module while `dir("someValues")` returns the attributes of the [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type- str) class as well as the attributes of instances thereof. For a proper distinction, take a look at [Modules, Classes, and Objects](http://learnpythonthehardway.org/book/ex40.html).
List Index Error on Python Question: Im writing a program to try to calculate how many times the most repeated word in a list occurs. I keep getting an error that says: index error. Even though when I print the list of my word_list, it shows there are 108 elements. Could someone point me in the right direction as to where my error is? length = len(word_list) num = 0 print(length) while num <= length: ele = word_list[num] if ele in wordDict: wordDict[ele] = wordDict[ele] +1 repeat = repeat + 1 if repeat > highestRepeat: highestRepeat = repeat else: wordDict[ele] = 1 repeat = 1 num = num+1 Answer: List indexing goes from `0` to `length-1`. In your while loop, you've told the `num` to go from `0` to `length`. That's why you have an index error. Simply change `num <= length` to `num < length`. That should fix your code for you. * * * As an aside, there are much better ways to do this particular task. A simple two liner: from collections import Counter print(Counter(word_list).most_common(1)) `Counter` will calculate the frequencies of each element in your list for you, and `most_common(1)` will return the element with the highest frequency in your list.