text
stringlengths
226
34.5k
Django-ckeditor file upload doesn't work Question: I use django-ckeditor module in my blog as WYSIWYG editor for create and edit articles in the administration. It work pretty well but I can't upload image to my server. When I click on the image button, the button "browse the server" and "upload image" doesn't appear as they supposed to (I saw it somewhere). I can only add externals images providing their urls. I use Django 1.8 with Python 3.4 The module django-ckeditor and ckeditor_uploader are correctly installed and added in the INSTALLED_APP. This is my settings.py file : import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'ckeditor', 'ckeditor_uploader', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'django-mini-blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'django-mini-blog.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LANGUAGE_CODE = 'fr-fr' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" Thanks in advance for your help. Sincerely, Answer: Did you add the following code to your urls.py file? urlpatterns = patterns( '', .... (r'^ckeditor/', include('ckeditor.urls')), )
Checking if dictionary contains the date and plan Question: So I am trying to create a function that checks whether or not the contents of a function is true: def command_add(date, event, calendar): ''' Add event_details to the list at calendar[date] Create date if it was not there :param date: A string as "YYYY-MM-DD" :param event: A string describing the event :param calendar: The calendars database :return: a string indicating any errors, "" for no errors ''' >>> calendar == {'2015-10-20': ['Python']} True >>> command_add("2015-11-01", "Computer Science class", calendar) '' How would I write such a function? The problem I'm having is how to make the string or how to see if the string for the date is in the format 'YYYY-MM-DD'. Answer: The following code uses `strptime` to parse the date, if the parsing fails it is not a proper date string. Then it checks if the date is already in the calendar dict or not to see whether to append or add the first entry. from datetime import datetime def command_add(date, event, calendar): ''' Add event_details to the list at calendar[date] Create date if it was not there :param date: A string as "YYYY-MM-DD" :param event: A string describing the event :param calendar: The calendars database :return: a string indicating any errors, "" for no errors ''' try: datetime.strptime('%Y-%m-%d', date): except ValueError: return 'Error parsing date' else: if date in calendar: calendar[date].append(event) else: calendar[date] = [event] return ''
convert ceilometer output to python dataframe Question: I'm a little new to Python and openstack ceilometer. I'm reading ceilometer data using the following code: import ceilometerclient.client cclient = ceilometerclient.client.get_client(2, os_username="Ceilometeradmin", os_password="blahblah", os_tenant_name="blahblah", os_auth_url="http://xxx.xx.xx.x:5000/v2.0") query = [dict(field='resource_id', op='eq', value='dd893564-85e5-43f8-a384-086417f1d82c')] ls = cclient.meters.list(q=query) (Please see picture of output attached) [![enter image description here](http://i.stack.imgur.com/JO3Qp.jpg)](http://i.stack.imgur.com/JO3Qp.jpg) Does anyone know how i could convert this into a dataframe? I tried : `ls2 = pandas.DataFrame(ls, columns=["user_id", "name", "resource_id", "source", "meter_id", "project_id", "type", "unit"])` but get the following error: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 250, in init copy=copy) File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 363, in _init_ndarray return create_block_manager_from_blocks([values.T], [columns, index]) File "/usr/lib/python2.7/dist-packages/pandas/core/internals.py", line 3750, in create_block_manager_from_blocks construction_error(tot_items, blocks[0].shape[1:], axes, e) File "/usr/lib/python2.7/dist-packages/pandas/core/internals.py", line 3732, in construction_error passed,implied)) ValueError: Shape of passed values is (1, 2), indices imply (8, 2) if someone could help it would really be much much appreciated.. Thank you Best Wishes T Answer: With the help of a colleague we managed to find the solution. I'm posting it in case it's useful to anyone trying to convert ceilometer data into a dataframe. ls2 = str(ls)[8:-2] tmp = ls2.replace("u'","'") tmp = tmp.replace("<Meter","") tmp = tmp.replace("}>","}") tmp= "["+tmp+"]" tmp = tmp.replace("'", "\"") parsed = json.loads(tmp) ls3 = pandas.DataFrame(parsed) Replaced characters which make it as invalid dictionary and converted into dataframe
How to loop through a tags and redirect to retrieve more a tags? Question: For educational purposes I am trying to write a program that would prompt the user for "url", "count" and "position". The "url" will be scraped and "a tags" within the "url" will be retrieved and this would yield a list of "a tags". The "position" is then used to select a new link from the list of "a tags" previously retrieved and use it as the new "url" to be scraped. "Count" is the number of times this process takes place. Code: import urllib from bs4 import BeautifulSoup as bfs # Declare global variables href_list = [] no_iterations = 0 # Prompt user for input url = raw_input('Enter url - ') count = raw_input('Enter count - ') position = raw_input('Enter position - ') # While loop with condition while no_iterations != int(count): no_iterations += 1 # Scraping the url html = urllib.urlopen(url).read() soup = bfs(html) # Retrieve all of the anchor tags tags = soup('a') for tag in tags: href_list.append(tag.get('href', None)) # Assiginig new url url = href_list[int(position)-1] # Printing info for user print 'Retrieving:', href_list[int(position)-1] print 'Last Url:', href_list[int(position)-1] When I run the program here is what I get: Enter url - http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html Enter count - 4 Enter position - 3 Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Montgomery.html Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Montgomery.html Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Montgomery.html Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Montgomery.html Last Url: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Montgomery.html By observing the output, I can see that the URL is not reset as it should, any advice is appreciated. Answer: I solved by resetting the list were I stored the retrieved a tags Code: import urllib from bs4 import BeautifulSoup as bfs # Declare global variables href_list = [] no_iterations = 0 # Prompt user for input url = raw_input('Enter url - ') count = raw_input('Enter count - ') position = raw_input('Enter position - ') # While loop with condition while no_iterations != int(count): no_iterations += 1 # Scraping the url html = urllib.urlopen(url).read() soup = bfs(html) # Retrieve all of the anchor tags tags = soup('a') for tag in tags: href_list.append(tag.get('href', None)) # Assiginig new url url = href_list[int(position)-1] href_list = [] # Printing info for user print 'Retrieving:', href_list[int(position)-1] print 'Last Url:', url So the new output now is: Enter url - http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html Enter count - 4 Enter position - 3 Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Montgomery.html Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Mhairade.html Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Butchi.html Retrieving: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Anayah.html Last Url: http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Anayah.html Thanks for your support
Python, matplotlib pyplot show() not blocking Question: I'm new to matplotlib.pyplot. I'm having trouble with the show() function not blocking. I've taken over a python application from someone that left and I seem to remembering this worked on his (IT reclaimed) PC. Here's the code ... import matplotlib.pyplot as plt plt.title("Molding X Error") plt.xlabel("X") plt.ylabel("X Error") plt.plot( ... details that work and not the problem ... ) plt.show(block=True) plt.title("Molding Y Error") plt.xlabel("Y") plt.ylabel("Y Error") plt.plot( ... details that work and not the problem ... ) plt.show(block=True) On the other guys PC, the first show() would display appropriately. After dismissing the first, the second would display. I run it, and it not only doesn't stop on the first show(), it combines data from both the first and second with the title and labels from the second. I step through with the debugger, and the first does show, but stepping to the second the same result is seen. Windows 7 Pro 64-bit. Python2.7.10, Anaconda 2.3.0 which contains (apparently) matplotlib1.4.3 Note: I did read through "(python) matplotlib pyplot show() .. blocking or not?" where it was from 2011 and was referring to matplotlib1.0.1 as a solution. Answer: <http://matplotlib.org/api/pyplot_api.html?highlight=plot#matplotlib.pyplot.show> > In non-interactive mode, display all figures and block until the figures > have been closed; in interactive mode it has no effect unless figures were > created prior to a change from non-interactive to interactive mode (not > recommended). In that case it displays the figures but does not block. A > single experimental keyword argument, block, may be set to True or False to > override the blocking behavior described above.
Python ConfigParser won't run from command line Question: Python script runs successfully within IDE, but has ConfigParser error when attempted to run via command line. The error: > raise NoOptionError(option, section) ConfigParser.NoOptionError: No option > 'password' in section: 'database' The code: from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('settings.ini') # sets database and API configuration from settings.ini API_KEY = parser.get('tokens','api_key') db_user = parser.get('database','user') db_pwd = parser.get('database','password') db_host = parser.get('database','host') db_database = parser.get('database','database') Path and Environment appear to be fine, so the issue seems to be with ConfigParser. Any thoughts on what might be wrong? To re-iterate, the script runs fine from within the IDE (when using Spyder, PyCharm, etc.). Environment is pointing to Anaconda, as anticipated. Many thanks for help. Answer: Your import target is incorrect. The module name is "configparser" (case- sensitive.) The IDEs you mentioned probably perform some start-up initialization that masks the error.
Start a neuronal network project Question: after a long term of reading the theory behind neural networks I finally want to stark to do my own project in object recognition. However I struggle to find a practical entry point. I want to use either C#,C++ or C however all new tutorials seem to involve newer languages such as python. For starting I would especially like to reprogram the theory concepts of Yann LeCuns publications about object recognition. Which programming language is recommended to use? And much more important: Which framework do I use? There seem to be docents of frameworks (AForge, Apache Mahout, OpenCV) and my theoretical knowledge seems to be too impractical to differentiate the usage of these. I want to program a simple independent neural network application which should be easy trainable plus I don't want to reprogram classes such as neuron or layer in order to focus on the architecture for the beginning. Thanks and sorry for the simple probably often ask question, however I just couldn't find anything matching. Greetings Nex Answer: disclosure: i'm not an expert. depends on what exactly you want to do. * if you want to build something from scratch, probably the easiest language to start prototyping is matlab/octave because it's high level and offers pretty fast matrix manipulations, nice math support (like numeric derivatives) and robust plotting to quickly verify your models. when you have your prototype, you can port to to c/c++ to make it faster, more space efficient, portable etc. * if you want to just use exiting tools/techniques and just play with parameters (preprocessing, feature selection etc) to find the best model for you, i would recommend start from R and caret package or python (don't remember the package name) * if you want to use NN in cluster on big data then i would try using existing frameworks like openCV (not sure if mahout provides NN)
webdriver container in circleci for testing Question: **Problem** I have a [CircleCI](https://circleci.com) continuous integration for my django application. I would like to use a [standalone chrome](https://github.com/SeleniumHQ/docker- selenium/tree/master/StandaloneChrome) selenium node container to run my UI tests. The following setup works locally: * **Launch django server in the background:** python manage.py migrate && python manage.py runserver 0.0.0.0:8081 & * **Run the webdriver container:** docker run --net='host' --name selenium -d -p 4444:4444 selenium/standalone-chrome * **Run test:** from fabric.operations import local from selenium import webdriver @given('I have a web browser') def browser(): return webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME) @when('I open the main page') def view_main(browser): assert "backend.fail" in local("curl http://localhost:8081/", capture=True) browser.maximize_window() browser.get("http://localhost:8081/") return browser `curl http://localhost:8081/` is run in the context of the CircleCI shell, and succeeds, whereas `browser.get("http://localhost:8081/")` is run from the docker container running webdriver and fails. **Question** How can I make my docker container see my django server on `localhost:8081` on CircleCI? **Research** I read in the docker [documentation](https://docs.docker.com/articles/networking/#container- networking) that `--net=host` puts the host and docker client on the same network stack, and it works locally in a vagrant vm. I have looked at [this question](http://stackoverflow.com/questions/25512772/setting-up-multiple- docker-containers-and-mongodb-to-run-in-circleci) which explores communication between multiple docker containers and [this question](http://stackoverflow.com/questions/31213195/running-docker- container-tests-on-circleci) which handles a general setup of docker tests on CircleCI, but none address the visibility of the host from a docker container. Answer: **Answer:** After some digging and using CircleCI's excellent `ssh` debugging tool, it turned out that the reason for the failure was not `--net='host'` but rather the selenium container failing to start. It silently failed because unable to start xvfb unable to start xvfb unable to start xvfb unable to start xvfb Then I googled _"selenium circleci"_ and it turned out that CircleCI has a native `xfvb` running on `:99` and `chromedriver` [preinstalled](https://circleci.com/docs/environment#browsers): > CircleCI runs graphical programs in a virtual framebuffer, using **xvfb**. > This means programs like **Selenium** , Capybara, Jasmine, and other testing > tools which require a browser **will work perfectly** , just like they do > when you use them locally. I changed my test to: @given('I have a web browser') def browser(): try: return webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME) except: return webdriver.Chrome() And now my tests pass.
thread fails to start if wx.app.mainloop isn't called from the main module Question: I'm hoping someone can explain this behavior to me. If I import a module that starts a wxpython interface, threads are unable to start until after the app.MainLoop() ends. Simplest example: simple_app.py import wx from threading import Thread def test(): from time import sleep while 1: print("thread still running") sleep(2) app = wx.App() frame = wx.Frame(None, -1, 'simple.py') frame.Show() thread = Thread(target=test) thread.setDaemon(True) thread.start() app.MainLoop() main.py import simple_app If you run simple_app.py by itself it works fine, if you run main.py the thread never starts... Why? I have a feeling it has to do with the thread being unable to secure a lock. Answer: The second thread in `simple_app.py` is trying to import the `time` module while an import is already running, which leads to deadlock when `simple_app` is being imported from the main module. Because imports acquire interpreter's import lock for the current thread while importing a module. It has been [documented](https://docs.python.org/2/library/threading.html#importing-in- threaded-code). Threads in the main module can import other modules that's why running `simple_app.py` as main module works. Moving `from time import sleep` to module level in `simple_app.py` solves the problem. Running the following code helps better understand the problem; my_time.py `from time import sleep` simple_app.py import imp import sys from threading import Thread from time import sleep import wx class MyFinder(object): def __init__(self): print('MyFinder initializing') if imp.lock_held(): while imp.lock_held(): print('import lock held') sleep(2) print('import lock released') else: print('import lock is not held') def find_module(self, module, package=None): print('MyFinder.find_module called with module name "{}", pakcage name "{}"'.format(module, package)) return None def test(): sys.meta_path.append(MyFinder()) from my_time import sleep count = 0 while True: print("{} thread still running".format(count)) count += 1 sleep(2) app = wx.App() frame = wx.Frame(None, -1, 'simple.py') frame.Show() thread = Thread(target=test) thread.setDaemon(True) thread.start() app.MainLoop()
Python Selenium Scrape Hidden Data Question: I'm trying to scrape the following page (just page 1 for the purpose of this question): <https://www.sportstats.ca/display-results.xhtml?raceid=4886> I can use Selinium to grab the source then parse it, but not all of the data that I'm looking for is in the source. Some of it needs to be found by clicking on elements. For example, for the first person I can get all the visible fields from the source. But if you click the +, there is more data I'd like to scrape. For example, the "Chip Time" (01:15:29.9), and also the City (Oakville) that pops up on the right after clicking the + for a person. I don't know how to identify the element that needs to be clicked to expand the +, then even after clicking it, I don't know how to find the values I'm looking for. Any tips would be great. Answer: Here is a sample code for your requirement. This code is base on python , selenium with crome exe file. from selenium import webdriver from lxml.html import tostring,fromstring import time import csv myfile = open('demo_detail.csv', 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) driver=webdriver.Chrome('./chromedriver.exe') csv_heading=["","","BIB","NAME","CATEGORY","RANK","GENDER PLACE","CAT. PLACE","GUN TIME","SPLIT NAME","SPLIT DISTANCE","SPLIT TIME","PACE","DISTANCE","RACE TIME","OVERALL (/814)","GENDER (/431)","CATEGORY (/38)","TIME OF DAY"] wr.writerow(csv_heading) count=0 try: url="https://www.sportstats.ca/display-results.xhtml?raceid=4886" driver.get(url) table_tr=driver.find_elements_by_xpath("//table[@class='results overview-result']/tbody/tr[@role='row']") for tr in table_tr: lst=[] count=count+1 table_td=tr.find_elements_by_tag_name("td") for td in table_td: lst.append(td.text) table_td[1].find_element_by_tag_name("div").click() time.sleep(5) table=driver.find_elements_by_xpath("//div[@class='ui-datatable ui-widget']") for demo_tr in driver.find_elements_by_xpath("//tr[@class='ui-expanded-row-content ui-widget-content view-details']/td/div/div/table/tbody/tr"): for demo_td in demo_tr.find_elements_by_tag_name("td"): lst.append(demo_td.text) wr.writerow(lst) table_td[1].find_element_by_tag_name("div").click() time.sleep(5) print count time.sleep(5) driver.quit() except Exception as e: print e driver.quit()
Index error on querying google datastore using gcloud Question: I am trying to use google datastore for my non GAE application. For that i have created kinds and ancestor related entities in datastore using gcloud python library. Also updated datastore index configuration for all the kinds using gcd tool via WEB-INF/datastore-indexes.xml file and its status' are serving. However i can not successfully query the index based columns either in console or using gcloud lib. Here is the query & traceback from gcloud import datastore ds = datastore.Client(dataset_id='XXXXXX') query = datastore.Query(ds, kind='event') query.add_filter('EvtName', '=', 'buy') query.add_filter('EventDateTime', '<=', datetime.datetime(2015, 10, 22, 8, 45)) for itm in query.fetch(): print(dict(itm)) gcloud.exceptions.PreconditionFailed: 412 no matching index found. here is my datastore-indexes.xml config <?xml version="1.0" encoding="utf-8"?> <datastore-indexes autoGenerate="false"> <datastore-index kind="event" ancestor="true"> <property name="EvtName" direction="desc" /> <property name="EventDateTime" direction="desc" /> </datastore-index> <datastore-index kind="att" ancestor="true"> <property name="EvtAttName" direction="desc" /> <property name="EventDateTime" direction="desc" /> </datastore-index> <datastore-index kind="att_val" ancestor="true"> <property name="AttValue" direction="desc" /> <property name="EventDateTime" direction="desc" /> </datastore-index> <datastore-index kind="user" ancestor="true"> <property name="EventDateTime" direction="desc" /> </datastore-index> </datastore-indexes> am i missing something? Answer: All of your indexes are designed to be used with ancestor queries (note the `ancestor=true`). However, your actual query does not query within a specific ancestor. In order to answer your specific query, you need the index: <datastore-index kind="event" ancestor="false"> <property name="EvtName" direction="desc" /> <property name="EventDateTime" direction="desc" /> </datastore-index> Or, if you actually do want to query for entities with a specific parent, make sure to add an ancestor filter with `Query#hasAncestor(Key parentKey)`.
Random choice function Question: I am making a game using pygame based on the game war. I am getting an error when running the code for splitting my deck in the main loop (it is in its own file). The error says: "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty IndexError: list index out of range The deck splitting file looks like this: import Deck from random import * deck = Deck.deck playerDeck = [] AIDeck = [] def splitDeck(): player_deck_count = 26 while player_deck_count > 0: transfer_card = (choice(deck)) playerDeck.append(transfer_card) deck.remove(transfer_card) player_deck_count -= 1 AIDeck = deck shuffle(playerDeck) shuffle(AIDeck) print "Player deck length:" + str(len(playerDeck)) print "AI deck length:" + str(len(AIDeck)) print "Deck length:" + str(len(deck)) The Deck file looks like this: deck = [ '2_c', '2_d', '2_h', '2_s', I get that is has to do with the sequence (list is empty) but there is obviously still 26 cards in the original deck. I have tried changing when the while player_deck_count loop stops but with no luck. Thanks for the help in advance P.S. just comment if you want the main loop. Answer: I believe your problem is that you are relying on the function to set the value of AIDeck. When you attempt to set AIDeck = deck you are moving the reference of `AIDeck` to the reference of `deck`. When the function returns, `AIDeck` is restored to its original definition, which was the empty list. If you are doing `choice(AIDeck)` anywhere in your file, it is probably the cause of your error.
generating a full combination of values from multiple lists in python? Question: I would like to generate a full-matrix of value combinations from multiple lists. But I don't always know how many lists will be provided, and each one can have a different length. I was able to get the answer by abusing itertools.product(), but I think it's overkill. Is there a more pythonic way? import itertools listoflists = [ ["happy","sad"], ["car","bike","truck"], ["true","false"], [3,6,34,8,31]] def comboGenerator(lol): # create a uniform N-dimensional struct, big enough to hold longest dimension longest = max(map(lambda x: len(x),lol)) superstruct = itertools.product(range(longest), repeat=len(lol)) # visit each cell in the struct, ignore the empty ones for a in superstruct: combo = [] try: for index in range(len(lol)): combo.append(lol[index][a[index]]) yield (combo) except IndexError: #this was an empty cell; try again pass for x in comboGenerator(listoflists): print (x) Answer: result = list(itertools.product(*listoflists)) if you want the element type of `result` list be a `list`, then convert it by: result = [list(item) for item in result]
Chaining MySQL commands, Automating database import Question: I am currently writing a python script to automate my process for installing a new project on my server. I simply want to be able to achieve this: use database_name; source database_file.sql In one line using the: mysql -e switch. pseudo code: mysql -uadam -p123456 -e 'use database_name and source database_file.sql' I have tried: mysql -uadam -p123456 -e 'database_name < database_file.sql' The above command throws a syntax error. Any help would be greatly appreciated. Ad Answer: Use this: mysql -uadam -p123456 database_name < database_file.sql You don't need the `-e` switch to import a `.sql` file
How to easily display top level of data structure in python Question: I am working with a (modestly) large complex structured data object in python. It is something I've imported from json, so it's a hierarchical mixture of dicts and lists. The data looks lovely in an online json-hierarchical browser. However I have trouble navigating it in Python. If I type pprint(data) It gives me 30 pages of output in the console. What if I just want to list, for example, the top two levels of the tree? So for example, if I have a list of dicts (e.g. each of which has several keys containing several lists of keys of lists), and at the lowest level there are numbers and strings. How can I show (in text form) just the higher-level part? In the mean time I have resorted to an IDE which has a tree view. But surely it's possible in the console? This must be a perennial problem - people need to do this all the time? Answer: Yep, pretty print does that; from [the documentation](https://docs.python.org/2/library/pprint.html), use the depth=n keyword parameter: >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ... ('parrot', ('fresh fruit',)))))))) >>> pp = pprint.PrettyPrinter(depth=6) >>> pp.pprint(tup) ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...))))))) You can pass that parameter directly to pprint.pprint: >>> pprint.pprint(tup, depth=6) ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
preserving the left and right child while printing python graphs using networkx Question: I am trying to print the binary tree using networkx library in python. But, I am unable to preserve the left and right childs. Is there a way to tell the Graph to print left child first and then the right child? import networkx as nx G = nx.Graph() G.add_edges_from([(10,20), (11,20)]) nx.draw_networkx(G) [![enter image description here](http://i.stack.imgur.com/KlNua.jpg)](http://i.stack.imgur.com/KlNua.jpg)  EDIT 1: On using the pygraphwiz, it results in a directed graph atleast. So, I have better picture of the root node. Below is the code I am using: import pygraphviz as pgv G = pgv.AGraph() G.add_node('20') G.add_node('10') G.add_node('11') G.add_edge('20','10') G.add_edge('20','11') G.add_edge('10','7') G.add_edge('10','12') G.layout() G.draw('file1.png') from IPython.display import Image Image('file1.png') But, this is still far from a structured format. I will post on what I find out next. The new graph looks like below (atleast we know the root): [![Root to Leaf Binary tree](http://i.stack.imgur.com/czjFJ.png)](http://i.stack.imgur.com/czjFJ.png) EDIT 2: For those who are facing issues with installation, please [refer to this post.](http://stackoverflow.com/questions/22698227/python-installation- issues-with-pygraphviz-and-graphviz) [The answer to this](http://stackoverflow.com/a/28832992/4160889) \- its very helpful if you want to install pygraphviz on windows 64 bit. Answer: I believe Networkx is not suited to binary trees but you can set the node positions yourself. I have wrote the following algorithm to setup node positions but it works fine for full or complete binary trees where key nodes are ordered [0,1,...]. def full_tree_pos(G): n = G.number_of_nodes() if n == 0 : return {} # Set position of root pos = {0:(0.5,0.9)} if n == 1: return pos # Calculate height of tree i = 1 while(True): if n >= 2**i and n<2**(i+1): height = i break i+=1 # compute positions for children in a breadth first manner p_key = 0 p_y = 0.9 p_x = 0.5 l_child = True # To indicate the next child to be drawn is a left one, if false it is the right child for i in xrange(height): for j in xrange(2**(i+1)): if 2**(i+1)+j-1 < n: print 2**(i+1)+j-1 if l_child == True: pos[2**(i+1)+j-1] = (p_x - 0.2/(i*i+1) ,p_y - 0.1) G.add_edge(2**(i+1)+j-1,p_key) l_child = False else: pos[2**(i+1)+j-1] = (p_x + 0.2/(i*i+1) ,p_y - 0.1) l_child = True G.add_edge(2**(i+1)+j-1,p_key) p_key += 1 (p_x,p_y) = pos[p_key] return pos G = nx.Graph() G.add_nodes_from(xrange(25)) pos = full_tree_pos(G) nx.draw(G, pos=pos, with_labels=True) plt.show() which gave the following graph. [![enter image description here](http://i.stack.imgur.com/Kdysx.png)](http://i.stack.imgur.com/Kdysx.png)
Python random number generator Question: The code works fine, but I can't figure out how to completely restart the program. I put continue in the code and I know that is not correct, because I want it to restart completely after you guess the correct number and it displays 'Congratulations! You guessed my number in _ guesses. import random guesses = 0 number = random.randint(1, 100) print('I am thinking of a number between 1 and 100.') while guesses < 100: guess = int(input('Guess? ')) guesses = guesses + 1 if guess < number: print('Your guess is too low.') if guess > number: print('Your guess is too high.') if guess == number: continue if guess == number: guesses = str(guesses) print('Congratulations! You guessed my number in ' + guesses + ' guesses!') Answer: so like this: while True: guesses = 0 while guesses < 100: if guesses == 100: break ... if guess == number: print ... yorn = input "do you want to try again?") if yorn == 'n': break so just wrap your code in an outer while, obviously i skipped a lot of your code
Working with the elements of the "matrix" created by genfromtxt, Python3.4 Question: I import a .txt file with the command `tab = np.genfromtxt()` and it creates a kind of matrix. I need to work with its contents. When I visualize the elements with the command for i in range n: print(tab[n][:]) it works and I can use matrix elements with `[][]` like if the first is the line number and the second the column one. Instead when I use the command `tab[0][:]` the command is like I used `tab[:][0]`, i.e. I can visualize only the line 0 with all its elements (`tab[0][:]=tab[:][0]`). What's the way I can move in a fixed column number and use all the line elements without a cicle "for i in range()" type? Thank you. Answer: All indices of a numpy array should be in a single `[]` separated by commas (ie `tab[i,j]`), if you provide just one index you get an array with the first dimension equal to that index (a row in this case). So `tab[:]` returns the whole matrix again. When you apply `[0]` over `tab[:]` it's the same as `tab[0]` For iterating over columns: for i in range n: print(tab[:,n]) For iterating over rows: for i in range n: print(tab[n,:])
UnicodeDecodeError: 'charmap' codec can't encode character X at position Y: character maps to undefined Question: **To CLARIFY: this question is not a duplicate of[this one](http://stackoverflow.com/questions/17912307/u-ufeff-in-python-string), I have already tried all the hints there and didn't get the answer.** I have a txt file with unicode data in, and am want to open the file as an string. I tried a=open('myfile.txt', 'r', encoding='utf-8') print a.read() but there is an error saying: > UnicodeDecodeError: 'charmap' codec can't encode character '\ufeff' at > position Y: character maps to undefined Now my question is, I don't care about my UTF-8 characters at all, is there anyway to put an exception that whenever python is encountering utf-8 character just remove it or pass it? **Also to clarify, I have tried the encoding with, utf-8, utf-8-sig, utf-16 and etc.** I tried this as well but no luck. a=open('myfile.txt', 'r', encoding='utf-8') try: print a.read() except: pass I also tried importing codecs and the code below: a=codecs.open('myfile.txt', 'r', encoding='utf-8') print a.read() but still same error is popping out. Answer: Correcting my answer for encoding in `print` statement: Avoid printing to `stdout` Windows, because Python assumes that CMD terminal can only handle Windows-1252 (MS copy of ISO of latin-1). This is easily sidestepped by always printing to `stderr` instead: import sys print('your text', file=sys.stderr) On Linux there should be no issue with printing Unicode correctly. **P.S.:** for Python 2.x: from __future__ import print_function import sys print('your text', file=sys.stderr) **P.P.S.:** **Original answer:** For python 3.x: a=open('myfile.txt', 'r', encoding='utf-8', errors='ignore') See <https://docs.python.org/3/library/codecs.html#error-handlers> for a detailed list of your options
How to check if Celery/Supervisor is running using Python Question: How to write a script in Python that outputs if celery is running on a machine (Ubuntu)? My use-case. I have a simple python file with some tasks. I'm not using Django or Flask. I use supervisor to run the task queue. For example, **tasks.py** from celery import Celery, task app = Celery('tasks') @app.task() def add_together(a, b): return a + b **Supervisor:** [program:celery_worker] directory = /var/app/ command=celery -A tasks worker info This all works, I now want to have page which checks if celery/supervisor process is running. i.e. something like this maybe using Flask allowing me to host the page giving a 200 status allowing me to load balance. For example... **check_status.py** from flask import Flask app = Flask(__name__) @app.route('/') def status_check(): #check supervisor is running if supervisor: return render_template('up.html') else: return render_template('down.html') if __name__ == '__main__': app.run() Answer: You can run the `celery status` command via code by importing the `celery.bin.celery` package: import celery import celery.bin.base import celery.bin.celery import celery.platforms app = celery.Celery('tasks', broker='redis://') status = celery.bin.celery.CeleryCommand.commands['status']() status.app = status.get_app() def celery_is_up(): try: status.run() return True except celery.bin.base.Error as e: if e.status == celery.platforms.EX_UNAVAILABLE: return False raise e if __name__ == '__main__': if celery_is_up(): print('Celery up!') else: print('Celery not responding...')
python: using raw socket with OSX Question: I found this code online and found that it doesn't work on OSX. Does anyone know the correct method without using a third party library? import socket import struct import binascii rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) while True: packet = rawSocket.recvfrom(2048) ethernet_header = packet[0][0:14] ethernet_detailed = struct.unpack(“!6s6s2s”, ethernet_header) arp_header = packet[0][14:42] arp_detailed = struct.unpack(“2s2s1s1s2s6s4s6s4s”, arp_header) # skip non-ARP packets ethertype = ethernet_detailed[2] if ethertype != ‘\x08\x06’: continue source_mac = binascii.hexlify(arp_detailed[5]) dest_ip = socket.inet_ntoa(arp_detailed[8]) if source_mac == ‘74c24671971c’: print “Tide button pressed!, IP = “ + dest_ip apparantly OSX does not have AF_PACKET or PF_PACKET and AF_INET is too high level for this I think, or at the very least requires more recoding than a drop in replacement. Thanks Answer: ok I figured this one out, on a mac I have to use pcap library. Here is the code I came up with. #!/usr/bin/env python2.7 import sys, binascii, subprocess import dpkt, pcap, socket cottonelle = 'f0272d8b52c0' def main(): name = pcap.lookupdev() try: pc = pcap.pcap(name) except: print pc.geterr() try: print 'listening on %s' % (pc.name) for ts, pkt in pc: eth = dpkt.ethernet.Ethernet(pkt) ip_hdr = eth.data if eth.type != dpkt.ethernet.ETH_TYPE_ARP: continue if binascii.hexlify(eth.src) == cottonelle: subprocess.call("/usr/local/bin/stopsim", shell=True) except Exception as e: print e, pc.geterr() if __name__ == '__main__': main()
Blender - Open and parse a .blend file from python script Question: I would like to open a .blend file from a python script and parse it (get objects, animations and materials). The documentation I have read so far about how to do this from blender API (running the script as a blender add-on), but I would like to run this script from the command line without opening blender. I appreciate all the help you can give me. Answer: I realized I don't need to open the binary blender file and parse it in order to use the objects. Blender has its own python installation, so I put a python script inside the folder **path_to_blender/version/scripts/addons** , I can execute it in the command line as follows: blender.exe --background --python ./version/scripts/addons/superScript.py Next, if you have a .blend file you want to read from your script, put it after the background parameter as follows: blender.exe --background myFile.blend --python ./version/scripts/addons/superScript.py And inside your python script do the following: import bpy import os for ob in bpy.context.scene.objects: print("object name: ", ob.data.name) In this example I'm printing all the objects inside the scene in the .blend file
Imagetk.PhotoImage crashes on Python 3.5 + Tk/Tcl 8.6 Question: I'm trying to display an image in Tkinter using Pillow but I get a weird error: "Process finished with exit code -1073741819 (0xC0000005)" and the Tkinter window never appears. Here's the code (simplified to the max): from PIL import Image, ImageTk from tkinter import Tk t = Tk() i = Image.open('data/pic.jpg') # small picture (29kb, 100x100px) i_tk = ImageTk.PhotoImage(i) # The problem disappears when this line is commented out. t.mainloop() I'm using Python 3.5, Tcl/Tk 8.6, Pillow 3.0.0 on Windows 10 (all in 64bit) That same script (replacing tkinter by Tkinter) runs perfectly on the same machine with Python 2.7.9, Tcl/Tk 8.5 and Pillow 2.9.0 (the Tk window appears and the exit code is 0 when I close the Tk window). Any help would be much appreciated. EDIT: Per user5510752's suggestion, I changed `i_tk = ImageTk.PhotoImage(i)` to `i_tk = tkinter.PhotoImage(i)`. The problem has now shifted from where I was making the PhotoImage to where I'm inserting it in the canvas. Here's the new code: from PIL import Image from tkinter import Tk, PhotoImage, Canvas t = Tk() c = Canvas(t, bg="blue") c.grid(sticky="news") c.i = Image.open("data/pic.jpg") c.p = PhotoImage(c.i) c.create_image(0, 0, image=c.p) # errors out here t.mainloop() This gives this error `TypeError: __str__ returned non-string (type JpegImageFile)`. Traceback (most recent call last): File "D:/Workspace/PythonProjects/Puzzle 3.5/main.py", line 29, in <module> c.create_image(0, 0, image=c.p) File "C:\Python 3.5\lib\tkinter\__init__.py", line 2328, in create_image return self._create('image', args, kw) File "C:\Python 3.5\lib\tkinter\__init__.py", line 2319, in _create *(args + self._options(cnf, kw)))) TypeError: __str__ returned non-string (type JpegImageFile) I looked into a different signature for this function for Python 3, but I couldn't find anything. This line works on Python 2.7 though (with `ImageTk.PhotoImage`). What's weirder is that if I try to load c.i into the canvas instead of c.p, the code doesn't error out and I get an empty canvas. [EDIT2] As per R4PH43L's suggestion I tried : from tkinter import Tk, PhotoImage, Canvas t = Tk() c = Canvas(t, bg="blue") c.grid(sticky="news") c.p=PhotoImage(file="data/pic.jpg") c.create_image(0, 0, image=c.p) # errors out here t.mainloop() This gave a new error : Traceback (most recent call last): File "D:/Workspace/PythonProjects/Puzzle 3.5/main.py", line 28, in <module> c.p=PhotoImage(file="data/pic.jpg") File "C:\Python 3.5\lib\tkinter\__init__.py", line 3393, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python 3.5\lib\tkinter\__init__.py", line 3349, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize data in image file "data/pic.jpg" I've tried each time with different JPEGs to no avail. This time I also tried with a GIF and it worked (but I need to open JPEGs, so...). It's worth noting that libjpeg is installed on my machine and Pillow doesn't seem to have any trouble using it (except when I pass the pic to ImageTk, then we're back to my original error). PS : If someone managed to show a jpg file in a tkinter canvas in python 3.5, please just post the version of Tcl/Tk, libjpeg and Pillow you're using. I suspect this may just be down to two modules being incompatible in my current Python 3 config. Answer: Most of the tkinter functions have changed for python 3, your variable, i_tk, must be like this: i_tk = tkinter.PhotoImage(i)
python match lists Question: Removing supersets when sublists are compared with other sublists in a list_of_lists Input: my_list = [['cat','bat'],['sat','rat','mat'],['cat','bat','hat'],['pat','mat']] Here ['cat', 'bat'] is a subset of ['cat', 'bat', 'hat'] So I need to remove the superset ['cat', 'bat', 'hat'] from my_list Desired Output should be: my_new_list = [['cat','bat'],['sat','rat','mat'],['pat','mat']] I found a similar thread but could not implement the same code for comparing sublists with one another. Can anyone help me with this? def match(my_list[],my_list[]): matches = set(my_list[]).issuperset() return [remove(my_list[]) for sublist in my_list if matches (sublist)] Answer: Take a look at this: from itertools import permutations my_list = [['cat','bat'],['sat','rat','mat'],['cat','bat','hat'],['pat','mat']] for a,b in permutations(my_list,2): if set(a).issubset(b): my_list.remove(b) print my_list
Data structure of memoization in db Question: What is the best data structure to cache (save/store/memorize) so many function result in database. Suppose function calc_regress with flowing definition in python: def calc_regress(ind_key, dep_key, count=30): independent_list = sql_select_recent_values(count, ind_key) dependant_list = sql_select_recent_values(count, dep_key) import scipy.stats as st return st.linregress(independent_list, dependant_list) I see answers to [What kind of table structure should be used to store memoized function parameters and results in a relational database?](http://stackoverflow.com/questions/11147972/what-kind-of-table- structure-should-be-used-to-store-memoized-function-parameter) but it seem to resolve problem of just one function while I have about 500 function. Answer: **Option A** You could use the structure in the linked answer, un-normalized with the number of columns = max number of arguments among the 500 functions. Also need to add a column for the function name. Then you could do a `SELECT * FROM expensive_func_results WHERE func_name = 'calc_regress' AND arg1 = ind_key AND arg2 = dep_key and arg3 = count`, etc. Ofcourse, that's not a very good design to use. For the same function called with fewer parameters, columns with null values/non-matches need to be ignored; otherwise you'll get multiple result rows. **Option B** Create the table/structure as `func_name`, `arguments`, `result` where 'arguments' is always a kwargs dictionary or positional args but not mixed per entry. Even with the kwargs dict stored as a string, order of keys->values in it is not predictable/consistent even if it's the same args. So you'll need to order it before converting to a string and storing it. When you want to query, you'll use `SELECT * FROM expensive_func_results WHERE func_name = 'calc_regress' AND arguments = 'str(kwargs_dict)'`, where `str(kwargs_dict)` is something you'll set programmatically. It could also be set to the result of [`inspect.getargspec`](https://docs.python.org/2.7/library/inspect.html#inspect.getargspec), (or [`inspect.getcallargs`](https://docs.python.org/2.7/library/inspect.html#inspect.getcallargs)) though you'll have to check for consistency. You won't be able to do queries on the argument combos unless you provide all the arguments to the query or partial match with `LIKE`. **Option C** Normalised all the way: One table `func_calls` as `func_name`, `args_combo_id`, `arg_name_idx`, `arg_value`. Each row of the table will store one arg for one combo of that function's calling args. Another table `func_results` as `func_name`, `args_combo_id`, `result`. You could also normalise further for `func_name` to be mapped to a `func_id`. In this one, the order of keyword args doesn't matter since you'll be doing an Inner join to select each parameter. This query will have to be built programmatically or done via a stored procedure, since the number of joins required to fetch all the parameters is determined by the number of parameters. Your function above has 3 params but you may have another with 10. `arg_name_idx` is 'argument name or index' so it also works for mixed kwargs + args. Some duplication may occur in cases like `calc_regress(ind_key=1, dep_key=2, count=30)` and `calc_regress(1, 2, 30)` (as well as `calc_regress(1, 2)` with a default value for count <\-- this cases should be avoided, the table entry should have all args); since the `args_combo_id` will be different for both but result will obviously be the same. Again, the inspect module may help in this area. * * * _[Edit]_ PS: Additionally, for the `func_name`, you may need to use a fully qualified name to avoid conflicts across modules in your package. And decorators may interfere with that as well; without a `deco.__name__ = func.__name__`, etc. PPS: If objects are being passed to functions being memoized in the db, make sure that their `__str__` is something useful & repeatable/consistent to store as arg values. This particular case doesn't require you to re-create objects from the arg values in the db, otherwise, you'd need to make `__str__` or `__repr__` like the way [`__repr__` was intended to be](https://docs.python.org/2/reference/datamodel.html#object.__repr__) (but isn't generally done): > this should look like a valid Python expression that could be used to > recreate an object with the same value (given an appropriate environment).
Cannot import seaborn Question: I have a problem with importing seaborn. I recently installed "anaconda" on my PC and tried to use seaborn pacjesge. I updated `scipy` and `numpy`. Actually before updating `scipy` python couldn't see `seaborn`. What is problem? Please help me Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 17:02:03) Type "copyright", "credits" or "license" for more information. IPython 3.2.0 -- An enhanced Interactive Python. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import seaborn as sns --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-ed9806ce3570> in <module>() ----> 1 import seaborn as sns ~/anaconda/lib/python2.7/site-packages/seaborn/__init__.py in <module>() ----> 1 from .rcmod import * 2 from .utils import * 3 from .palettes import * 4 from .linearmodels import * 5 from .categorical import * ~/anaconda/lib/python2.7/site-packages/seaborn/rcmod.py in <module>() 1 """Functions that alter the matplotlib rc dictionary on the fly.""" ----> 2 import numpy as np 3 import matplotlib as mpl 4 5 from . import palettes ~/anaconda/lib/python2.7/site-packages/numpy/__init__.py in <module>() 178 return loader(*packages, **options) 179 --> 180 from . import add_newdocs 181 __all__ = ['add_newdocs', 182 'ModuleDeprecationWarning', ~/anaconda/lib/python2.7/site-packages/numpy/add_newdocs.py in <module>() 11 from __future__ import division, absolute_import, print_function 12 ---> 13 from numpy.lib import add_newdoc 14 15 ############################################################################### ~/anaconda/lib/python2.7/site-packages/numpy/lib/__init__.py in <module>() 6 from numpy.version import version as __version__ 7 ----> 8 from .type_check import * 9 from .index_tricks import * 10 from .function_base import * ~/anaconda/lib/python2.7/site-packages/numpy/lib/type_check.py in <module>() 9 'common_type'] 10 ---> 11 import numpy.core.numeric as _nx 12 from numpy.core.numeric import asarray, asanyarray, array, isnan, \ 13 obj2sctype, zeros ~/anaconda/lib/python2.7/site-packages/numpy/core/__init__.py in <module>() 12 if 'GOTOBLAS_MAIN_FREE' not in os.environ: 13 os.environ['GOTOBLAS_MAIN_FREE'] = '1' ---> 14 from . import multiarray 15 os.environ.clear() 16 os.environ.update(envbak) ImportError: libopenblas.so.0: cannot open shared object file: No such file or directory In [2]: Answer: In my case, I just installed the jupyter again, and it works
How to apply a function for each element in a matrix in Python? Question: I have a matrix of triangles where each line has 3 verticies: elementSet: Element Number Vertices 2 473 1159 917 3 271 1026 816 And I also have a matrix of nodes that assign a 2d coordinated for every vertice nodeSet: Vertice Number (X,Y) 917 5.487167292060809 2.195789288329368 271 5.448888739433895 2.38822856765269 I've written some methods to handle the area calculation, they are contained in a class: def findArea(self): self.elementsArea = nu.zeros((self.elementSet.shape[0],1)) self.elementsArea[:] = self.calcArea(*self.elementSet[:,-3:]) #Calculate the area of 3 points def calcArea (self,p1,p2,p3): [p1,p2,p3] = [self.nodeCoord(p1),self.nodeCoord(p2),self.nodeCoord(p3)] return 0.5*abs(p1[Xc]*(p2[Yc] - p3[Yc]) + p2[Xc]*(p3[Yc]-p1[Yc]) + p3[Xc]*(p1[Yc] - p2[Yc])) # returns the vertices of a point def nodeCoord(self, point): return(self.nodeSet[point-1,-3:-1]) where the function `calcArea` works fine but I want to apply a function to every element of a matrix and assign to another matrix without using a loop. I have to write something like: A[:] = func(B[:]) In `def findArea()` I tried to do something like this but it gives me the following error: calcArea() takes 4 positional arguments but 2171 were given I wanna use calcArea() to calculate the area passing arrays as arguments the same way I did in this exemple: import numpy as np def test(x,y): return x*y f = np.array([[1,2,5,6,7] , [3,4,9,6,7] ,[6,7,23,34,32]]) print(test(f[0,:],f[1,:])) I am trying to apply calcArea method but I am getting now only a 2 dimmensions array when I was suppose to get an array the same dimmension the original vectors a.calcArea(f[0,:],f[1,:],f[2,:]) array([ 7.5, 0. ]) Answer: If you can rearrange your data into a set of three 2D arrays containing the _x,y_ coordinates for the first, second and third vertices of all your triangles (e.g. with dimensions `(2, n)` where `n` is the number of triangles) then you can easily vectorize the computation over all triangles: import numpy as np # adapted from your code. here p1, p2 and p3 are (2, ...) vectors of x,y coords. def triangle_area(p1, p2, p3): return 0.5 * np.abs(p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])) n = 100000 # some random vertex data vert_data = np.random.randn(3, 2, n) # each of these is a (2, n) vector of x,y coordinates P1, P2, P3 = vert_data # a 100000-long vector of areas areas = triangle_area(P1, P2, P3) Timing: In [41]: %%timeit P1, P2, P3 = np.random.randn(3, 2, 100000) ....: triangle_area(P1, P2, P3) ....: 1000 loops, best of 3: 1.09 ms per loop
Intelligent replacement using given terms in sympy Question: I'm using [sympy](http://www.sympy.org/en/index.html) to do symbolic calculations in Python3. My problem is to enforce a substitution of a known term a, defined as a product of x, y and z. See this minimal example: import sympy as sp from sympy.abc import a,x,y,z expr=(x*y)/z**3 *(x**2*y**2-5*x*y*z+12*z**2) print (expr) #as typed in line 3 print (expr.subs(x*y/z,a)) #only substitues the first factor to a**1/z**2 print (sp.simplify(expr)) #not any better What I'd like to see is an expression of the form a**3-5*a**2+12*a with a=x*y/z Neither line 4 nor lines 5 or 6 do the trick. Can anyone help me? Thank you! Answer: Well, for this particular example, the following idea leads to a solution, but in more generality, I don't know how to achieve the goal. So, instead of substituting `x*y/z` as `a`, substitute equivalently `x*y` to `a*z`, and then simplify. expr2 = expr.subs(x*y, a*z) print(expr2) print(sp.simplify(expr2))
Decimal to binary Half-Precision IEEE 754 in Python Question: I was only able to convert a decimal into a binary single-precision IEEE754, using the `struct.pack` module, or do the opposite (float16 or float32) using `numpy.frombuffer` Is it possible to convert a decimal to a binary half precision floating point, using Numpy? I need to print the result of the conversion, so if I type `"117.0"`, it should print `"0101011101010000"` Answer: > if I type "117.0", it should print "0101011101010000" >>> import numpy as np >>> bin(np.float16(117.0).view('H'))[2:].zfill(16) '0101011101010000'
reading a csv file and removing \n in Python Question: I'm trying to read a csv file and put the elements in an array but the last element of each row is being joined with the first element of the following row with a \n in the middle. Here is the code: f = open("read_file.csv", "r+") lines = f.read().split(',') f.close() print lines exit() Answer: You would want to use the csv module in the standard library import csv with open('read_file.csv', 'r+') as csvfile: lines = csv.reader(csvfile) for line in lines: # do your stuff here
what's wrong with this python code Question: This is a code with Web crawler. I'm a beginer in learning python.So i don't know how to solve. It seems wrong with search() # -*- coding:utf-8 -*- import urllib,urllib2,re class BDTB: def __init__(self,baseUrl,seeLZ): self.baseUrl = baseUrl self.seeLZ = '?see_lz' + str(seeLZ) def getPage(self,pageNum): try: url = self.baseUrl + self.seeLZ + '&pn=' + str(pageNum) request = urllib2.Request(url) response = urllib2.urlopen(request) #print response.read().decode('utf-8') return response except urllib2.URLError,e: if hasattr(e,'reason'): print u'连接百度贴吧失败,错误原因',e.reason return None def getTitle(self): page = self.getPage(1) pattern = re.compile('<h3 class.*?px">(.*?)</h3>',re.S) result = re.search(pattern,page) if result: print result.group(1) return result.group(1).strip() else: return None baseURL = 'http://tieba.baidu.com/p/4095047339' bdtb = BDTB(baseURL,1) bdtb.getTitle() Answer: This will raise a `TypeError: expected string or buffer` because you are passing the object returned from `urllib2.urlopen(request)` to `re.search()` when it requires an `str`. If you change the return value from: return responce # returns the object to one that returns the text contained in the request: return responce.read() # returns the text contained in the responce Your script works and after executing it returns: 广告兼职及二手物品交易集中贴 _Additionally_ , since you're working with `Python 2.x` you might want to change you object from `class BDTB:` to `class BDTB(object)` in order to use [**new style classes**](http://stackoverflow.com/questions/54867/what-is-the- difference-between-old-style-and-new-style-classes-in-python).
How to sort .csv file values by combining like strings using python3 Question: I'm still learning so please bear with me. I've been trying to figure this out for sometime now but have not found what im looking for. My Product.csv file looks like this. 111 ; Info1 ; Description 1 ; Remarks1 123 ; Info1 ; Description 1 ; Remarks1 156 ; Info2 ; Description 2 ; Remarks2 124 ; Info3 ; Description 3 ; Remarks3 I would like to combine entries that are similar like this. 111, 123 ; Info1 ; Description 1 ; Remarks1 156 ; Info2 ; Description 2 ; Remarks2 124 ; Info3 ; Description 3 ; Remarks3 From here i can manipulate my csv file in Excel using vba to insert into a quotation. This is what i would like to achieve using Python. I'm stummped on where to start. I think I need to sart by opening the file and then reading the csv file. After that assign variable to #(i.e. 111) , info, Description, Remarks. Then sort thru the variables and combine like #'s. Then write it back to the file. Please let me know if you need me to calrify anything. Answer: That's a task for [itertools.groupby](https://docs.python.org/3.4/library/itertools.html#itertools.groupby) **EDIT:** I re-factored the first version to improve readability # file group_by_trailing_py2.py import os import csv from itertools import groupby DELIM=';' IN_FILENAME = 'My Product.csv' OUT_FILENAME = 'My Product.grouped.csv' ############ skip this if you run it against productive data ############### DATA = '''111 ; Info1 ; Description 1 ; Remarks1 123 ; Info1 ; Description 1 ; Remarks1 156 ; Info2 ; Description 2 ; Remarks2 124 ; Info3 ; Description 3 ; Remarks3''' if (os.environ.get('WITH_DATA_GENERATION')): open(IN_FILENAME,'w').write(DATA) ############################################################################## keyfunc = lambda row: row[1:] with open(IN_FILENAME) as csv_file: rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc) it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0], groupby(rows, key=keyfunc)) with open(OUT_FILENAME, 'w') as csv_file: writer = csv.writer(csv_file, delimiter=DELIM) for row in it: writer.writerow(row) if run with WITH_DATA_GENERATION=1 python3 group_by_trailing_pk2.py it produces `My Product.grouped.csv` with the content: 111, 123 ; Info1 ; Description 1 ; Remarks1 156 ; Info2 ; Description 2 ; Remarks2 124 ; Info3 ; Description 3 ; Remarks3 Because you have an existing workload **you will not set WITH_DATA_GENERATION** and delete the code between and including the `'####...'` comment lines.
Mix APIView and FormMixin: 'function' object has no attribute 'copy' Question: I want to make a class based view that has GET method which renders a form and POST method which process form data and also accept JSON. So I use Django REST Framework's APIView and Django's FormMixin like this: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer from django.views.generic.edit import FormMixin from django.core.urlresolvers import reverse_lazy from feedback.models import Feedback class FeedbackView(GenericAPIView, FormMixin): renderer_classes = (TemplateHTMLRenderer, JSONRenderer) template_name = 'feedback/feedback.html' form_class = FeedbackForm success_url = reverse_lazy('feedback') def get(self, request, *args, **kwargs): form = self.get_form() return Response({'form': form}) When `get` method is called, I get this error: Exception Type: AttributeError at /feedback/ Exception Value: 'function' object has no attribute 'copy' Traceback: File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/rest_framework/views.py" in dispatch 466. response = self.handle_exception(exc) File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/rest_framework/views.py" in dispatch 463. response = handler(request, *args, **kwargs) File "/home/roman/work/gvis_website/feedback/views.py" in get 62. form = self.get_form() File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/django/views/generic/edit.py" in get_form 74. return form_class(**self.get_form_kwargs()) File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/django/views/generic/edit.py" in get_form_kwargs 81. 'initial': self.get_initial(), File "/home/roman/.virtualenvs/env__gvis_website/lib/python3.3/site-packages/django/views/generic/edit.py" in get_initial 54. return self.initial.copy() `initial` is an empty dictionary defined in FormMixin class like this: initial = {} Why it suddenly lost its `copy` method? Or what does exception means? Exception won't appear if I replace `APIView` by some Django built-in class like `View`. Can I use APIView class and FormMixin or I should change my way to render form? Answer: The reason this happens is that `GenericAPIView` already has a method called `initial`. <https://github.com/tomchristie/django-rest- framework/blob/master/rest_framework/views.py#L369> First thing's first - you should not add FormMixin into DRF generic view, they are not intended to work together. You should use `HTMLFormRenderer` as your renderer instead. Please refer to <http://www.django-rest- framework.org/topics/html-and-forms/#rendering-forms> for more details. Also, think about splitting your json endpoints by using prefixed urls, smth like `api/v1/`. This will save you a lots of headaches overtime, when dealing with more complicated logic.
UserString subclass, 'str' object is not callable Question: I'm kinda stuck at this code, it's supposed to create a string-like object, which, upon using, will return internal lambda's value. I use collections.UserString. from collections import UserString class instrx(UserString): func = None data = '' def __init__(self,func): self.func = func def __getattribute__(self,name): print("get",name) if name=='data': self.data = self.func() return UserString.__getattribute__(self,name) a = instrx(lambda: 'aa') print(a,type(a)) print(a.lower()) Running this code gives me this: Traceback (most recent call last): File "C:\path\a.py", line 14, in <module> print(a.lower()) File "C:\Python35\lib\collections\__init__.py", line 1082, in __str__ def __str__(self): return str(self.data) File "C:\path\a.py", line 10, in __getattribute__ self.data = self.func() TypeError: 'str' object is not callable Python version: 3.4, 3.5. Answer: Okay, I figured this out. It seems that in some functions in UserString (like `.lower()` in example) `self.__class__(self.data)` construction is used. I did a little workaround: import time from collections import UserString class instrx(UserString): func = None data = '' def __init__(self,data,func=None): self.data = data if func==None: self.func = lambda: UserString.__getattribute__(self,'data') else: self.func = func def __getattribute__(self,name): if name=='data': self.data = str(self.func()) return UserString.__getattribute__(self,name) a = instrx('',func=lambda: time.time()) print(a,type(a)) print(a.lower()) print(a+"test") Works just fine.
Efficient repeated substring replace with Python Question: How can I efficiently replace substrings in python, where one substring may be part of another? For example: >>> "||||".replace("||","|X|") '|X||X|' # What I want: |X|X|X| Certainly I could keep repeating the replace and until there are no more instances of `||` in the string, but surely there's a better/faster way? Answer: In general you need to repeat the process. In this specific case however you can use a regexp to insert `X` between consecutive `|` signs: import re print(re.sub("[|](?=[|])", "|X", "||||")) meaning is "replace any pipe with pipe+X if what follows is another pipe (but don't consider it part of the match)"
Iterate and discard sequential duplicates Question: I'm new to python(any kind of coding really). So i'm sorry if if gets a bit confusing I have a csv file like the following A B C D E F G H 14 BP1 BP1-19119308 OR1A1 19119308 chip-chip Hs578T human 11/23/09 15 BP1 BP1-19119308 PTPRE 19119308 chip-chip Hs578T human 11/23/09 16 BP1 BP1-19119308 SELE 19119308 chip-chip Hs578T human 11/23/09 17 BP1 BP1-19119308 TAC3 19119308 chip-chip Hs578T human 11/23/09 18 BP1 BP1-19119308 VEGFA 19119308 chip-chip Hs578T human 11/23/09 19 CHD7 CHD7-19251738 APOA1 19251738 chip-chip MESC mouse 11/23/09 20 CHD7 CHD7-19251738 ARHGAP26 19251738 chip-chip MESC mouse 11/23/09 And I need to make it look like this BP1-19119308-chip-chip-Hs578T-human OR1A1 PTPRE SELE TAC3 VEGFA CHD7-19251738-chip-chip-MESC-mouse APOA1 ARHGAP26 I did manage to the C-F-G-H in the first column with this import csv out = open ('test.csv','rt', encoding='utf8') data = csv.reader(out) output = csv.writer(out) data = [row for row in data] new_data = [[row[2]+'-'+row[5]+'-'+row[6] +'-'+ row[7], row[3]] for row in data] print (new_data) out = open('new_data.csv','wt') output = csv.writer(out) for row in new_data: output.writerow(row) out.close() A B BP1-19119308-chip-chip-Hs578T-human OR1A1 BP1-19119308-chip-chip-Hs578T-human PTPRE BP1-19119308-chip-chip-Hs578T-human SELE BP1-19119308-chip-chip-Hs578T-human TAC3 BP1-19119308-chip-chip-Hs578T-human VEGFA CHD7-19251738-chip-chip-MESC-mouse APOA1 CHD7-19251738-chip-chip-MESC-mouse ARHGAP26 CHD7-19251738-chip-chip-MESC-mouse ATP11A But now I have these duplicates in A and I have no idea how to delete them and transpose all the values in B that were assigned to these duplicates. I tried looping again to compare the current value to the previous value and I just messed the whole thing up. Any suggestions? Answer: You want to use a dictionary. If you're doing further analysis, save the aggregated values in a list for each identifier. Your identifier string is a key, and under each key, you have a list of values. new_keys = [row[2] + '-' + row[5] + '-' + row[6] + '-' + row[7] for row in data] new_values = [row[3] for row in data] aggregate_values = {} # An empty dictionary # Iterate across the paired lists together for key, value in zip(new_keys, new_values): if key not in aggregate_values: aggregate_values[key] = [value] else: aggregate_values[key].append(value) # printed output for key in aggregate_values: print key + " " + " ".join(aggregate_values[key])
xml child-value extraction with python Question: I have trouble extracting the attribute/value of element t0, t1, t2. this is my initial attempt. I was hoping to assign the values in t0,t1,t2 into the variables listed below, but I had no luck with that(started learning python yesterday!) Anyone with an idea? from xml.dom import minidom xmldoc = minidom.parse('all.xml') Sensor0 = xmldoc.getElementsByTagName("t0") Sensor1 = xmldoc.getElementsByTagName("t1") Sensor2 = xmldoc.getElementsByTagName("t2") print(Sensor0) print(Sensor1) print(Sensor2) this is what is stored in the variables - obviously not the values what I am looking for [<DOM Element: t0 at 0x2fe1d00>] [<DOM Element: t1 at 0x2ff16c0>] [<DOM Element: t2 at 0x2ff92b0>] here is my xml file <xml><data> <devicename>ALL4000</devicename> <n0>0</n0><t0>1.25</t0><min0> 0.00</min0><max0> 2.55</max0><l0>-55</l0><h0>150</h0><s0>102</s0> <n1>1</n1><t1>1.44</t1><min1> 2.32</min1><max1> 10487.04</max1><l1>-55</l1><h1>150</h1><s1>102</s1> <n2>2</n2><t2>1.81</t2><min2> 0.00</min2><max2> 2.55</max2><l2>-55</l2><h2>150</h2><s2>102</s2> <n3>3</n3><t3>-20480.00</t3><min3> 0.00</min3><max3> 5580.80</max3><l3>-55</l3><h3>150</h3><s3>0</s3> <n4>4</n4><t4>-20480.00</t4><min4> 40.96</min4><max4> 41943.04</max4><l4>-55</l4><h4>150</h4><s4>0</s4> <n5>5</n5><t5>-20480.00</t5><min5> 10.24</min5><max5> 0.08</max5><l5>-55</l5><h5>150</h5><s5>0</s5> <n6>6</n6><t6>-20480.00</t6><min6> 0.00</min6><max6>-20480.00</max6><l6>-55</l6><h6>150</h6><s6>0</s6> <n7>7</n7><t7>-20480.00</t7><min7> 0.00</min7><max7> 0.00</max7><l7>-55</l7><h7>150</h7><s7>0</s7> <n8>8</n8><t8>-20480.00</t8><min8> 336855.04</min8><max8> 1342177.28</max8><l8>-55</l8><h8>150</h8><s8>0</s8> <n9>9</n9><t9>-20480.00</t9><min9> 0.00</min9><max9> 0.00</max9><l9>-55</l9><h9>150</h9><s9>0</s9> <n10>10</n10><t10>-20480.00</t10><min10> 0.00</min10><max10> 0.00</max10><l10>-55</l10><h10>150</h10><s10>0</s10> <n11>11</n11><t11>-20480.00</t11><min11> 0.00</min11><max11> 0.00</max11><l11>-55</l11><h11>150</h11><s11>0</s11> <n12>12</n12><t12>-20480.00</t12><min12> 0.00</min12><max12> 0.00</max12><l12>-55</l12><h12>150</h12><s12>0</s12> <n13>13</n13><t13>-20480.00</t13><min13> 0.00</min13><max13> 0.00</max13><l13>-55</l13><h13>150</h13><s13>0</s13> <n14>14</n14><t14>-20480.00</t14><min14> 0.00</min14><max14> 0.00</max14><l14>-55</l14><h14>150</h14><s14>0</s14> <n15>15</n15><t15>-20480.00</t15><min15> 0.00</min15><max15> 0.00</max15><l15>-55</l15><h15>150</h15><s15>0</s15> <fn0>1</fn0><ft0>0</ft0><fs0>0</fs0> <fn1>2</fn1><ft1>0</ft1><fs1>0</fs1> <fn2>3</fn2><ft2>0</ft2><fs2>0</fs2> <fn3>4</fn3><ft3>0</ft3><fs3>0</fs3> <fn4>5</fn4><ft4>0</ft4><fs4>0</fs4> <fn5>6</fn5><ft5>0</ft5><fs5>0</fs5> <fn6>7</fn6><ft6>0</ft6><fs6>0</fs6> <fn7>8</fn7><ft7>0</ft7><fs7>0</fs7> <fn8>9</fn8><ft8>0</ft8><fs8>0</fs8> <fn9>10</fn9><ft9>0</ft9><fs9>0</fs9> <fn10>11</fn10><ft10>0</ft10><fs10>0</fs10> <fn11>12</fn11><ft11>0</ft11><fs11>0</fs11> <fn12>13</fn12><ft12>0</ft12><fs12>0</fs12> <fn13>14</fn13><ft13>0</ft13><fs13>0</fs13> <fn14>15</fn14><ft14>0</ft14><fs14>0</fs14> <fn15>16</fn15><ft15>0</ft15><fs15>0</fs15> <rn0>0</rn0><rt0>0</rt0> <rn1>1</rn1><rt1>0</rt1> <rn2>2</rn2><rt2>0</rt2> <rn3>3</rn3><rt3>0</rt3> <it0>248</it0><it1>255</it1><it2>255</it2><it3>255</it3><it4>128</it4><it5>1</it5><it6>255</it6><it7>255</it7> <date>28.07.2006</date><time>03:53:53</time><ad>1</ad><ntpsync>-1</ntpsync><i>10</i><f>0</f> <sys>18068255</sys><mem>24368</mem><fw>2.89</fw><dev>ALL4000</dev> <sensorx>5</sensorx><sensory>3</sensory> </data></xml> Answer: I tried to answer you question in the following code with comments: from xml.dom import minidom # Parse the xml xmldoc = minidom.parse('all.xml') # Get all Elements with the name t0. This returns a list of Elements.. Sensor0Elm = xmldoc.getElementsByTagName('t0') # The expectation is to only get one element, so I # grab the first one in the list Sensor0Elm = Sensor0Elm[0] # The element can contain many nodes. The expectation is only # one node containing the data, so we grab the first node and # obtain the data. Sensor0 = Sensor0Elm.childNodes[0].data # Finally we convert the unicode data into a floating point number Sensor0 = float(Sensor0) You can do this same thing in a loop for all of the Sensor data t0, t1, and t2.
Python counter not recognizing dictionary Question: I have a list and a dictionary and I want to ultimately find a sum of the values in the two. For example, I want the code below to return : {gold coin : 45, rope : 1, dagger : 6, ruby : 1} First I right a function to turn the dragonLoot list into a dictionary and then I run a Counter to add the two dictionaries together. However, when I run the code I get the following: {'ruby': 1, 'gold coin': 3, 'dagger': 1} Counter({'gold coin': 42, 'dagger': 5, 'rope': 1}) For some reason it looks like the Counter is not recognizing the dictionary that I create from dragonLoot. Does anyone have any suggestions on what I am doing wrong? Thanks! inv = {'gold coin' : 42, 'rope' : 1, 'dagger' : 5} dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby'] def inventory(item): count = {} for x in range(len(item)): count.setdefault(item[x],0) count[item[x]] = count[item[x]] + 1 print(count) inv2 = inventory(dragonLoot) from collections import Counter dicts = [inv,inv2] c = Counter() for d in dicts: c.update(d) print(c) Answer: You are not returning the count in your inventory method: def inventory(item): count = {} for x in range(len(item)): count.setdefault(item[x],0) count[item[x]] = count[item[x]] + 1 print(count) You are simply printing your inventory calculation. Change that print to a return, or add a return line after the print: def inventory(item): count = {} for x in range(len(item)): count.setdefault(item[x],0) count[item[x]] = count[item[x]] + 1 print(count) return count Adding that to your code and running it, gives this output: Counter({'gold coin': 45, 'dagger': 6, 'rope': 1, 'ruby': 1}) Alternatively, the implementation provided by @nneonneo is optimal.
Configuring mod_wsgi for wamp server on windows Question: I am new in Django development. I have created an Django application and tested in development server i.e. 127.0.0.1:8080/mysite. Then I decided to run this app on Apache server 2.4.9. As all we know the best option is configuring mod_wsgi. My problem is Apache server never runs after configuring as bellow: 1. Keep mod_wsgi.so [ downloaded ](https://modwsgi.googlecode.com/files/mod_wsgi-win32-ap22py27-3.3.so)on 'C:\wamp\bin\apache\apache2.4.9\modules\'. 2. Insert "LoadModule wsgi_module modules/mod_wsgi.so" to httpd.conf 3. Restart wamp server I am using 32 bit of Python,Apache and mod_wsgi. Python is installed for all user. Please help me - Answer: First of all copy mod_wgi in modules folder, then add following to httpd.conf modules list: LoadModule wsgi_module modules/mod_wsgi.so attention that naming is important (should suffix with _module) Add the following to your httpd.conf Include path_to_your_proj/django_wsgi.conf django_wsgi.conf file: WSGIScriptAlias path_to/django.wsgi <Directory project_path> Allow from all Order allow,deny </Directory> Alias /static path_to_static_files django.wsgi file: import os import sys #Calculate the path based on the location of the WSGI script. CURRENT_DIR = os.path.dirname(__file__).replace('\\','/') PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir)) SETTINGS_DIR = os.path.join(PROJECT_ROOT,'proj_dir_name') if PROJECT_ROOT not in sys.path: sys.path.append(PROJECT_ROOT) if SETTINGS_DIR not in sys.path: sys.path.append(SETTINGS_DIR) os.chdir(SETTINGS_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'proj_name.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() **If you're using a virtualenv (that I suggest) do as follows:** httpd.conf file: # virtual env02 <VirtualHost ip-adddress_or_dns:port_if_other_than_80> ServerName just_a_name # like : app01 ServerAlias just_an_alias # like : app01.mydomain.com ErrorLog "logs/env02.error.log" CustomLog "logs/env02.access.log" combined WSGIScriptAlias / direct_path_to_you_wsgi_with_forward_slashes # like: C:/virtual/venv01/proj_name/wsgi.py <Directory proj_dir_with_forward_slashed> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static path_to_static_folder_with_forward_slashes <Directory path_to_static_folder_with_forward_slashes> Require all granted </Directory> </VirtualHost> # end virtual env02 wsgi.py file: activate_this = 'c:/virtual/env02/scripts/activate_this.py' # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('c:/Organizer/virtual/env02/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('c:/virtual/proj_name') sys.path.append('c:/virtual/proj_name/default_app_name') os.environ['DJANGO_SETTINGS_MODULE'] = 'default_app_name.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "default_app_name.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
How could I extract the lengthy config from my controller/main code Question: In my `controller.py` file, I have lots of actions to do. And I also need the following config in dictionary format. But these configs, `params_template`, `header`, .... are really distracting me. How could I save them in another Python file , and load them into current `controller.py` Thanks params_template=""" { "__EVENTTARGET": "AvailabilitySearchInputSearchView$LinkButtonSubmit", "availabilitySearch.SearchInfo.SalesCode": null, "availabilitySearch.SearchInfo.SearchStations[0].DepartureStationCode": FROM_CITY, "availabilitySearch.SearchInfo.SearchStations[0].ArrivalStationCode": TO_CITY, "availabilitySearch.SearchInfo.SearchStations[0].DepartureDate": "11/28/2015", "availabilitySearch.SearchInfo.SearchStations[1].DepartureStationCode": null, "availabilitySearch.SearchInfo.SearchStations[1].ArrivalStationCode": null, "availabilitySearch.SearchInfo.SearchStations[1].DepartureDate": null, "availabilitySearch.SearchInfo.Direction": "Oneway", "fromDate": "1448640000000", "returnDate": null, "fromDate_1": null, "fromDate_2": null, "availabilitySearch.SearchInfo.AdultCount": "1", "availabilitySearch.SearchInfo.ChildrenCount": "0", "availabilitySearch.SearchInfo.InfantCount": "0", "availabilitySearch.SearchInfo.PromoCode": null } """ headers = { 'Origin': 'http://www.flyscoot.com', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.8', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Cache-Control': 'max-age=0', 'Referer': 'http://www.flyscoot.com/index.php/en/', 'Connection': 'keep-alive', 'AlexaToolbar-ALX_NS_PH': 'AlexaToolbar/alxg-3.3', } ... Answer: You can make a separate configuration file from the data you have. For example, in a file `test.ini`, store your data like below: [headers] Origin: 'http://www.flyscoot.com' Accept-Encoding: 'gzip, deflate' Accept-Language: 'en-US,en;q=0.8' Upgrade-Insecure-Requests: '1' User-Agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36' Content-Type: 'application/x-www-form-urlencoded' Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' Cache-Control: 'max-age=0' Referer: 'http://www.flyscoot.com/index.php/en/' Connection: 'keep-alive' AlexaToolbar-ALX_NS_PH: 'AlexaToolbar/alxg-3.3' Once you are done, you can now use [ConfigParser](https://docs.python.org/2/library/configparser.html) to achieve a very flexible control on your data. If you apply the below code with above data, see what you can achieve: from ConfigParser import RawConfigParser parser= RawConfigParser() parser.read('demo.ini') print #To retrieve all the sections print parser.sections() print #to retrieve options of a section print parser.options('headers') #To get value of each option in a section for i in parser.options('headers'): print parser.get('headers',i) Output: ['headers'] ['origin', 'accept-encoding', 'accept-language', 'upgrade-insecure-requests', 'user-agent', 'content-type', 'accept', 'cache-control', 'referer', 'connection', 'alexatoolbar-alx_ns_ph'] 'http://www.flyscoot.com' 'gzip, deflate' 'en-US,en;q=0.8' '1' 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36' 'application/x-www-form-urlencoded' 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' 'max-age=0' 'http://www.flyscoot.com/index.php/en/' 'keep-alive' 'AlexaToolbar/alxg-3.3' Read more about ConfigParser from [Here](https://wiki.python.org/moin/ConfigParserExamples). Hope this helps :)
Python - making my code more economic Question: I need some help on making this code more economical - I am sure that, there are a lot of lines I can cut down on. The code is about a quiz that will ask 10 questions and your score will be outputted at the end. import random studentname=input("what is your name?:") score=0 trueanswer=0 def question(): global operation global number1 global number2 global studentanswer global score number1=random.randrange(1,10) number2=random.randrange(1,10) operation=random.choice(["*","-","+"]) print("what is", number1,operation,number2,"?:") studentanswer=int(input("insert answer:")) def checking(): global score if operation == "*": trueanswer = number1*number2 if studentanswer == trueanswer: print("correct") score=score+1 else: print("incorrect") score=score elif operation == "-": trueanswer = number1-number2 if studentanswer == trueanswer: print("correct") score=score+1 else: print("incorrect") score=score elif operation == "+": trueanswer = number1+number2 if studentanswer == trueanswer: print("correct") score = score+1 else: print("incorrect") score=score def main(): for i in range (10): question() checking() print("your score is", score) main() Answer: You can reduce the entire checking function to this: def checking(): trueanswer = eval(str(number1)+operation+str(number2)) if studentanswer == trueanswer: print("correct") score=score+1 else: print("incorrect") score=score
Python code returning error 'Object is not callable' Question: So, i have started playing around with encryption coding and have been trying to create a unique encryption key based from time. This is my code so far : from threading import Timer from pyclbr import Function import hashlib, binascii, time key1="" buffer1="" buffer2="" class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self.timer=None self.function=function self.interval=interval self.args=args self.kwargs=kwargs self.is_running=False self.start() def _run(self): self.is_running=False self.start() self.function(*self.args,**self.kwargs) def start(self): if not self.is_running: self.timer=Timer(self.interval,self._run) self.timer.start() self.is_running=True def stop(self): self.timer.cancel() self.is_running=False def generateKeys(): global key1 global buffer1 global buffer2 t=int((time.time())/10) t=hashlib.sha1(str(t).encode('utf-8')) t=t.hexdigest() t=t.encode('utf-8') t=binascii.hexlify(t) t=t.decode('utf-8') t=t[0:11] t=int(t)>>5 buffer2=buffer1 buffer1=key1 key1=str(t) def printKeys(): print("Keys : "+key1+" "+buffer1+" "+buffer2) timerStart=RepeatedTimer(10,generateKeys()) #generateKeys(); timerStart2=RepeatedTimer(11,printKeys()) Whenever I run the above code I keep getting the error: Exception in thread Thread-49: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 923, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 1189, in run self.function(*self.args, **self.kwargs) File "/Users/Kiro/Documents/LiClipse Workspace/EncryptionFinal/pkg/enc_keygen.py", line 22, in _run self.function(*self.args,**self.kwargs) TypeError: 'str' object is not callable Exception in thread Thread-50: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 923, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 1189, in run self.function(*self.args, **self.kwargs) File "/Users/Kiro/Documents/LiClipse Workspace/EncryptionFinal/pkg/enc_keygen.py", line 22, in _run self.function(*self.args,**self.kwargs) TypeError: 'NoneType' object is not callable Does anyone have any idea why? What I want is the generateKeys() function to keep running every 10 seconds and the printKeys() function to tell me those keys every 11 seconds (to check that its assigning the keys correctly to the global variables). This is more experimentation than anything but would like help in fixing this code as i would like to get it working. Answer: With your line timerStart=RepeatedTimer(10,generateKeys()) you are handing over the result of the call `generateKeys()` to the `__init__` method. What you actually want to do, is to hand over the function itself. Then you must not call it: timerStart = RepeatedTimer(10, generateKeys)
OBDII data pass to wxpython staticText continues update issues(raspberry PI2) Question: I am total beginner in programming. I already start a small project by using raspberry PI connect to the car OBD port and reading the data to the wxpython GUI. The OBD library I was using from <http://brendan-w.com/work/python-obd> By using the instruction above, I could successful print living rpm data in the python shell line by line. Code is here: import obd import time connection = obd.Async("/dev/rfcomm0") # same constructor as 'obd.OBD()' cmd = obd.commands.RPM connection.watch(cmd) # keep track of the RPM connection.start() # start the async update loop while(True): response_rpm = connection.query(cmd).value print(response_rpm) # non-blocking, returns immediately time.sleep(0.01) #obd.debug.console = True After this, I created the GUI by using wxformbuilder and change to wxpython code. I test the GUI wxpython code in raspberry PI which was no problem. But after add my OBD library code into it and, the whole frame is not working The thing that I want to do is to using the staticText.SetLabel() to display the living data in a while loop. The Code after add OBD library is here :<http://pastebin.com/4HYXn4cv> after running this in the raspberry Pi I only got a gray frame and nothing work Answer: The problem is you blocking the GUI with the `sleep` statement in the tight `while(True)` loop. You are essentially polling the sensor in fixed time intervals. The smart way to poll in `wxPython` is using a timer (`wx.Timer`). You can let call it the content of your `while` loop (do not call more then 20 times per second, more is just useless and will clog up the event loop). The `sleep` has to be removed, because it is eating up all the unscheduled time and is blocking the GUI. _python-odb_ is itself already ansynchronuous ([see](https://github.com/brendanwhitfield/python-OBD/wiki/Async-Querying), second example), but the solution above requires the least restructuring of your program.
print All the keys of a json file in python Question: I have a folder where I have around 20000 son files.I want to find out all the unique keys of each json and I want take an union of all the keys.But I got stuck in the initial step only.I am able to find the keys of a single son file. I have wrote the following code till now: from pprint import pprint import json json_data=open("/Users/akira/out/1.json") jdata = json.load(json_data) for key, value in jdata: pprint("Key:") pprint(key) It is giving me an error as follows: Traceback (most recent call last): File "/Users/akira/PycharmProjects/csci572/linkedbased.py", line 8, in <module> for key, value in jdata: ValueError: need more than 1 value to unpack My json is a nested json.Please suggest me how can I get all the keys. { "a": "Offer", "inLanguage": "et", "availabl": { "a": "Place", "address": { "a": "PostalAddress", "name": "Oklahoma" } }, "description": "Smith and Wesson 686 357 magnum 6 inch barrel wood handle great condition shoots great.", "priceCurrency": "USD", "geonames_address": [ { "a": "PopulatedPlace", "hasIdentifier": { "a": "Identifier", "label": "4552707", "hasType": "http://dig.isi.edu/gazetteer/data/SKOS/IdentifierTypes/GeonamesId" }, "hasPreferredName": { "a": "Name", "label": "Tahlequah" }, "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/4552707", "fallsWithinState1stDiv": { "a": "State1stDiv", "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/State1stDiv/US_OK", "hasName": { "a": "Name", "label": "Oklahoma" } }, "score": 0.5, "fallsWithinCountry": { "a": "Country", "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/Country/US", "hasName": { "a": "Name", "label": "United States" } }, "fallsWithinCountyProvince2ndDiv": { "a": "CountyProvince2ndDiv", "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/CountyProvince2ndDiv/US_OK_021" }, "geo": { "lat": 35.91537, "lon": -94.96996 } } ], "price": 750, "title": "For Sale: Smith &amp; Wesson 686", "publisher": { "a": "Organization", "name": "armslist.com", "uri": "http://dig.isi.edu/weapons/data/organization/armslist" }, "uri": "http://dig.isi.edu/weapons/data/page/13AD9516F01012C5F89E8AADAE5D7E1E2BA97FF9/1433463841000/processed", "seller": { "a": "PersonOrOrganization", "description": "Private Party" } //, ... } Answer: Instead of `for key, value in jdata:`, use `for key, value in jdata.items():` like this: for key, value in data.items(): pprint("Key:") pprint(key) Take a look at the [docs](https://docs.python.org/3/library/stdtypes.html#dict.items) for dict: > **items()** : > > Return a new view of the dictionary’s items ((key, value) pairs). **EDIT:** If you want to get all of the nested keys and not just the top level ones, you could take an approach like those suggested in [another answer](http://stackoverflow.com/a/26167568/996114) like so: def get_keys(dl, keys_list): if isinstance(dl, dict): keys_list += dl.keys() map(lambda x: get_keys(x, keys_list), dl.values()) elif isinstance(dl, list): map(lambda x: get_keys(x, keys_list), dl) keys = [] get_keys(jdata, keys) print(keys) # [u'a', u'inLanguage', u'description', u'priceCurrency', u'geonames_address', u'price', u'title', u'availabl', u'uri', u'seller', u'publisher', u'a', u'hasIdentifier', u'hasPreferredName', u'uri', u'fallsWithinState1stDiv', u'score', u'fallsWithinCountry', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'hasType', u'label', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'lat', u'lon', u'a', u'address', u'a', u'name', u'a', u'description', u'a', u'name', usury'] print(list(set(keys))) # unique list of keys # [u'inLanguage', u'fallsWithinState1stDiv', u'label', u'hasName', u'title', u'hasPreferredName', u'lon', u'seller', u'score', u'description', u'price', u'address', u'lat', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'publisher', u'hasIdentifier', u'name', u'priceCurrency', u'geonames_address', u'hasType', u'availabl', u'uri', u'fallsWithinCountry']
expected two blank lines pep8 warning in python Question: I'm using vim editor as python IDE, below is a simple python program to calculate square root of a number:- import cmath def sqrt(): try: num = int(input("Enter the number : ")) if num >= 0: main(num) else: complex(num) except: print("OOPS..!!Something went wrong, try again") sqrt() return def main(num): squareRoot = num**(1/2) print("The square Root of ", num, " is ", squareRoot) return def complex(num): ans = cmath.sqrt(num) print("The Square root if ", num, " is ", ans) return sqrt() and the warnings are :- 1-square-root.py|2 col 1 C| E302 expected 2 blank lines, found 0 [pep8] 1-square-root.py|15 col 1 C| E302 expected 2 blank lines, found 1 [pep8] 1-square-root.py|21 col 1 C| E302 expected 2 blank lines, found 0 [pep8] Can you please tell why these warnings are coming? [![enter image description here](http://i.stack.imgur.com/m1Rlp.png)](http://i.stack.imgur.com/m1Rlp.png) Answer: import cmath def sqrt(): try: num = int(input("Enter the number : ")) if num >= 0: main(num) else: complex_num(num) except: print("OOPS..!!Something went wrong, try again") sqrt() return def main(num): square_root = num**(1/2) print("The square Root of ", num, " is ", square_root) return def complex_num(num): ans = cmath.sqrt(num) print("The Square root if ", num, " is ", ans) return sqrt() The previous will fix your [PEP8](https://www.python.org/dev/peps/pep-0008/) problems. After your import you need to have 2 new lines before starting your code. Also, between each `def foo()` you need to have 2 as well. In your case you had 0 after import, and you had 1 newline between each function. Part of PEP8 you need to have a newline after the end of your code. Unfortunately I don't know how to show it when I paste your code in here. Pay attention to the naming, it's part of PEP8 as well. I changed `complex` to `complex_num` to prevent confusion with builtin [`complex`](https://docs.python.org/3.0/library/functions.html#complex). In the end, they're only warning, they can be ignored if needed.
Read one specific cell of numpy matrix Question: I wrote a function to see if a matrix is symmetric or not: def issymmetric(mat): if(mat.shape[0]!=mat.shape[1]): return 0 for i in range(mat.shape[0]): for j in range(i): if (mat[i][j]!=mat[j][i]): return 0 return 1 It works well with built-in ndarrays e.g. numpy.ones: import numpy as np a=np.ones((5,5), int) print issymmetric(a) And with numpy arrays: import numpy as np a=np.array([[1, 2, 3], [2, 1 , 2], [3, 2, 1]]) print issymmetric(a) But when it comes to numpy matrixes: import numpy as np a=np.matrix([[1, 2, 3], [2, 1 , 2], [3, 2, 1]]) print issymmetric(a) It gaves me this error: File "issymetry.py", line 9, in issymmetric if (mat[i][j]!=mat[j][i]): File "/usr/lib/python2.7/dist-packages/numpy/matrixlib/defmatrix.py", line 316, in __getitem__ out = N.ndarray.__getitem__(self, index) IndexError: index 1 is out of bounds for axis 0 with size 1 shell returned 1 That's because There is no a[0][1] `a[0]` is `matrix([[1, 2, 3]])`. `a[0][0]` is `matrix([[1, 2, 3]])` too., but there is no `a[0][1]`. How can I fix this issue, without changing the matrix type, or the function? In general, what is the proper way to read and update one specific cell of a numpy matrix? Answer: It is best to use `[i,j]` style indexing in `numpy`. Often you can get by with `[i][j]` when using `np.array`, but not with `np.matrix`. Remember an `np.matrix` is always 2d. In a shell construct a simple 2d array, and try different methods of indexing. Now try it with `np.matrix` arrays. Pay attention to the shape. In [2]: A = np.arange(6).reshape(2,3) In [3]: A[1] # short for A[1,:] Out[3]: array([3, 4, 5]) # shape (3,) In [4]: A[1][2] # short for A[1,:][2] Out[4]: 5 In [5]: M=np.matrix(A) In [6]: M[1] Out[6]: matrix([[3, 4, 5]]) # shape (1,3), 2d In [7]: M[1][2] ... IndexError: index 2 is out of bounds for axis 0 with size 1 correct indexing that works with both In [9]: A[1,2] Out[9]: 5 In [10]: M[1,2] Out[10]: 5 `A[i][j]=...` is also prone to failure when used on the LHS. It only works if the first part `A[i]` returns a `view`. If fails if it produces a `copy`.
Read Excel XML .xls file with pandas Question: I'm aware of a number of previously asked questions, but none of the solutions given work on the reproducible example that I provide below. I am trying to read in `.xls` files from <http://www.eia.gov/coal/data.cfm#production> \-- specifically the **Historical detailed coal production data (1983-2013)** `coalpublic2012.xls` file that's freely available via the dropdown. Pandas cannot read it. In contrast, the file for the most recent year available, 2013, `coalpublic2013.xls` file, works without a problem: import pandas as pd df1 = pd.read_excel("coalpublic2013.xls") but the next decade of `.xls` files (2004-2012) do not load. I have looked at these files with Excel, and they open, and are not corrupted. The error that I get from pandas is: --------------------------------------------------------------------------- XLRDError Traceback (most recent call last) <ipython-input-28-0da33766e9d2> in <module>() ----> 1 df = pd.read_excel("coalpublic2012.xlsx") /Users/jonathan/anaconda/lib/python2.7/site-packages/pandas/io/excel.pyc in read_excel(io, sheetname, header, skiprows, skip_footer, index_col, parse_cols, parse_dates, date_parser, na_values, thousands, convert_float, has_index_names, converters, engine, **kwds) 161 162 if not isinstance(io, ExcelFile): --> 163 io = ExcelFile(io, engine=engine) 164 165 return io._parse_excel( /Users/jonathan/anaconda/lib/python2.7/site-packages/pandas/io/excel.pyc in __init__(self, io, **kwds) 204 self.book = xlrd.open_workbook(file_contents=data) 205 else: --> 206 self.book = xlrd.open_workbook(io) 207 elif engine == 'xlrd' and isinstance(io, xlrd.Book): 208 self.book = io /Users/jonathan/anaconda/lib/python2.7/site-packages/xlrd/__init__.pyc in open_workbook(filename, logfile, verbosity, use_mmap, file_contents, encoding_override, formatting_info, on_demand, ragged_rows) 433 formatting_info=formatting_info, 434 on_demand=on_demand, --> 435 ragged_rows=ragged_rows, 436 ) 437 return bk /Users/jonathan/anaconda/lib/python2.7/site-packages/xlrd/book.pyc in open_workbook_xls(filename, logfile, verbosity, use_mmap, file_contents, encoding_override, formatting_info, on_demand, ragged_rows) 89 t1 = time.clock() 90 bk.load_time_stage_1 = t1 - t0 ---> 91 biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) 92 if not biff_version: 93 raise XLRDError("Can't determine file's BIFF version") /Users/jonathan/anaconda/lib/python2.7/site-packages/xlrd/book.pyc in getbof(self, rqd_stream) 1228 bof_error('Expected BOF record; met end of file') 1229 if opcode not in bofcodes: -> 1230 bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8]) 1231 length = self.get2bytes() 1232 if length == MY_EOF: /Users/jonathan/anaconda/lib/python2.7/site-packages/xlrd/book.pyc in bof_error(msg) 1222 if DEBUG: print("reqd: 0x%04x" % rqd_stream, file=self.logfile) 1223 def bof_error(msg): -> 1224 raise XLRDError('Unsupported format, or corrupt file: ' + msg) 1225 savpos = self._position 1226 opcode = self.get2bytes() XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '<?xml ve' And I have tried various other things: df = pd.ExcelFile("coalpublic2012.xls", encoding_override='cp1252') import xlrd wb = xlrd.open_workbook("coalpublic2012.xls") to no avail. My pandas version: 0.17.0 I've also submitted this as a bug to the pandas github [issues](https://github.com/pydata/pandas/issues/11503) list. Answer: You can convert this Excel XML file programmatically. Requirement: only python and pandas. import pandas as pd from xml.sax import ContentHandler, parse # Reference https://goo.gl/KaOBG3 class ExcelHandler(ContentHandler): def __init__(self): self.chars = [ ] self.cells = [ ] self.rows = [ ] self.tables = [ ] def characters(self, content): self.chars.append(content) def startElement(self, name, atts): if name=="Cell": self.chars = [ ] elif name=="Row": self.cells=[ ] elif name=="Table": self.rows = [ ] def endElement(self, name): if name=="Cell": self.cells.append(''.join(self.chars)) elif name=="Row": self.rows.append(self.cells) elif name=="Table": self.tables.append(self.rows) excelHandler = ExcelHandler() parse('coalpublic2012.xls', excelHandler) df1 = pd.DataFrame(excelHandler.tables[0][4:], columns=excelHandler.tables[0][3])
Extracting value data from multiple JSON strings in a single file Question: I know I am missing the obvious here but I have the following PYTHON code in which I am trying to- * Take a specified JSON file containing multiple strings as an input. * Start at the line 1 and look for the key value of "content_text" * Add the key value to a new dictionary and write said dictionary to a new file * Repeat 1-3 on additional JSON files * * * import json def OpenJsonFileAndPullData (JsonFileName, JsonOutputFileName): output_file=open(JsonOutputFileName, 'w') result = [] with open(JsonFileName, 'r') as InputFile: for line in InputFile: Item=json.loads(line) my_dict={} print item my_dict['Post Content']=item.get('content_text') my_dict['Type of Post']=item.get('content_type') print my_dict result.append(my_dict) json.dumps(result, output_file) OpenJsonFileAndPullData ('MyInput.json', 'MyOutput.txt') However, when run I receive this error: AttributeError: 'str' object has no attribute 'get' Answer: Python is case-sensitive. Item = json.loads(line) # variable "Item" my_dict['Post Content'] = item.get('content_text') # another variable "item" By the way, why don't you load whole file as json at once?
Python Threads object append to list Question: I am learning multi-thread in python.I often see when the program use multi thread,it will append the thread object to one list, just as following: # imports import threading import time def worker(): print "worker...." time.sleep(30) threads = [] for i in range(5): thread = threading.Thread(target=worker) threads.append(thread) thread.start() I think append the thread object to list is good practice, but I don't know why should we do this? Answer: This is common practice. Taking your example: # imports import threading import time def worker(): print "worker...." time.sleep(30) threads = [] for i in range(5): thread = threading.Thread(target=worker) threads.append(thread) thread.start() One might want to wait for every thread to finish its work: for thread in threads: # iterates over the threads thread.join() # waits until the thread has finished work * * * **Without storing** the threads in some data structure you would have to do it (create, start, join, ...) **manually** : thread_1 = threading.Thread(target=worker) (...) thread_n = threading.Thread(target=worker) thread_1.start() (...) thread_n.start() thread_1.join() (...) thread_n.join() * * * As you see (and can imagine): the more you work with the threads, the more "paperwork" would be created if you handle every thread manually. This fastly gets too much of a hassle. Additionally your code would be more confusing and less maintainable.
AttributeError: 'module' object has no attribute 'ensure_future' Question: Hi i am writing a n/w bound server application using python asyncio which can accept a post request. In post request i am accepting a symbol parameter please tell me the best way to deal with n/w bound application.where i am collecting the data from another web api's by sending the post request to them. Following is the code : import asyncio import aiohttp import json import logging # async def fetch_content(url, symbols): # yield from aiohttp.post(url, symbols=symbols) @asyncio.coroutine def fetch_page(writer, url, data): response = yield from aiohttp.post(url, data=data) resp = yield from response.read_and_close() print(resp) writer.write(resp) return @asyncio.coroutine def process_payload(writer, data, scale): tasks = [] data = data.split('\r\n\r\n')[1] data = data.split('\n') data = [x.split(':') for x in data] print(data) data = {x[0]: x[1] for x in data} print(data) # data = data[0].split(':')[1] data = data['symbols'] print(data) data = data.split(',') data_len = len(data) data_first = 0 data_last = scale url = 'http://xxxxxx.xxxxxx.xxx/xxxx/xxxx' while data_last < data_len: tasks.append(asyncio.ensure_future(fetch_page(writer, url,{'symbols': ",".join(data[data_first:data_last])}))) data_first += scale data_last += scale tasks.append(asyncio.ensure_future(fetch_page(writer, url,{'symbols': ",".join(data[data_first:data_last])}))) loop.run_until_complete(tasks) return @asyncio.coroutine def process_url(url): pass @asyncio.coroutine def echo_server(): yield from asyncio.start_server(handle_connection, 'xxxxxx.xxxx.xxx', 3000) @asyncio.coroutine def handle_connection(reader, writer): data = yield from reader.read(8192) if data: message = data.decode('utf-8') print(message) yield from process_payload(writer, message, 400) writer.write_eof() writer.close() #url = 'http://XXXXXXX.xxxxx.xxx/xxxx/xxxxxx/xxx' data = {'symbols': 'GD-US,14174T10,04523Y10,88739910,03209R10,46071F10,77543110,92847N10'} loop = asyncio.get_event_loop() loop.run_until_complete(echo_server()) try: loop.run_forever() finally: loop.close() But i am receiving the following error: future: <Task finished coro=<handle_connection() done, defined at fql_server_async_v2.py:53> exception=AttributeError("'module' object has no attribute 'ensure_future'",)> Traceback (most recent call last): File "/home/user/anugupta/lib/python3.4/asyncio/tasks.py", line 234, in _step result = coro.send(value) File "fql_server_async_v2.py", line 60, in handle_connection yield from process_payload(writer, message, 400) File "/home/user/anugupta/lib/python3.4/asyncio/coroutines.py", line 141, in coro res = func(*args, **kw) File "fql_server_async_v2.py", line 41, in process_payload tasks.append(asyncio.ensure_future(fetch_page(writer, url, {'symbols':",".join(data[data_first:data_last])}))) AttributeError: 'module' object has no attribute 'ensure_future' ^CTraceback (most recent call last): File "fql_server_async_v2.py", line 72, in <module> loop.run_forever() File "/home/user/anugupta/lib/python3.4/asyncio/base_events.py", line 236, in run_forever self._run_once() File "/home/user/anugupta/lib/python3.4/asyncio/base_events.py", line 1017, in _run_once event_list = self._selector.select(timeout) File "/home/user/anugupta/lib/python3.4/selectors.py", line 424, in select fd_event_list = self._epoll.poll(timeout, max_ev) Answer: `ensure_future` was added in _asyncio 3.4.4_ , use `async` for earlier versions. While `async` is deprecated now it will be supported in oversable future.
Python pretty printer for debugging stdlib variables won't work Question: I followed this post for debugging variables in a pretty way [The value of strings doesn't appear in eclipse mars CDT](http://stackoverflow.com/questions/32411117/the-value-of-strings-doesnt- appear-in-eclipse-mars-cdt) however I ended up having an error message as follows: File "/usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19-gdb.py", line 63, in <module> from libstdcxx.v6.printers import register_libstdcxx_printers ImportError: No module named 'libstdcxx' How may I solve the problem? Answer: It looks like your `.gdbinit` does not have the correct contents, or is not being run. Ensure the path added is correct for your machine and that the gdbinit file is running. Since you are getting that error, it should only be necessary to add the correct path to python. Here is a sample trace that first does not work and then does work once the path is corrected: $ cat hello.cc #include <string> using namespace std; int main() { string mystring = "my string here"; return 0; } $ g++ hello.cc -g -o hello.elf $ gdb hello.elf --quiet Reading symbols from hello.elf...done. (gdb) b hello.cc:6 Breakpoint 1 at 0x400863: file hello.cc, line 6. (gdb) r Starting program: /tmp/x/hello.elf Traceback (most recent call last): File "/usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19-gdb.py", line 63, in <module> from libstdcxx.v6.printers import register_libstdcxx_printers ImportError: No module named 'libstdcxx' Breakpoint 1, main () at hello.cc:6 6 return 0; (gdb) p mystring $1 = {static npos = <optimised out>, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x602028 "my string here"}} (gdb) python >import sys >sys.path.insert(0, '/usr/share/gcc-4.8/python/') >end (gdb) r The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: /tmp/x/hello.elf Breakpoint 1, main () at hello.cc:6 6 return 0; (gdb) p mystring $2 = "my string here" (gdb) Version info for the above example: $ g++ --version g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ gdb --version GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1 Copyright (C) 2014 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word". ## When using Eclipse CDT When using Eclipse CDT you need to specify the gdbinit file manually. Eclipse CDT starts GDB with the `--nx` flag, which prevents GDB from picking up any `.gdbinit` files automatically. You instead should specify a CDT appropriate init file in the Launch Configuration: [![gdbinit in cdt](http://i.stack.imgur.com/8n4Eu.png)](http://i.stack.imgur.com/8n4Eu.png) Additionally, you can change your default launch gdbinit for new launch configuration in the Preferences as shown in this dialog: [![default gdb init](http://i.stack.imgur.com/1C1fE.png)](http://i.stack.imgur.com/1C1fE.png)
GDB hangs when multi-threaded python extension is used to debug multi threaded program Question: I'm trying to develop a GDB python extension that defines a command that launches a new thread, in which the user can inspect an arbitrary type of variables. The skeleton of my python extension is this: import gdb import threading def plot_thread(): import time while True: print('Placeholder for a window event loop.') time.sleep(1) pass pass class PlotterCommand(gdb.Command): def __init__(self): super(PlotterCommand, self).__init__("plot", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL) self.dont_repeat() pass def invoke(self, arg, from_tty): plot_thread_instance=threading.Thread(target=plot_thread) plot_thread_instance.daemon=True plot_thread_instance.start() pass pass PlotterCommand() As can be seen, I define a _plot_ command here. When I try to debug the following program, GDB will hang if I: 1. Put a breakpoint anywhere inside the procedure() thread (say, line 9, inside the while loop). 2. Run the command _plot_ after gdb hits the breakpoint. 3. Run _continue_ after that. #include <iostream> #include <thread> using namespace std; void procedure() { cout << "before loop"<<endl; while(1) { cout << "loop iteration"<<endl; } } int main() { thread t(procedure); t.join(); return 0; } The strangest thing is that, if I change this code to call _procedure()_ without launching a thread, GDB never hangs (and the placeholder messages are still printed as I expect). So far, I've tried to run this procedure with GDB versions 7.5.1 and 7.10, but I always experience the same behavior. What am I doing wrong? Aren't daemon threads not supported by GDB? That doesn't seem to be in accordance with what the [section 23.2.2.1 of the documentation](http://docs.adacore.com/gdb-docs/html/gdb_24.html#SEC299) is suggesting: GDB may not be thread safe, but I don't think it should hang after launching such a silly daemon thread. Answer: From [this blog post](http://blog.0x972.info/?d=2015/09/04/08/54/56-bug-with- multiple-threads-running-inside-gdb): > GDB uses this function _(sigsuspend, the function where GDB hangs)_ to wait > for new events from the application execution: when something occurs in the > debuggee (see how debuggers work), the kernel will inform GDB of it by > sending a SIGCHLD signal. When it's received, GDB awakes and check what > happened. > > However, the signal is delivered to GDB process, but not necessarily to its > main thread. And it practise, it occurs often that it's delivered to the > second thread, who doesn't care about it (that's the default behavior), and > continues its life as if nothing occurred. The solution is to configure the thread signal handling behavior, so that only the GDB main thread gets notified by these signals: import gdb import threading import pysigset, signal # Import these packages! def plot_thread(): import time while True: print('Placeholder for a window event loop.') time.sleep(1) pass pass class PlotterCommand(gdb.Command): def __init__(self): super(PlotterCommand, self).__init__("plot", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL) self.dont_repeat() pass def invoke(self, arg, from_tty): with pysigset.suspended_signals(signal.SIGCHLD): # Disable signals here! plot_thread_instance=threading.Thread(target=plot_thread) plot_thread_instance.daemon=True plot_thread_instance.start() pass pass pass PlotterCommand() The _pysigset_ package is required, and can be installed from pip (sudo pip install pysigset).
Can a Tornado WebSocketHandler receive messages asynchronously? Question: On the python side, I've created a `WebSocketHandler`. from tornado import gen from tornado.escape import json_decode from tornado.websocket import WebSocketHandler class Echo(WebSocketHandler): ... @gen.coroutine def on_message(self, message): message = json_decode(message) response = yield self.do_echo(message) self.write_message(response) @gen.coroutine def do_echo(self, message): # emulate long, blocking call sleep(randint(0, 5)) raise gen.Return(message) On the javascript side, I start multiple clients (different browsers) at the same time with: var ws = new WebSocket('ws://localhost:5000/echo'); ws.onmessage = function (evt) { console.log(JSON.parse(evt.data)); } for (var i = 0; i < 10; i++) { var msg = { messageid: i, payload: 'An echo message.' }; ws.send(JSON.stringify(msg)); } All clients, as expected, finish at roughly the same time. However, each client's received messages are logged in the exact order (`messageid`) that they were sent as if the `WebSocketHandler` is queuing messages. Python logs on the server side reflect this as well. So then, my questions are: * Why is each message read and returned in the order that it was sent? * Is it possible to circumvent this queuing behavior? How? * Am I completely missing something embarrassingly basic? Note that this is not the real code but a reasonable facsimile. Answer: You must never run "long, blocking calls" on the IOLoop thread, because that blocks everything else. That `sleep` call (or whatever it's standing in for), must either be rewritten to be asynchronous or handed off to another thread (which is fairly easy with `concurrent.futures.ThreadPoolExecutor`). See <http://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with- time-sleep-running-in-parallel> for more on this.
Trouble incrementing variables in Python 3.4.3 Tkinter with labels and buttons Question: So I have started making a survival game, but ran into a problem pretty fast. I wanted to make a button that should will go and collect a certain time, (as in shrubs), and when hit, the amount of shrub shown on the screen will increment by 15. But every time I try to make it, the amount of shrub goes from 0 to 15, which is good, but then it won't go any higher. Here is the code I have currently: import tkinter as tk root = tk.Tk() # have root be the main window root.geometry("550x300") # size for window root.title("SURVIVE") # window title shrubcount = 0 def collectshrub(): global shrubcount shrubcount += 15 shrub.config(text=str(shrubcount)) def shrub(): shrub = tk.Label(root, text='Shrub: {}'.format(shrubcount), font=("Times New Roman", 16)).place(x=0, y=0) def shrubbutton(): shrubbutton = tk.Button(root, command=collectshrub, text="Collect shrub", font=('Times New Roman', 16)).place(x=0, y=200) shrub() # call shrub to be shown root.mainloop() # start the root window Any help would be nice! Thanks tons Getting these errors shrub.config(text=str(shrub count)) AttributeError: 'NoneType' object has no attribute 'config' Answer: Inkblot has the right idea. Your shrub function sets the number of shrubs at 0. Clicking "Collect Shrub" calls forces shrub to output shrubcount but at no time is the shrubcount variable updated. A cleaner version of your code, that does what you want may look like this: import ttk from Tkinter import * class Gui(object): root = Tk() root.title("Survive") shrubs = IntVar() def __init__(self): frame = ttk.Frame(self.root, padding="3 3 12 12") frame.grid(column=0, row=0, sticky=(N, W, E, S)) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) ttk.Label(frame, text="Shrubs:").grid(column=0, row=0, sticky=W) ttk.Entry(frame, textvariable=self.shrubs, width=80).grid(column=0, row=2, columnspan=4, sticky=W) ttk.Button(frame, command=self.add_shrubs, text="Get Shrubs").grid(column=6, row=3, sticky=W) def add_shrubs(self): your_shrubs = self.shrubs.get() self.shrubs.set(your_shrubs + 15) go = Gui() go.root.mainloop() Notice that all add_shrub does is increment shrubcount by 15. Displaying the number of shrubs is handled by the shrubs label object.
Why can't I use true/false/null in a Python object fed to json.dumps()? Question: * I'm tring to decode(I think that's the right word) JSON to convert true, false, null to True, False, None for python * I know I need the `json` library * I followed [this thread's answer](http://stackoverflow.com/a/11977844/4462930) but it didn't get me anywhere. * I still receive the same error: `NameError: name 'true' is not defined` ... import json raw_json = { 'a':'aa', 'b':'bb', 'c':'cc', 'd':true, 'e':false, 'f':null } json_dump = json.dumps(raw_json) json_load = json.loads(json_dump) What am I doing wrong/need to do? Also, I'm coming from a javascript background so it has been a pain trying to learn the conventions and terms. What are the 'u's prepending each json key in the other thread's link following 'd2'? Answer: In your JSON variable `raw_json`, you need to capitalize `True` and `False`. In Python, Boolean values are capitalized for true and false. When you serialize it into JSON, they will be lower cased. Also, `None` is the Python equivalent of `null`. When you perform a JSON dump, you are taking in a Python dictionary (which must be valid Python) and outputting a string which follows the JSON standard. The conversion visually changes the upper cased True, False, and None into their JSON equivalents true, false, and null. To answer why there are `u`s on the strings, that is referring to the strings being Unicode strings.
Get url link from the web using python Question: So I am trying to write a script that will allow to search for a certain place and get the coordinates. I am very limited with the packages because I'm not allow download any packages that does not already comes with python 2.7. import webbrowser location = input('Enter your location: ') webbrowser.open('https://www.google.com/maps/place/'+location) My browser opens and the url changes to https://www.google.com/maps/place/Washington+Monument/@38.8894838,-77.0374678,17z/data=!3m1!4b1!4m2!3m1!1s0x89b7b7a1be0c2e7f:0xe97346828ed0bfb8 From there, I want to get the new url so I can strip it to just have the coordinates. Anyone one know how to get the new url the browser creates? Answer: >>> import urllib >>> text = urllib.urlopen('https://www.google.com/maps/place/washington').read() >>> p = text.find('cacheResponse([[[') >>> p 228 >>> text[228: 300] 'cacheResponse([[[26081602.52827102,-95.67706800000001,37.06250000000001]' >>>
Import function for class-wide docstring tests Question: I am developing on a larger project which has a class with docstrings tests for each method. Each docstring contains a few examples/tests. The docstrings make use of a function in another module frequently and I would like to import it once and have it available in every docstring function test. For example, if this is `tests.py` class A(object): def test1(self): """ >>> myfunc() 1 """ pass def test2(self): """ >>> myfunc() 1 """ pass And this is `funcs.py` from tests import A # Do stuff with A def myfunc(): return 1 I would like avoid modifying the above code to this: class A(object): def test1(self): """ >>> from funcs import myfunc >>> myfunc() 1 """ pass def test2(self): """ >>> from funcs import myfunc >>> myfunc() 1 """ pass And instead do something like a class level docstring module import. I also can't just import the function directly in the module because in my case that would create a circular dependency. Doctests are invoked using `python -m doctest tests.py` which has this error output: * * * File "tests.py", line 4, in tests.A.test Failed example: myfunc() Exception raised: Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run compileflags, 1) in test.globs File "<doctest tests.A.test[0]>", line 1, in <module> myfunc() NameError: name 'myfunc' is not defined ******************************************** 1 items had failures: 1 of 1 in tests.A.test ***Test Failed*** 1 failures. It succeeds using the test code that has imports. For anyone wondering why I might want to do this, my real world code is at <https://github.com/EntilZha/ScalaFunctional/blob/master/functional/pipeline.py>. The function I want to import is `seq` since it is an entrypoint alias to the class `Sequence`. I would prefer to use `seq` in the docstrings since very importantly they serve as documentation examples, `seq` has additional behavior, and I want to start running them as my test suite to make sure they stay up to date. Answer: From the [`doctest` man page](https://docs.python.org/2/library/doctest.html#what-s-the-execution- context), "_By default, each time doctest finds a docstring to test, it uses a shallow copy of M‘s globals_ ". All you have to do is make sure that `myfunc` is present in the module's globals, perhaps by adding from funcs import myfunc to the top of the file.
How to generate a bar chart of occurrences per year in matplotlib python? Question: I have list of dates and I want to generate a bar chart with matplotlib in python. 2007-05-06 2007-05-11 2007-06-01 2007-06-04 2007-06-06 2007-09-01 2007-10-06 2007-11-06 2007-11-07 … And I want to provide this two type of bar char [![enter image description here](http://i.stack.imgur.com/zHihj.png)](http://i.stack.imgur.com/zHihj.png) I can use this code but I'm searching for more efficient code because as you can see I have years between 2007 and 2012 and sometimes this range can be wider def plot(): #--- the two samples --- samples1 = [1, 1, 1, 3, 2, 5, 1, 10, 10, 8] samples2 = [6, 6, 6, 1, 2, 3, 9, 12 ] samples3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12] N = 12 # number of bins hist1 = np.array([0] * N ) hist2 = np.array([0] * N ) hist3 = np.array([0] * N ) #--- create two histogram. Values of 1 go in Bin 0 --- for x in samples1: hist1[x-1] += 1 for x in samples2: hist2[x-1] += 1 for x in samples3: hist3[x-1] += 1 #--- display the bar-graph --- width = 1 p1 = plt.bar( np.arange(0,N)+0.5, hist1, width, color='#9932cc' ) p2 = plt.bar( np.arange(0,N)+0.5, hist2, width, color='#ffa500', bottom=hist1 ) p3 = plt.bar( np.arange(0,N)+0.5, hist3, width, color='#d2691e', bottom=hist1+hist2 ) plt.legend( (p1[0], p2[0], p3[0]), ( 'hist1', 'hist2', 'hist3' ) ) plt.xlabel( 'Bins' ) plt.ylabel( 'Count' ) #plt.axis([1, 46, 0, 6]) plt.xticks( np.arange( 1,N+1 ) ) plt.axis( [width/2.0, N+width/2.0, 0, max( hist1+hist2+hist3)] ) plt.show() Can you help me to generate this kind of chart !? Thank you Answer: You can use `numpy` `histogram` to get the data in bar format directly, which should be faster than looping in python. As a minimal example based on your data above, import numpy as np import matplotlib.pyplot as plt #--- the two samples --- samples1 = [1, 1, 1, 3, 2, 5, 1, 10, 10, 8] samples2 = [6, 6, 6, 1, 2, 3, 9, 12 ] samples3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12] N = 12 # number of bins hist1 = np.array([0] * N ) hist2 = np.array([0] * N ) hist3 = np.array([0] * N ) #--- create two histogram. Values of 1 go in Bin 0 --- hist1, n = np.histogram(samples1,N) hist2, n = np.histogram(samples2,N) hist3, n = np.histogram(samples3,N) #--- display the bar-graph --- width = 1 p1 = plt.bar( np.arange(0,N)+0.5, hist1, width, color='#9932cc' ) p2 = plt.bar( np.arange(0,N)+0.5, hist2, width, color='#ffa500', bottom=hist1 ) p3 = plt.bar( np.arange(0,N)+0.5, hist3, width, color='#d2691e', bottom=hist1+hist2 ) plt.legend( (p1[0], p2[0], p3[0]), ( '2010', '2011', '2012' ) ) plt.xlabel( 'Bins' ) plt.ylabel( 'Count' ) import datetime months = [((datetime.date(2010, i, 1).strftime('%B'))[:3]) for i in range(1,13)] plt.xticks( np.arange( 1,N+1 ),months ) plt.axis( [width/2.0, N+width/2.0, 0, max( hist1+hist2+hist3)] ) plt.show()
Removing curly brackets from a tuple in python Question: I'm creating a test module to eventually import into a larger program using python. My test module uses tkinter widgets to display a list of numbers that increases when a button is pressed. import tkinter import math #Defining Variables global Counter Counter = 0 global ArrayDisplay1 ArrayDisplay1 = Counter #Defining the GUI class simpleapp_tk(tkinter.Tk): def __init__(self, parent): tkinter.Tk.__init__(self, parent) self.parent = parent self.initialise() def initialise(self): #Creating the GUI self.grid() self.resizable(False, False) self.labelVariableArray3 = tkinter.StringVar() ArrayLabel3 = tkinter.Label(self, textvariable=self.labelVariableArray3, anchor='w',bg='white') ArrayLabel3.grid(column=2, row=5, columnspan=5, sticky='EW') self.labelVariableArray3.set("") ArrayButton2 = tkinter.Button(self, text=u"Next Number", command=self.ArrayClick2) ArrayButton2.grid(column=2, row=3, sticky='EW') def ArrayClick2(self): global Counter global ArrayDisplay1 Counter = Counter + 1 if Counter == 1: ArrayDisplay1 = (Counter) self.labelVariableArray3.set(ArrayDisplay1) else: ArrayDisplay1 = (ArrayDisplay1, ",", Counter) self.labelVariableArray3.set(ArrayDisplay1) if __name__ == "__main__": app = simpleapp_tk(None) app.title('Arrays, Sorts and Searches') app.mainloop() my problem lies within the 'ArrayClick2' module. I wrote the code hoping to have the output be: 1 1, 2 1, 2, 3 and so on. However I instead get: 1 1, 2 {1, 2}, 3 {{1, 2}, 3}, 4 and so forth. I tried using replace and strip, but neither of these seem to work with a tuple. Can someone tell me of another way to create this list or just to remove the brackets? Also I've been told by the head of the program development that I can't use the python function named list because for some reason that I couldn't understand it was incompatible with the main program. Answer: You can concatenate tuples using + for example `tuple0 = tuple0 + (element,)`. To get your result from tuple you can use join `''.join(str(element) + ',' for element in ArrayDisplay1)[:-1]` [:-1] to ignore last element which is `,` Without changing your code, Changes are: line 9 : `ArrayDisplay1 = (Counter,)` ArrayDisplay1 must be a tuple if else statement in ArrayClick2 function: if Counter == 1: ArrayDisplay1 = (Counter,) self.labelVariableArray3.set(ArrayDisplay1) else: ArrayDisplay1 +=(Counter,) self.labelVariableArray3.set(''.join(str(i)+',' for i in ArrayDisplay1)[:-1]) I hope it will be useful.
How to set apache2 environment variables in wsgi file (Flask) Question: Currently I work with Flask micro framework. How to set Environment variables in wsgi file? I have done this in apache2 envvars file like this: export PRODROOT=${PRODROOT:-/home/peter/Lv-164.UI/ecomap} export PYSRCROOT=${PYSRCROOT:-${PRODROOT}/src/python} export CONFROOT=${CONFROOT:-${PRODROOT}/etc} export PYTHONPATH=${PRODROOT}/src/python How I can do that in wsgi file? Thanks for your attention. Answer: The wsgi file is just a Python file, so you can use `os.environ` to set environment variables for your code. E.g. in your wsgi file: import os os.environ['PRODROOT'] = '/home/peter/Lv-164.UI/ecomap' os.environ['PYSRCROOT'] = os.environ['PRODROOT'] + '/src/python' os.environ['CONFROOT'] = os.environ['PRODROOT'] + '/etc' os.environ['PYTHONPATH'] = os.environ['PRODROOT'] + '/src/python' from yourpackage.yourapp import app as application I'm not sure that setting `PYTHONPATH` will work in this scenario (though it's worth a try). If you're using `mod_wsgi` then you can set it with the `WSGIPythonPath` directive. <https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonPath>
Execute Python script within Jupyter notebook using a specific virtualenv Question: I would like to execute a long running Python script from within a Jupyter notebook so that I can hack on the data structures generated mid-run. The script has many dependencies and command line arguments and is executed with a specific virtualenv. Is it possible to interactively run a Python script inside a notebook from a specified virtualenv (different to that of the Jupyter installation)? Thanks! Answer: I found this link to be very useful: <https://ocefpaf.github.io/python4oceanographers/blog/2014/09/01/ipython_kernel/> Make sure that you pip install jupyter into your virtualenv. In case the link goes away later, here's the gist: You need to create a new kernel. You specify your kernel with a JSON file. Your kernels are usually located at `~/.ipython/kernels`. Create a directory with the name of your virtualenv and create your kernel.json file in it. For instance, one of my paths looks like `~./ipython/kernels/datamanip/kernel.json` Here's what my kernel.json file looks like: { "display_name": "Data Manipulation (Python2)", "language": "python", "codemirror_mode": { "version": 3, "name":"ipython" }, "argv": [ "/Users/ed/.virtualenvs/datamanip/bin/python", "-c", "from IPython.kernel.zmq.kernelapp import main; main()", "-f", "{connection_file}" ] } I am not certain exactly what the codemirror_mode object is doing, but it doesn't seem to do any harm.
Python - How to redirect stderr to a file? Question: The following code I got from <http://forums.devshed.com/python- programming-11/redirect-stdout-stderr-file-500952.html> which tells how to redirect a stderr to a file. I tried it but the error message is not getting saved to the file. While I am not using sys.stderr = file_err the error is displayed in the idle terminal, when I am assigning file_err to sys.stderr the error is not displayed in the idle terminal, and it is not being copied to the file_name.log import sys original_stderr = sys.stderr file_err = open('file_name.log', 'w') # I tried with .txt also sys.stderr = file_err print(list[file]) # Used to create a NameError sys.stderr = original_stderr file_err.close() Am I supposed to write it to the file or is there an error in the program? Answer: Your code works fine (I mean: the redirection to stderr.). Note however than from python3.5 you can use [`contextlib.redirect_stderr`](https://docs.python.org/3.5/library/contextlib.html#contextlib.redirect_stderr)'s context manager to do this: from contextlib import redirect_stderr with open('filename.log', 'w') as stderr, redirect_stderr(stderr): # errors from here are logged to the file. Note: * You don't have to explicitly call `close`. * You don't have to explicitly save the old stderr and restore it at the end. By the way: instead of saving the old `stderr` value you could simply use `sys.__stderr__`.
Cython wrapper not fast enough, how to speed it up? Question: I have a C++ library and I want to wrap some of its functionality in python. The function splits the given character array into 5 parts, not actual splitting but the structure we pass a pointer to, contains the information about the parts after the function returns. The 5 structures each contain 2 integers, one denoting the beginning of the part, and the other, the part's length. The python wrapper should accept a python string and return a dictionary or tuple of the 5 parts(as python strings also). My current approach of calling the function and then splitting the python string based on the sub-part information using python slicing syntax has not yielded any significant speed gains. I realize that there are many similar questions, but none of those cases have been helpful to me. The Cython definition code is - cdef extern from "parse.h" namespace util ctypedef struct part: int begin; int len; ctypedef struct Parsed: part part1; part part2; part part3; part part4; part part5; void ParseFunc(const char* url, int url_len, Parsed* parsed) The Cython code is - cimport parseDef def parse(url, url_len): cdef parseDef.Parsed parsed parseDef.parseFunc(url, url_len, &parsed) part1 = url[parsed.part1.begin:parsed.part1.begin+parsed.part1.len] #similar code for other parts return (part1, part2, part3, part4, part5) Typical string size for this wrapper will be 10-50 generally. Answer: You can get a small benefit from doing the indexing on `const char*` instead of the string cimport parseDef def parse(url, url_len): cdef const char* url_as_char_ptr = url # automatic conversion cdef parseDef.Parsed parsed parseDef.parseFunc(url, url_len, &parsed) part1 = url_as_char_ptr[parsed.part1.begin:parsed.part1.begin+parsed.part1.len] #similar code for other parts return (part1, part2, part3, part4, part5) I don't think you can beat this by much is that, mostly because the c-code generated is actually pretty efficient. The indexing line is translated to something like __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_url_as_char_ptr + idx1, idx2 - idx1) (noting that I've replaced `parsed.part1.begin` with `idx1` just for the sake of readability and because I'm testing this with slightly different code since I don't have `parseFunc`. You can check your exact code with `cython -a yourfile.pyx` and looking at the html output). This is basically just calling the Python c-api string constructor function. That will necessarily make a copy of the string it is passed, but you can't avoid that (the Python string constructor always makes a copy). That doesn't leave a lot of overhead to remove.
VS2015 + Python 3.4 File IO Question: I am trying to self teach python by writing a quick script using Visual Studio 2015 and Python 3.4 to parse an Recuva output log file. > Starting Point Promo 2013 - Compilation-HD.mp4 15020953 M:\Videos For Future > Use\ Note the input file has multiple spaces between the filename, filesize and output path. import os import re fileName = os.path.join( "C:\\", "Users", "temp", "Downloads", "deleted_files.txt" ) pattern = r""" (.*) \s{2,} \d+ \s{2,} (.*) """ regex = re.compile( pattern, re.X ) try: with open( fileName ) as inputFile: # Loop over lines and extract variables of interest for line in inputFile: print( line ) match_obj = regex.match( line ) if match_obj: # pattern matched name = match_obj.group( 1 ) # group 1 is the first object directory = match_obj.group( 2 ) print( name + "=>" + directory ) else: print( "Line not matched: " + line ) inputFile.close() except (OSError, IOError) as err: raise IOError( "%s: %s" % (fileName, err.strerror)) Each time I run the code, I get an error on print( line ) and the debugger in VS2015 only shows newlines. Am I missing something in my file opening and read operation? Be kind, this is my first python script! The error message I get back is _ÿþ-'charmap' codec can't encode character '\xfe' in position 1: character maps to_ EDIT (Updated Trial): I receive the same error message if I run the script from the command line: > File "RecuvaRenamer.py", line 21 in print( line ) File > "C:\Python34\lib\encodings\cp437.py", line 19, in encode return > codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: > 'charmap' codec can't encode character '\xfe' in position 1 character maps > to Answer: Ok, nevermind. Nothing wrong with the code. The input file was not encoded in UTF-8. Converted input to UTF-8 format and the file "almost" parses correctly.
Dice-rolling game doesn't change results Question: Doing a dice Rolling game in python, and whenever I start my second round I still end up getting the same dice results from the previous round. import random import time #gets the dice side def roll_dice(sides): dice_results = list() for side in sides: roll_result = random.randint(1,side+1) dice_results.append(roll_result) return dice_results #pulls a dice out from the list def dice_fell(roll_result): player1_dice = player1_dice_results player2_dice = player2_dice_results for item in player1_dice: if item % 4 == 0: player1_dice.remove(item) return player1_dice for item in player2_dice: if item % 4 == 0: player2_dice.remove(item) return player2_dice # variables dice_set1=[4, 6, 8, 10, 12, 20, 100] dice_set2=[4, 6, 8, 10, 12, 20, 100] player1_dice_results = roll_dice(dice_set1) player2_dice_results = roll_dice(dice_set2) player1_final_results = dice_fell(player1_dice_results) player2_final_results = dice_fell(player2_dice_results) player1_total= sum(player1_dice_results) player2_total= sum(player2_dice_results) player1_score = 0 player2_score = 0 while player1_score < 3 or player2_score < 3: # This part just announces what happens exit= input(str("Press Enter to start! Press 'q' to leave after each round! \n")) if exit != "q": print("Let's begin! Be careful for the small table!") elif exit == "q": quit() print("You are rolling...") time.sleep(2) print("You have rolled: ",player1_final_results) if len(player1_final_results) < 7: print("Sorry player 1, some of your dice have fallen off the table!") print() print("Your total is: ",player1_total) print() print("Player 2 is rolling...") time.sleep(2) print("Player 2 has rolled:" ,player2_final_results) if len(player2_final_results) < 7: print("Sorry player 2, some of your dice have fallen off the table!") print() print("Player 2's total is: ",player2_total) print() if player1_total > player2_total: print() print("You have won the round with,",player1_total,"!"), player1_score += 1 print("Your score is: ",player1_score) elif player2_total > player1_total: print() print("Player 2 has won the round with,",player2_total,"!"), player2_score += 1 print("Player 2's score is: ",player2_score) if player1_score == 3: print("Congratulations, you won!") elif player2_score == 3: print("Player 2 wins! Better luck next time champ!") Answer: I believe that I've fixed the indentation problems. I _have_ reproduced the problem. As Kevin said, your immediate problem is that you roll the dice only once, _before_ you enter your **while** loop. Here's what it looks like with the rolls inside the loop, but after the player decides whether to continue. dice_set1=[4,6,8,10,12,20,100] dice_set2=[4,6,8,10,12,20,100] player1_score = 0 player2_score = 0 while player1_score < 3 or player2_score < 3: # This part just announces what happens exit = raw_input(str("Press Enter to start! Press 'q' to leave after each round! \n")) if exit != "q": print("Let's begin! Be careful for the small table!") elif exit == "q": quit() player1_dice_results = roll_dice(dice_set1) player2_dice_results = roll_dice(dice_set2) player1_final_results = dice_fell(player1_dice_results) player2_final_results = dice_fell(player2_dice_results) player1_total= sum(player1_dice_results) player2_total= sum(player2_dice_results) print("You are rolling...") ... # remainder of code omitted * * * That said, do note that you have several other problems with the program. You won't terminate until _both_ players have won three times -- use **and** instead of **or** in the **while** condition. Most of my other comments are more appropriate for the codeReview group; you might post there when you're done debugging.
Python - Remove the last character in a text file Question: I m generating a file text as you can see below and i m trying to suppress the last character "," of this file text after generating it but i cant... *Nset, nset 0570, 0571, 0572, 0573, 0574, 0575, 0576, 0577, 0578, 0579, 0579 0580, 0581, 0582, 0583, 0584, 0585, 0586, 0587, 0588, 0589, 0589 0590, 0591, I have found on Stack this kind of code, but, it doesnt work... import sys with open(sys.argv[1]) as f, open('out.txt', 'w') as out: for line in f: out.write(line.split()[-1]+'\n') \----EDIT LATER---- My code to generate the file text : fichier_write.write("*Nset,") fichier_write.write("\n") compt = 0 for i in range(0,node_label.size): if Eleme_CI[i]!=0: fichier_write.write("%.4i, "%(Eleme_CI[i])), compt = compt + 1 if compt == 10: fichier_write.write("%.4i"%(Eleme_CI[i])), fichier_write.write("\n") compt = 0 fichier_write.close() Answer: import re # get text into a string \Z is the end of a string in regex with open('data') as f: text = f.read() text = re.sub(r'.\Z',r'',text) print(text) Money amount left 39.0 *Nset, nset 0570, 0571, 0572, 0573, 0574, 0575, 0576, 0577, 0578, 0579, 0579 0580, 0581, 0582, 0583, 0584, 0585, 0586, 0587, 0588, 0589, 0589 0590, 0591
Create and import helper functions in tests without creating packages in test directory using py.test Question: **Question** How can I import helper functions in test files without creating packages in the `test` directory? **Context** I'd like to create a test helper function that I can import in several tests. Say, something like this: # In common_file.py def assert_a_general_property_between(x, y): # test a specific relationship between x and y assert ... # In test/my_test.py def test_something_with(x): some_value = some_function_of_(x) assert_a_general_property_between(x, some_value) _Using Python 3.5, with py.test 2.8.2_ **Current "solution"** I'm currently doing this via importing a module inside my project's `test` directory (which is now a package), but I'd like to do it with some other mechanism if possible (so that my `test` directory doesn't have packages but just tests, and the tests can be run on an installed version of the package, as is recommended [here in the py.test documentation on good practices](http://pytest.org/latest/goodpractises.html#choosing-a-test-layout- import-rules)). Answer: my option is to create an extra dir in `tests` dir and add it to pythonpath in the conftest so. tests/ helpers/ utils.py ... conftest.py setup.cfg in the `conftest.py` import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers') in `setup.cfg` [pytest] norecursedirs=tests/helpers this module will be available with `import utils', only be careful to name clashing.
fast way to transpose and concat csv files in python? Question: I am trying to transpose multiple files of the same format and concatinating them into 1 big CSV file. I wanted to use numpy for transposing as its a really fast way of doing it but it somehow skips all my headers which i need. These are my files: testfile1.csv time,topic1,topic2,country 2015-10-01,20,30,usa 2015-10-02,25,35,usa testfile2.csv time,topic3,topic4,country 2015-10-01,40,50,uk 2015-10-02,45,55,uk This is my code to transpose and merge all csv files into 1 big file: from numpy import genfromtxt import csv file_list=['testfile1.csv','testfile2.csv'] def transpose_append(csv_file): my_data = genfromtxt(item, delimiter=',',skip_header=0) print my_data, "my_data, not transposed" if i == 0: transposed_data = my_data.T print transposed_data, "transposed_data" for row in transposed_data: print row, "row from first file" csv_writer.writerow([row]) else: transposed_data = my_data.T for row in transposed_data: print row, "row from second file" csv_writer.writerow([row][:1]) with open("combined_transposed_file.csv", 'wb') as outputfile: csv_writer = csv.writer(outputfile) for i,item in enumerate(file_list): transpose_append(item) outputfile.close() This is the output of a print. It show transposing work somewhat but its missing my headers: [[ nan nan nan nan] [ nan 20. 30. nan] [ nan 25. 35. nan]] my_data, not transposed [[ nan nan nan] [ nan 20. 25.] [ nan 30. 35.] [ nan nan nan]] transposed_data This is my expected output: ,2015-10-01,2015-10-02,country topic1,20,25,usa topic2,30,35,usa topic3,40,45,uk topic4,50,55,uk Answer: There are various ways of handling headers in `genfromtxt`. The default is to treat them as part of the data: In [6]: txt="""time,topic1,topic2,country ...: 2015-10-01,20,30,usa ...: 2015-10-02,25,35,usa""" In [7]: data=np.genfromtxt(txt.splitlines(),delimiter=',',skip_header=0) In [8]: data Out[8]: array([[ nan, nan, nan, nan], [ nan, 20., 30., nan], [ nan, 25., 35., nan]]) But since the default dtype is float, the strings all appear as `nan`. You can treat them as headers - the result is a structured array. The headers now appear in the `data.dtype.names` list. In [9]: data=np.genfromtxt(txt.splitlines(),delimiter=',',names=True) In [10]: data Out[10]: array([(nan, 20.0, 30.0, nan), (nan, 25.0, 35.0, nan)], dtype=[('time', '<f8'), ('topic1', '<f8'), ('topic2', '<f8'), ('country', '<f8')]) With `dtype=None`, you let it choose the dtype. Based on the strings in the 1st line, it loads everything as `S10`. In [11]: data=np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None) In [12]: data Out[12]: array([['time', 'topic1', 'topic2', 'country'], ['2015-10-01', '20', '30', 'usa'], ['2015-10-02', '25', '35', 'usa']], dtype='|S10') This matrix can be transposed, and printed or written to a csv file: In [13]: data.T Out[13]: array([['time', '2015-10-01', '2015-10-02'], ['topic1', '20', '25'], ['topic2', '30', '35'], ['country', 'usa', 'usa']], dtype='|S10') Since I'm using `genfromtxt` to load, I could use `savetxt` to save: In [26]: with open('test.txt','w') as f: np.savetxt(f, data.T, delimiter=',', fmt='%12s') np.savetxt(f, data.T, delimiter=';', fmt='%10s') # simulate a 2nd array ....: In [27]: cat test.txt time, 2015-10-01, 2015-10-02 topic1, 20, 25 topic2, 30, 35 country, usa, usa time;2015-10-01;2015-10-02 topic1; 20; 25 topic2; 30; 35 country; usa; usa
Trying to find if a line intersects with another, but it is failing even when the lines do intersect Question: At the start of my program I draw six straight vertical line segments, and then after I randomly draw as many line segments as the user wants. Every time it is drawn, I check if it does intersect one of those six segments. The problem is, even if they intersect, it never returns True. I am using Python, and used y = mx + b for both lines to find a common point where they do intersect, and check if it lies on both of the line segments. Here is the code: import random import turtle wn = turtle.Screen() wn.setworldcoordinates(-50, -50, 50.5, 50) intersectCount = 0 stickCount = 0 def drawLines(): draw = turtle.Turtle() for x in range(-5, 6): if x % 2 != 0: draw.penup() draw.goto(x * 10, 50) draw.pendown() draw.goto(x * 10, -50) def drawStick(): draw = turtle.Turtle() draw.color("Brown") rand = random.Random() stickLength = 10 # sticks are 10 units long x1 = rand.randint(-50, 50) y1 = rand.randint(-50, 50) x2 = 0 y2 = 0 direction = rand.randint(1, 4) if(direction == 1): x2 = x1 + stickLength y2 = y1 - stickLength elif(direction == 2): x2 = x1 - stickLength y2 = y1 + stickLength elif(direction == 3): x2 = x1 + stickLength y2 = y1 + stickLength else: x2 = x1 - stickLength y2 = y1 - stickLength draw.penup() draw.goto(x1, y1) draw.pendown() draw.goto(x2, y2) global stickCount stickCount += 1 for x in range(-5, 6): if x % 2 != 0: if (checkStick(x * 10, 50, x * 10, -50, x1, y1, x2, y2)): global intersectCount intersectCount += 1 break def drop(): sticks = input("Enter how many sticks you would like to drop: ") sticks = int(sticks) for x in range(0, sticks): drawStick() print(str(stickCount) + " sticks were dropped") print("There were " + str(intersectCount) + " sticks that intersected") def checkStick(x1, y1, x2, y2, sX1, sY1, sX2, sY2): #greatest and least x coordinates from the line greatestX = 0 leastX = 0 if(x1 == x2 or x1 > x2): greatestX = x1 leastX = x2 else: greatestX = x2 leastX = x1 #same thing but with y's greatestY = 0 leastY = 0 if(y1 == y2 or y1 > y2): greatestY = y1 leastY = y2 else: greatestY = y2 leastY = y1 #same thing but with stick x's gStickX = 0 lStickX = 0 if(sX1 == sX2 or sX1 > sX2): greatestX = sX1 leastX = sX2 else: greatestX = sX2 leastX = sX1 #same thing but with stick x's gStickY = 0 lStickY = 0 if(sY1 == sY2 or sY1 > sY2): greatestY = sY1 leastY = sY2 else: greatestY = sY2 leastY = sY1 #y = mx + b #the stick stickSlope = ((sY2 - sY1) / (sX2 - sX1)) # m, or the slope stickIntercept = sY1 - (stickSlope * sX1) # b = y - (mx) #the line lineSlope = 0 if(x2 - x1 != 0): # m, or the slope lineSlope = (y2 - y1) / (x2 - x1) lineIntercept = y1 - (lineSlope * x1) # b = y - (mx) #set the two formulas equal to each other, find x and then y, that is where they intersect#this will be reset as the x of intersection x = (lineIntercept - stickIntercept) / (stickSlope - lineSlope) # solving for x by getting the x's on one side, and other numbers on one side, then dividing out whatever number x is being multiplied by to get what x is y = ((stickSlope * x) + stickIntercept) # back to y = mx + b now that we have all the variable to find y #points intersect at x, y if(stickSlope == lineSlope): return False # parallel else: #checking if it is within the line segment if(x <= greatestX and x >= leastX): if(y <= greatestY and y >= leastY): #checking if it is within the stick segment if(x <= gStickX and x >= lStickX): if(y <= gStickY and x >= lStickY): return True else: return False else: return False else: return False else: return False drawLines() drop() raw_input() # waits for the user to click a key to exit Answer: Replace your function which checks for segments collision (`checkStick`) with def checkStick(x1, y1, x2, y2, x3, y3, x4, y4): dx1 = x2 - x1 dy1 = y2 - y1 dx2 = x4 - x3 dy2 = y4 - y3 if dx1 * dy2 - dx2 * dy1 == 0: # Segments are on parallel lines. There will be intersection if segments # are collinear and they give intersecting projection to both axis segments_collinear = (y3 - y1) * dx1 == dy1 * (x3 - x1) collision_ox = max(x1, x2) >= min(x3, x4) and min(x1, x2) <= max(x3, x4) collision_oy = max(y1, y2) >= min(y3, y4) and min(y1, y2) <= max(y3, y4) return segments_collinear and collision_ox and collision_oy s = (dx1 * (y1 - y3) - dy1 * (x1 - x3)) / (dx1 * dy2 - dx2 * dy1) t = (dx2 * (y1 - y3) - dy2 * (x1 - x3)) / (dx1 * dy2 - dx2 * dy1) return 0 <= s <= 1 and 0 <= t <= 1 If you want to understand the _idea_ behind formula for parameters `s` and `t`, look at [this answer](http://stackoverflow.com/a/565282/595870) (parameters `u` ant `t` there) Basically, if `0 <= s <= 1 and 0 <= t <= 1`, then intersection of two lines (which are extensions of our segments) is at both of our segments. Otherwise it is outside. Special case. If `dx1 * dy2 - dx2 * dy1 == 0` then our lines are parallel. We will have intersection only if both segments are on the same line ([3rd point is collinear with first two](http://math.stackexchange.com/questions/38338/methods-for-showing-three- points-in-mathbbr2-are-colinear-or-not)) and they actually intersect on this line (sements projections to both axis intersect).
Regular Expression String Mangling Efficiency in Python - Explanation for Slowness? Question: I'm hoping someone can help explain why Python's re module seems to be so slow at chopping up a very large string for me. I have string ("content") that is very nearly 600k bytes in size. I'm trying to hack off just the beginning part of it, a variable number of lines, delimited by the text ">>>FOOBAR<<<". The literal completion time is provided for comparison purposes - the script that this snippet is in takes a bit to run naturally. The first and worst method: import re content = "Massive string that is 600k and contains >>>FOOBAR<<< about 200 lines in" content = re.sub(".*>>>FOOBAR<<<", ">>>FOOBAR<<<", content, flags=re.S) Has a completion time of: real 6m7.213s While a wordy method: content = "Massive string that is 600k and contains >>>FOOBAR<<< about 200 lines in" newstir = "" flag = False for l in content.split('\n'): if re.search(">>>FOOBAR<<<", l): flag = True #End if we encountered our flag line if flag: newstir += l #End loop through content content = newstir Has an expected completion time of: real 1m5.898s And using a string's .split method: content = "Massive string that is 600k and contains >>>FOOBAR<<< about 200 lines in" content = content.split(">>>FOOBAR<<<")[1] Also has an expected completion time of: real 1m6.427s What's going on here? Why is my re.sub call so ungodly slow for the same string? Answer: There is no good way to do it with a pattern starting either with `.*` or `.*?` in particular with large data, since the first will cause a lot of backtracking and the second must test for each taken character if the following subpattern fails (until it succeeds). Using a non-greedy quantifier isn't faster than using a greedy quantifier. I suspect that your ~600k content data are in a file at the beginning. Instead of loading the whole file and storing its content to a variable, work line by line. In this way you will preserve memory and avoid to split and to create a list of lines. Second thing, if you are looking for a literal string, don't use a regex method, use a simple string method like `find` that is faster: with open('yourfile') as fh: for line in fh: result += line if line.find('>>>FOOBAR<<<') > -1: break If `>>>FOOBAR<<<` isn't a simple literal string but a regex pattern, in this case compile the pattern before: pat = re.compile(r'>>>[A-Z]+<<<') with open('yourfile') as fh: for line in fh: result += line if pat.search(line): break
Downloading csv file from a website using python Question: I have the following website [yahoo finance](https://in.finance.yahoo.com/q/hp?s=%5EBSESN&a=03&b=3&c=1997&d=10&e=4&f=2015&g=d). I want to set a date range on that page for e.g April 3rd 1997 to 4th November 2015. Once I set the date range I get a link to download the file as `csv` on that page, below the tables. I want to download the csv file. But I want all of this to be done programmatically. How do I achieve this using python. Answer: This might be helpful : import requests import shutil def callme(): url = "http://real-chart.finance.yahoo.com/table.csv?s=%5EBSESN&a=03&b=3&c=1997&d=10&e=4&f=2015&g=d&ignore=.csv" r = requests.get(url, verify=False,stream=True) if r.status_code!=200: print "Failure!!" exit() else: r.raw.decode_content = True with open("file1.csv", 'wb') as f: shutil.copyfileobj(r.raw, f) print "Success" if __name__ == '__main__': callme() How to get this URL ? You can get the list of API calls in any website by right click-> Inspect Element ->Network. Now when you make any request from browser, it will list out all the API calls. You can split the date according to your need and pass it in the URL. You need to do some research about how Yahoo passes the date in URL. Edit 1: This script will run over HTTP and HTTPS.
The app returned an error when the Google Cloud Endpoints server attempted to communicate with it Question: Hi I'm new to Google App Engine and Cloud Endpoints. I have an app engine that serves web application. And I want to use it with Cloud Endpoints. So I just added source codes from here: <https://cloud.google.com/appengine/docs/python/endpoints/getstarted/backend/write_api> But I cannot deploy app and get this error message: Checking if Endpoints configuration has been updated. 07:13 AM Failed to update Endpoints configuration. The app returned an error when the Google Cloud Endpoints server attempted to communicate with it. 07:13 AM See the deployment troubleshooting documentation for more information: https://developers.google.com/appengine/docs/python/endpoints/test_deploy#troubleshooting_a_deployment_failure And this is my source codes import endpoints from protorpc import messages from protorpc import message_types from protorpc import remote package = 'Hello' class Greeting(messages.Message): """Greeting that stores a message.""" message = messages.StringField(1) class GreetingCollection(messages.Message): """Collection of Greetings.""" items = messages.MessageField(Greeting, 1, repeated=True) STORED_GREETINGS = GreetingCollection(items=[ Greeting(message='hello world!'), Greeting(message='goodbye world!'), ]) @endpoints.api(name='helloworld', version='v1') class HelloWorldApi(remote.Service): """Helloworld API v1.""" @endpoints.method(message_types.VoidMessage, GreetingCollection, path='hellogreeting', http_method='GET', name='greetings.listGreeting') def greetings_list(self, unused_request): return STORED_GREETINGS ID_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.IntegerField(1, variant=messages.Variant.INT32)) @endpoints.method(ID_RESOURCE, Greeting, path='hellogreeting/{id}', http_method='GET', name='greetings.getGreeting') def greeting_get(self, request): try: return STORED_GREETINGS.items[request.id] except (IndexError, TypeError): raise endpoints.NotFoundException('Greeting %s not found.' % (request.id,)) APPLICATION = endpoints.api_server([HelloWorldApi]) exactly same with tutorial and my app.yaml application: my application id version: application version runtime: python27 api_version: 1 threadsafe: true handlers: - url: /data script: MLP.app login: admin - url: /insert_db script: MLP.app login: admin - url: /validete script: MLP.app login: admin - url: /stylesheets static_dir: stylesheets - url: /js static_dir: js - url: /.* script: MLP.app - url: /_ah/spi/.* script: MLP_mobile_backend.APPLICATION libraries: - name: webapp2 version: latest - name: jinja2 version: latest - name: pycrypto version: latest - name: endpoints version: 1.0 MLP.py is just web service with webapp2 How can I solve the problem? Answer: From the `app.yaml` line `script: MLP_mobile_backend.APPLICATION`, it means your code sample must live in a `MLP_mobile_backend.py` file at the root of your app engine project . ├── app.yaml ├── MLP.py └── MLP_mobile_backend.py with an endpoint api server named `APPLICATION` defined in that file just as in your code sample above. APPLICATION = endpoints.api_server([HelloWorldApi]) After those requirements are fulfilled, this line points to how to access your endpoints: @endpoints.api(name='helloworld', version='v1') So for example, let's say you're running your devserver's module on port 8080 and you want to access the **hellogreeting** path: @endpoints.method(message_types.VoidMessage, GreetingCollection, path='hellogreeting', http_method='GET', name='greetings.listGreeting') you can use [_cURL_](http://curl.haxx.se) or [_httpie_](http://httpie.org/) or _your browser_ to locally navigate to the devserver's default module at <http://localhost:8080/_ah/api/helloworld/v1/hellogreeting> or with Google's API explorer at <http://localhost:8080/_ah/api/explorer> which should result in this response body: { "items": [ { "message": "hello world!" }, { "message": "goodbye world!" } ] } Once you get it set up locally, you can then deploy it. [More here](https://cloud.google.com/appengine/docs/python/endpoints/test_deploy)
How to use ctypes void ** pointer in python3 Question: I would to connect a spectrometer by its DLL, one of function is defined as UINT UAI_SpectrometerOpen(unsigned int dev, void** handle, unsigned int VID, unsigned int PID) from document, dev is Specify the index for the spectrometer handle is Return to the pointer of handle of the spectrometer VID is Provide specified VID PID is Provide specified PID dev, VID, PID are known, but I don't know how to set handle. my current code is as import ctypes otoDLL = ctypes.CDLL('UserApplication.dll') spectrometerOpen = otoDLL.UAI_SpectrometerOpen spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(c_void_p), ctypes.c_uint, ctypes.c_uint) spectrometerOpen.restypes = ctypes.c_uint handle = ctypes.c_void_p errorCode = spectrometerOpen(0, handle, 1592, 2732) When I run above code, I got error as runfile('C:/Users/Steve/Documents/Python Scripts/otoDLL.py', wdir='C:/Users/Steve/Documents/Python Scripts') Traceback (most recent call last): File "<ipython-input-1-73fe9922d732>", line 1, in <module> runfile('C:/Users/Steve/Documents/Python Scripts/otoDLL.py', wdir='C:/Users/Steve/Documents/Python Scripts') File "C:\Users\Steve\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile execfile(filename, namespace) File "C:\Users\Steve\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "C:/Users/Steve/Documents/Python Scripts/otoDLL.py", line 5, in <module> spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(c_void_p), NameError: name 'c_void_p' is not defined I am not familiar with ctypes and C, can anyone help me to resolve this matter. Thanks a lot. Answer: According to your error output: File "C:/Users/Steve/Documents/Python Scripts/otoDLL.py", line 5, in <module> spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(c_void_p), You forget to put `ctypes` before `c_void_p`, thus: spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(ctypes.c_void_p), ctypes.c_uint, ctypes.c_uint) According to your function signature , the handle parameter is a pointer to a `void*`, thus you need to pass it like this: import ctypes otoDLL = ctypes.CDLL('UserApplication.dll') spectrometerOpen = otoDLL.UAI_SpectrometerOpen spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(ctypes.c_void_p), ctypes.c_uint, ctypes.c_uint) spectrometerOpen.restypes = ctypes.c_uint # declare HANDLE type, which is a void* HANDLE = ctypes.c_void_p # example: declare an instance of HANDLE, set to NULL (0) my_handle = HANDLE(0) #pass the handle by reference (works like passing a void**) errorCode = spectrometerOpen(0, ctypes.byref(my_handle), 1592, 2732) Note: this is just an example, you should check the documentation of the `spectrometerOpen` function to see what exactly it is awaiting exactly for the `handle` parameter (can it be NULL, what type is it exactly, etc.).
Django FSM state transition error Question: from datetime import datetime from django.db import models from django_fsm import FSMField, transition class Network(models.Model): name = models.CharField(max_length=100, unique=True) prefix = models.CharField(max_length=20, default='') country = models.CharField(max_length=50, default='') client_wsdl = models.TextField(blank=True, default='') class Meta: db_table = 'network' def __unicode__(self): return u'{0}'.format(self.name) class SmsMessage(models.Model): #Define State Machine received, started, failed, submitted, completed = "received", "started", "failed", "submitted", "completed" STATE_CHOICES = ( (received, received), (started, started), (failed, failed), (submitted, submitted), (completed, completed), ) message_id = models.CharField(max_length=50) sender_id = models.CharField(max_length=50, default='') msisdn = models.CharField(max_length=50) message = models.CharField(max_length=200) priority = models.CharField(max_length=50) status = models.CharField(max_length=20, default='') state = FSMField(default=received, choices=STATE_CHOICES, protected=True) callback = models.CharField(max_length=200, default='') network = models.ForeignKey(Network, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'sms_message' def __unicode__(self): return self.message_id @transition(field=state, source='received', target=started) def started(self): ''' Change message request to started state. ''' return @transition(field=state, source='started', target=failed) def failed(self): ''' For started requests that cannot be submitted to Network hence in a failed state. ''' return @transition(field=state, source=started, target=submitted) def submitted(self): ''' Change message request to submitted state. ''' return @transition(field=state, source='submitted', target=completed) def completed(self): ''' Request was sucessfully submited to mno and a response returned. ''' return From my code above, submitted state transitions fail with this error: Traceback (most recent call last): worker_1 | File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task worker_1 | R = retval = fun(*args, **kwargs) worker_1 | File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__ worker_1 | return self.run(*args, **kwargs) worker_1 | File "/app/sms_platform/apps/api/tasks.py", line 176, in run worker_1 | return self._send_sms(msisdn, message, request_id, correlation_id, mno, sender_id, pk=pk) worker_1 | File "/app/sms_platform/apps/api/tasks.py", line 126, in _send_sms worker_1 | sms_obj.submitted() worker_1 | File "/usr/local/lib/python2.7/dist-packages/django_fsm/__init__.py", line 512, in _change_state worker_1 | return fsm_meta.field.change_state(instance, func, *args, **kwargs) worker_1 | File "/usr/local/lib/python2.7/dist-packages/django_fsm/__init__.py", line 304, in change_state worker_1 | object=instance, method=method) worker_1 | TransitionNotAllowed: Can't switch from state 'started' using method 'submitted' The only difference is that submitted in transition source is NOT quoted like the others. Otherwise if I quote 'submitted', it works okay. Am puzzled at this since all the states are defined at the beginning of the class. Answer: The problem that you have `started` variable redifined to the method name class SmsMessage(models.Model) ... started, ...= ... "started", ... @transition(field=state, source='received', target=started) def started(self): # <- LOL .... @transition(field=state, source=started, target=submitted) def submitted(self): .... >>> print(SmsMessage.started) <unbound method SmsMessage.started>
Unable to create a sample VPC using boto. socket.gaierror: [Errno -2] Name or service not known Question: I am a beginner and am trying to create a VPC using boto. [root@localhost orchestration]# cat create-vpc.py #!/usr/bin/python import boto.vpc import pdb from boto.vpc import VPCConnection #c = VPCConnection() c=boto.vpc.connect_to_region('us-east-1') vpc = c.create_vpc('10.0.12.0/16') subnet = c.create_subnet(vpc.id, '10.0.12.1/24') This is my sample script to create a VPC. However i am getting an error "gaierror: [Errno -2] Name or service not known" Here is the complete traceback. Traceback (most recent call last): File "create-vpc.py", line 13, in <module> vpc = c.create_vpc('10.0.12.0/16') File "/usr/lib/python2.7/site-packages/boto/vpc/__init__.py", line 135, in create_vpc return self.get_object('CreateVpc', params, VPC) File "/usr/lib/python2.7/site-packages/boto/connection.py", line 1192, in get_object response = self.make_request(action, params, path, verb) File "/usr/lib/python2.7/site-packages/boto/connection.py", line 1116, in make_request return self._mexe(http_request) File "/usr/lib/python2.7/site-packages/boto/connection.py", line 913, in _mexe self.is_secure) File "/usr/lib/python2.7/site-packages/boto/connection.py", line 705, in get_http_connection return self.new_http_connection(host, port, is_secure) File "/usr/lib/python2.7/site-packages/boto/connection.py", line 747, in new_http_connection connection = self.proxy_ssl(host, is_secure and 443 or 80) File "/usr/lib/python2.7/site-packages/boto/connection.py", line 792, in proxy_ssl int(self.proxy_port)), timeout) File "/usr/lib64/python2.7/socket.py", line 559, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno -2] Name or service not known I have also configured the ~/.boto file with the access and the secret keys. FYI, [root@localhost orchestration]# cat ~/.boto [Credentials] aws_access_key_id=<my-access-key> aws_secret_access_key=<my-secret-key> I have also gone through some other similar questions that suggests to add yun.local entry in the /etc/hosts file. Here are my /etc/hosts file and /etc/resolv.conf files. [root@localhost orchestration]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.240.1 yun.local [root@localhost orchestration]# cat /etc/resolv.conf # Generated by NetworkManager search comviva.com nameserver 172.19.1.10 nameserver 172.19.1.11 nameserver 172.16.1.20 # NOTE: the libc resolver may not support more than 3 nameservers. # The nameservers listed below may not be recognized. nameserver 172.16.1.22 Also o/p of telnet [root@localhost orchestration]# telnet yun.local 80 Trying 192.168.240.1... telnet: connect to address 192.168.240.1: Connection refused FYI, [root@localhost orchestration]# nslookup ec2.us-east-1.amazonaws.com Server: 172.19.1.11 Address: 172.19.1.11#53 Name: ec2.us-east-1.amazonaws.com Address: 54.239.26.182 [root@localhost orchestration]# [root@localhost orchestration]# [root@localhost orchestration]# dig ec2.us-east-1.amazonaws.com ; <<>> DiG 9.9.4-RedHat-9.9.4-18.el7 <<>> ec2.us-east-1.amazonaws.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24619 ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4000 ;; QUESTION SECTION: ;ec2.us-east-1.amazonaws.com. IN A ;; ANSWER SECTION: ec2.us-east-1.amazonaws.com. 0 IN CNAME ec2.amazonaws.com. ec2.amazonaws.com. 48 IN A 54.239.20.1 ;; Query time: 153 msec ;; SERVER: 172.19.1.10#53(172.19.1.10) ;; WHEN: Tue Nov 17 23:32:12 EST 2015 ;; MSG SIZE rcvd: 90 I also tried to create this VPC using Ansible and as expected got the same error there as well. How do i overcome this gaierror ? Any answers shall be heartily appreciated. Answer: To create your VPCConnection (or really any service connection object) in boto, you should use this incantation: import boto.vpc c = boto.vpc.connect_to_region('us-east-1') # or whatever In this way, you are guaranteed to have a properly initialized VPCConnection object pointing to the right endpoint.
Pass variable from .py file to .kv file Question: I'm new to Kivy and am kind of learning on the job. I've a basic understanding of how to utilise various widgets and nest layouts. The code is as follows (saved as GUI.py):- from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.properties import ListProperty, NumericProperty, StringProperty class TestScreen(Screen): pass class VariableScreen(Screen): pass class SummaryScreen(Screen): pass class ProgressScreen(Screen): pass class CompletedResultsScreen(Screen): pass class SavedResultsScreen(Screen): pass class ScreenManagement(ScreenManager): pass GUI_code = Builder.load_file("GUI.kv") class GUIWindow(App): #App class is inherited sampletext = StringProperty("Five times Five") def build(self): return GUI_code if __name__ == "__main__": GUIWindow().run() The GUI.kv file contains the following: #: import FadeTransition kivy.uix.screenmanager.FadeTransition ScreenManagement: transition: FadeTransition() TestScreen: VariableScreen: SummaryScreen: ProgressScreen: CompletedResultsScreen: SavedResultsScreen: <TestScreen>: name: "Test_Screen" FloatLayout: Label: text: "Test" size_hint: 0.1,0.1 pos_hint: {"right":0.5,"top":1} Label: text: app.sampletext size_hint: 0.1,0.1 pos_hint: {"right":0.1,"top":1} Button: on_release: app.root.current = "Saved_Results_Screen" text: "Saved Results" size_hint: 0.1,0.1 pos_hint: {"left":1,"bottom":1} font_size: 15 Button: on_release: app.root.current = "Variable_Screen" text: "Variable" size_hint: 0.1,0.1 pos_hint: {"right":1,"bottom":1} font_size: 15 Only the relevant part of the .kv file is posted. Some strings have to be passed from the .py file to the .kv file. The question was addressed in the below link: [Pass variable value from main.py to .kv file](http://stackoverflow.com/questions/31370346/pass-variable-value-from- main-py-to-kv-file?lq=1&newreg=bdc6a866403649bdbb6b16334a2db62b) Based on the suggestion there, I placed sampletext in the GUIWindow class using the StringProperty class. (Also tried a simple string sampletext = "Five times Five". Gives the same error) The code does not run when the text property under the second label in is set to text: app.sampletext (An application window with white space opens. It is non responsive. The python kernel needs to be reloaded to shut it) The following error message is displayed 18: pos_hint: {"right":0.5,"top":1} 19: Label: >> 20: text: app.sampletext 21: size_hint: 0.1,0.1 22: pos_hint: {"right":0.1,"top":1} ... AttributeError: 'NoneType' object has no attribute 'bind' It runs properly when the text property is set to text: "Five times Five" Could someone be kind enough to explain what is going wrong? Answer: I can't find any documentation describing why, but it seems like the parser is trying to access `app.sampletext` when you parse the file, which you are doing before your `App` class is even defined, let alone created. Move the `Builder.parse` line into your `build(self):` function and it will work fine.
Pygame - rect appears and immediately disappears Question: I am rewriting my question [Pygame - rect disappears before I reach it](http://stackoverflow.com/questions/33506991/pygame-rect-disappears-before- i-reach-it) because I think I have not described it clearly. Full code: #! /usr/bin/python import pygame, time, sys, random, os from pygame.locals import * from time import gmtime, strftime pygame.init() w = 640 h = 400 screen = pygame.display.set_mode((w, h),RESIZABLE) clock = pygame.time.Clock() x = y = 100 def starting(): basicfont = pygame.font.SysFont(None, 48) text = basicfont.render('Starting...', True, (255, 255, 255), (0, 0, 255)) textrect = text.get_rect() textrect.centerx = screen.get_rect().centerx textrect.centery = screen.get_rect().centery screen.fill((0, 0, 255)) screen.blit(text, textrect) pygame.display.update() def taskbar(): basicfont = pygame.font.SysFont(None, 24) pygame.draw.rect(screen, ((0, 255, 0)), (0, h-40, w, 40), 0) text = basicfont.render(strftime("%Y-%m-%d", gmtime()), True, (0, 0, 0)) text2 = basicfont.render(strftime("%H:%M:%S", gmtime()), True, (0, 0, 0)) screen.blit(text, (w - 100, h - 37)) screen.blit(text2, (w - 100, h - 17)) logoimage = pygame.image.load("C:\Users\chef\Desktop\logo.png").convert() logoimage = pygame.transform.scale(logoimage, (40, 40)) screen.blit(logoimage, (0, h-40),) def start(): button1, button2, button3 = pygame.mouse.get_pressed() mousex, mousey = pygame.mouse.get_pos() if 0 < mousex < 40 and h-40 < mousey < h: if button1: pygame.draw.rect(screen, ((255, 0, 0)), (0, int(h/2), int(w/6), int(h/2)-40), 0) pygame.display.update() starting() #time.sleep(2) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type==VIDEORESIZE: w = event.dict['size'][0] h = event.dict['size'][1] screen=pygame.display.set_mode(event.dict['size'],RESIZABLE) screen.fill((255, 255, 255)) taskbar() start() pygame.display.update() clock.tick(60) Just like my original question, when I press logoimage.png and the red rectangle pops up, it shows for a second then immediately disappears. How can I make it so that the rect will stay until I press outside of it? Answer: You should move the `screen.fill((255, 255, 255))` out of the `while` loop. This is causing problems, because each time the program loops, it colors the display white, writing over whatever you had there before. One way to work around this is to move the `screen.fill((255, 255, 255))` out of the loop and place it before the `pygame.draw.rect` function. This will color the screen before you place the rect, and will not continue to fill it. For instance: if button1: screen.fill((255, 255, 255)) pygame.draw.rect(screen, ((255, 0, 0)), (0, int(h/2), int(w/6), int(h/2)-40), 0) You could also move it elsewhere or come up with a way to draw rect every loop after you fill the window. Hope this helped.
Return multiple matches of regular expression within a string in python pandas Question: I am trying to extract all matches contained in between "><" in a string The code below only returns the first match in the string. In: import pandas as pd import re df = pd.Series(['<option value="85">APOE</option><option value="636">PICALM1<']) reg = '(>([A-Z])\w+<)' df2 = df.str.extract(reg) print df2 Out: 0 1 0 >APOE< A I would like to return "APOE" and "PICALM1" and not just "APOE" Thanks for your help! Answer: No need for pandas. df = '<option value="85">APOE</option><option value="636">PICALM1<' reg = '>([A-Z][^<]+)<' print re.findall(reg,df) ['APOE', 'PICALM1'] Parsing HTML with regular expressions may not be the best idea, have you considered using BeautifulSoup?
File txt: FileNotFoundError: [Errno 2] No such file or directory Question: i have a txt file and if i try to open it python says: runfile('/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python/untitled0.py', wdir='/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python') Traceback (most recent call last): File "<ipython-input-30-b4bdfdd17ca2>", line 1, in <module> runfile('/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python/untitled0.py', wdir='/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python') File "/Users/costanzanaldi/anaconda/lib/python3.4/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile execfile(filename, namespace) File "/Users/costanzanaldi/anaconda/lib/python3.4/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python/untitled0.py", line 13, in <module> in_file = open("POLO_SCIENTIFICO_(LAMMA).txt","r") FileNotFoundError: [Errno 2] No such file or directory: 'POLO_SCIENTIFICO_(LAMMA).txt' 1)the file EXISTS! 2)the path is correct! It is in the desktop! Answer: You need to change your directory to your desktop in order to access the file. You'd do that using the `os` module, like this: import os os.chdir("/path/to/Desktop")
Convert python string with newlines and tabs to dictionary Question: I'm a bit stuck with this particular problem I'm having. I have a working solution, but I don't think it's very Pythonic. I have a raw text output like this: Key 1 Value 1 Key 2 Value 2 Key 3 Value 3a Value 3b Value 3c Key 4 Value 4a Value 4b I'm trying to make a dictionary: { 'Key 1': ['Value 1'], 'Key 2': ['Value 2'], 'Key 3': ['Value 3a', 'Value 3b', 'Value 3c'], 'Key 4': ['Value 4a', 'Value 4b'] } The raw output can be made into a string and it looks something like this: my_str = " Key 1\n\tValue 1 \nKey 2\n\tValue 2 \nKey 3\n\tValue 3a \n\tValue 3b \n\tValue 3c \nKey 4\n\tValue 4a \n\tValue 4b " So the Values are separated by \n\t and the Keys are separated by \n If I try to do something like this: dict(item.split('\n\t') for item in my_str.split('\n')) It doesn't parse it correctly because it splits the 'n' in \n\t as well. So far I have something like this: #!/usr/bin/env python str = "Key 1\n\tValue 1\nKey 2\n\tValue 2\nKey 3\n\tValue 3a \n\tValue 3b \n\tValue 3c\nKey 4\n\tValue 4a \n\tValue 4b" output = str.replace('\n\t', ',').replace('\n',';') result = {} for key in output.split(';'): result[key.split(',')[0]] = key.split(',')[1:] print result Which returns: {'Key 1': ['Value 1'], 'Key 2': ['Value 2'], 'Key 3': ['Value 3a ', 'Value 3b ', 'Value 3c'], 'Key 4': ['Value 4a ', 'Value 4b']} However, this looks quite gross to me, I'm just wondering if there is a pythonic way to do this. Any help would be super appreciated! Answer: Batteries are included - `defaultdict` deals with auto-hydrating a new key's value as a list and we leverage `str`'s `iswhitespace` method to check for indentation (otherwise we could have used a regular expression): from collections import defaultdict data = """ Key 1 Value 1 Key 2 Value 2 Key 3 Value 3a Value 3b Value 3c Key 4 Value 4a Value 4b """ result = defaultdict(list) current_key = None for line in data.splitlines(): if not line: continue # Filter out blank lines # If the line is not indented then it is a key # Save it and move on if not line[0].isspace(): current_key = line.strip() continue # Otherwise, add the value # (minus leading and trailing whitespace) # to our results result[current_key].append(line.strip()) # result is now a defaultdict defaultdict(<class 'list'>, {'Key 1': ['Value 1'], 'Key 2': ['Value 2'], 'Key 3': ['Value 3a', 'Value 3b', 'Value 3c'], 'Key 4': ['Value 4a', 'Value 4b']})
How to pass a python array to an oracle stored procedure? Question: I have a problem. When I pass a Python array: self.notPermited = [2,3] This is my procedure def select_ids_entre_amistades(self,cod_us,ids_not): lista = [] try: cursor = self.__cursor.var(cx_Oracle.CURSOR) print ids_not data = self.__cursor.arrayvar(cx_Oracle.NUMBER, ids_not) print data l_query = self.__cursor.callproc("SCHEMA.PROC_SELECT_IDS_ENT_AMISTADES", [cursor,cod_us,data]) lista = l_query[0] return lista except cx_Oracle.DatabaseError as ex: error, = ex.args print(error.message) return lista The problem is when I call that procedure using this: self.select_ids_entre_amistades(int_id,self.notPermited) I visualize in the console the following message: > PLS-00306: wrong number or types of arguments in call to 'PROC In the database I create the array object like this: CREATE TYPE SCHEMA.ARRAY_ID_FRIENDS AS TABLE OF INT; The Oracle stored procedure starts like this: CREATE OR REPLACE PROCEDURE FACEBOOK.PROC_SELECT_IDS_ENT_AMISTADES (CONSULTA OUT SYS_REFCURSOR,COD_US IN INT, IDS_FRIEND IN SCHEMA.ARRAY_ID_FRIENDS) I don't know what the problem is, I believe `cx_Oracle.NUMBER` is not integer but there aren't other numeric type. Thanks in advance. Answer: When you look at the `cx_Oracle` documentation, it says you can create the arrays like this; > > Cursor.arrayvar(dataType, value[, size]) > > > Create an array variable associated with the cursor of the given type and > size and return a variable object (Variable Objects). The value is either an > integer specifying the number of elements to allocate or it is a list and > the number of elements allocated is drawn from the size of the list. If the > value is a list, the variable is also set with the contents of the list. If > the size is not specified and the type is a string or binary, 4000 bytes > (maximum allowable by Oracle) is allocated. This is needed for passing > arrays to PL/SQL (in cases where the list might be empty and the type cannot > be determined automatically) or returning arrays from PL/SQL. You may pass your arrays as long as array types are compatible with your `PL/SQL` procedure's parameter. Here is a simple example to create an array. >>> myarray=cursor.arrayvar(cx_Oracle.NUMBER,range(0,10)) >>> myarray <cx_Oracle.NUMBER with value [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]> Here is a [link](http://osdir.com/ml/python.db.cx- oracle/2005-06/msg00014.html) (belongs to 2005 seems outdated, not sure) showing how to create arrays in `PL/SQL` side. ## EDIT: I added a complete example below showing how to pass `arrayvar` and other variable types. I tested the code with Oracle 10g and Python 2.7. I hope this helps. from __future__ import print_function import cx_Oracle as cxo conn = cxo.connect("<YOUR TNS STRING>") cursor = conn.cursor() ref_cursor = cursor.var(cxo.CURSOR) cod_us = cursor.var(cxo.NUMBER, 10) ids_friend = cursor.arrayvar(cxo.NUMBER, range(0, 10)) ids_friend_sum = cursor.var(cxo.NUMBER) cursor.execute(''' DECLARE TYPE REF_CURSOR IS REF CURSOR; TYPE ARRAY_ID_FRIENDS IS TABLE OF INT INDEX BY BINARY_INTEGER; FUNCTION test(CONSULTA OUT REF_CURSOR, COD_US IN INT, IDS_FRIEND IN ARRAY_ID_FRIENDS) RETURN NUMBER IS sum_ NUMBER:=0; BEGIN OPEN CONSULTA FOR SELECT 1 FROM DUAL UNION SELECT 2 FROM DUAL; FOR i in IDS_FRIEND.FIRST..IDS_FRIEND.LAST LOOP sum_:=sum_+IDS_FRIEND(i); END LOOP; RETURN sum_; END; BEGIN :ids_friend_sum:=test(:ref_cursor,:cod_us,:ids_friend); END; ''', {"ref_cursor": ref_cursor, "cod_us": cod_us, "ids_friend": ids_friend, "ids_friend_sum": ids_friend_sum}) print("ref cursor=", end=" ") for rec in ref_cursor.getvalue(): print(rec, end="\t") print("\nids_friend_sum=", ids_friend_sum.getvalue())
getting an error while using mpl_toolkits.basemap Question: from mpl_toolkits.basemap import Basemap - is not working in ipython Getting error as - No module named basemap I'm using jupyter Answer: You probably don't have basemap installed. It is a separate package. If you are using conda, you can install it with: conda install basemap If not, you can install with: pip3 install --allow-external basemap --allow-unverified basemap basemap (the `--allow-stuff` is because basemap is not on PyPI because its [installers are too big](https://github.com/matplotlib/basemap/issues/198).
How to access keys from buckets with periods (.) in their names using boto3? Question: ## Context I am trying to get an encryption status for all of my buckets for a security report. However, since encryption is on a key level basis, I want to iterate through all of the keys and get a general encryption status. For example, "yes" is all keys are encrypted, "no" if none are encrypted, and "partially" is some are encrypted. **I must use boto3 because there is a known issue with boto where the encryption status for each key always returns None.[See here.](https://github.com/boto/boto/issues/2836)** ## Problem I am trying to iterate over all the keys in each of my buckets using boto3. The following code works fine until it runs into buckets with names that contain periods, such as "my.test.bucket". from boto3.session import Session session = Session(aws_access_key_id=<ACCESS_KEY>, aws_secret_access_key=<SECRET_KEY>, aws_session_token=<TOKEN>) s3_resource = session.resource('s3') for bucket in s3_resource.buckets.all(): for obj in bucket.objects.all(): key = s3_resource.Object(bucket.name, obj.key) # Do some stuff with the key... When it hits a bucket with a period in the name, it throws this exception when `bucket.objects.all()` is called, telling me to send all requests to a specific endpoint. This endpoint can be found in the exception object that is thrown. for obj in bucket.objects.all(): File "/usr/local/lib/python2.7/site-packages/boto3/resources/collection.py", line 82, in __iter__ for page in self.pages(): File "/usr/local/lib/python2.7/site-packages/boto3/resources/collection.py", line 165, in pages for page in pages: File "/usr/lib/python2.7/dist-packages/botocore/paginate.py", line 85, in __iter__ response = self._make_request(current_kwargs) File "/usr/lib/python2.7/dist-packages/botocore/paginate.py", line 157, in _make_request return self._method(**current_kwargs) File "/usr/lib/python2.7/dist-packages/botocore/client.py", line 310, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/lib/python2.7/dist-packages/botocore/client.py", line 395, in _make_api_call raise ClientError(parsed_response, operation_name)botocore.exceptions.ClientError: An error occurred (PermanentRedirect) when calling the ListObjects operation: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint. ## Things I have tried * Setting the endpoint_url paramter to the bucket endpoint specified in the exception response like `s3_resource = session.resource('s3', endpoint_url='my.test.bucket.s3.amazonaws.com')` * Specifying the region the bucket is located in like `s3_resource = session.resource('s3', region_name='eu-west-1')` I believe the problem is similar to [this stackoverflow question](http://stackoverflow.com/questions/27652318/cant-connect- to-s3-buckets-with-periods-in-their-name-when-using-boto-on-herok) in boto, which fixes the problem by setting the calling_format parameter in the s3Connection constructor. Unfortunately, I can't use boto though (see above). ## Update Here is what ended up working for me. It is not the most elegant approach, but it works =). from boto3.session import Session session = Session(aws_access_key_id=<ACCESS_KEY>, aws_secret_access_key=<SECRET_KEY>, aws_session_token=<TOKEN>) s3_resource = session.resource('s3') # First get all the bucket names bucket_names = [bucket.name for bucket in s3_resource.buckets.all()] for bucket_name in bucket_names: # Check each name for a "." and use a different resource if needed if "." in bucket_name: region = session.client('s3').get_bucket_location(Bucket=bucket_name)['LocationConstraint'] resource = session.resource('s3', region_name=region) else: resource = s3_resource bucket = resource.Bucket(bucket_name) # Continue as usual using this resource for obj in bucket.objects.all(): key = resource.Object(bucket.name, obj.key) # Do some stuff with the key... Answer: Just generalizing the great answer provided from [Ben](http://stackoverflow.com/users/2430241/ben-whaley). import boto3 knownBucket = 'some.topLevel.BucketPath.withPeriods' s3 = boto3.resource('s3') #get region region = s3.meta.client.get_bucket_location(Bucket=knownBucket)['LocationConstraint'] #set region in resource s3 = boto3.resource('s3',region_name=region)
Blender Scripting - Import Collada file and save it as .blend Question: Right now, I have a script in python that converts a collada (.dae) file into a blender file (.blend). In the command Line: C:\Program Files\Blender Foundation\Blender>blender.exe --background --python c:\Users\c.diaz\Desktop\convert_collada_to_blend.py -- c:\Users\c.diaz\Desktop \Maya.dae -- c:\Users\c.diaz\Desktop\Result.blend My script: import bpy import sys argv = sys.argv argv = argv[argv.index("--") + 1:] # get all args after "--" dae_in = argv[0] blend_out = argv[1] bpy.ops.wm.collada_import(filepath=dae_in) bpy.ops.render.render() bpy.ops.wm.save_mainfile(filepath=blend_out) After executing the command, I get a lot of output indicating that It's actually doing something. However, at the end of the process, I don't know where the result file is being saved. Any Help From you guys, I'll appreciate it. Answer: Look for a file named `--` in the current directory when you enter the command, in the temp directory, or possibly the same dir as blender.exe. The location of the [temp directory](https://docs.python.org/3.4/library/tempfile.html#tempfile.tempdir) may vary, try import tempfile print(tempfile.gettempdir()) You use `argv = argv[argv.index("--") + 1:]` to get the args after the first '--' which includes the extra '--' between the two paths that you are expecting to be used. The second of these is what you are assigning to `blend_out` I expect the command you want to use is C:\Program Files\Blender Foundation\Blender\blender.exe --background --python c:\Users\c.diaz\Desktop\convert_collada_to_blend.py -- c:\Users\c.diaz\Desktop\Maya.dae c:\Users\c.diaz\Desktop\Result.blend Also of note is your use of `bpy.ops.render.render()`, this doesn't save the rendered image (assuming you have a camera setup). Use `bpy.ops.render.render(write_still=True)` to have the rendered image saved to disk. You may also want to set `bpy.context.scene.render.filepath` to specify where the image is saved.
Getting each values from a value list python Question: Hi I have a custom Django/python resource/view. as follows class ResourceView(JSONResponseMixin, View): def get(self, request, *args, **kwargs): status = 'error' msg = "Success" # Getting the x value from url/queryset x= self.request.GET.get('x') mas = self.request.GET.get('mas') queryset_df = Forecast.objects.filter(Q(x=int(fab)) | Q(x=int("0"+x)))\ .values_list('mas').distinct() queryset_or = Record.objects.filter(Q(pc_ext__x=int(x)) | Q(pc_ext__x=int("0"+x)))\ .values_list('mas').distinct() new_mas_list = list(set(list(queryset_df) + list(queryset_or))) new_mas_list.sort() return self.render_json_response(dict(objects=new_mas_list)) Which returns a value list of masksets. How to get each value of the valuelist(Because in my html, i have a dropdown to display each valuelist objects, displays fine; but when I select one it returned me as a value list object as `["5300A"]` instead of 5300A. I am using AngularJS to get the value as follows: //UPDATE MAS BASED ON USER FAB $scope.update_mas = function(){ $scope.processing['update_mas'] = { msg: 'loading mas..', class: 'text-warning', show: true }; console.log('Stage1: Loading Mas..... '); $http.get('{% url "masresourceview" %}', { params: { x: $scope.x} }).success( function(data){ $scope.processing['update_mas'] = { msg: 'mas updated.', class: 'text-success' }; setTimeout(function () { $scope.processing['update_mas'] = null; $scope.$apply(); }, 1000); $scope.maslist = data['objects']; $scope.isDisable = true; console.log($scope.maslist); }).error(function(data, status){ $scope.processing['update_mas'] = { msg: 'Internal Error', class: 'text-danger' }; console.log('Stage1: Internal error while loading initial data:'+status ); }); }; My resource/list looks like this: { objects: [ [ "AMD14NM" ], [ "BAFFIN1" ], [ "BAGERA1" ], [ "ELLSMR1" ], [ "GARFLD1" ], [ "GARFLD2" ], When I put `$scope.maslist = data['objects'][0];` I can get the first object's value perfectly. What I can do for the rest of the object's values? Do I need to improve my views.py/resources? Thanks in advance. Answer: Just updated the return part with `flatten`. `from compiler.ast import flatten` `return self.render_json_response(dict(objects=flatten(new_mas_list)))`
Simple database table dumping in a specific path Question: How can I dump MySQL database table only which will store my on drive 'c:', rather than whole database here is my running python connect script: cnx = mysql.connector.connect(user='test', password ='test',host='192.168.25.63', database='test',port='3306') I also refer to this question using subprocess: [How to copy a database with mysqldump and mysql in Python?](http://stackoverflow.com/questions/26256248/how-to-copy-a-database- with-mysqldump-and-mysql-in-python) I just want to have a python script just like having MySQLdump using windows command. Answer: You can simply use following command with `popen`: import subprocess subprocess.popen("mysqldump db_name table_name > your_path/table_name.sql", shell=True)
How to convert string values to integer values while reading a CSV file? Question: When opening a CSV file, the column of integers is being converted to a string value ('1', '23', etc.). What's the best way to loop through to convert these back to integers? import csv with open('C:/Python27/testweight.csv', 'rb') as f: reader = csv.reader(f) rows = [row for row in reader if row[1] > 's'] for row in rows: print row CSV file below: Account Value ABC 6 DEF 3 GHI 4 JKL 7 Answer: I think this does what you want: import csv with open('C:/Python27/testweight.csv', 'rb') as f: reader = csv.reader(f, delimiter='\t') header = next(reader) rows = [header] + [[row[0], int(row[1])] for row in reader] for row in rows: print row Output: ['Account', 'Value'] ['ABC', 6] ['DEF', 3] ['GHI', 4] ['JKL', 7]
How can I 'hide' a tab in Spotfire depending on the current user in IronPython? Question: I have a tab that contains a visualizations for data validation and testing. I'd like to leave that tab in there without showing to anyone but the devs. I can get the current user this way but can't find how to 'hide' the tab. from System.Threading import Thread print Thread.CurrentPrincipal.Identity.Name Answer: I'm quite sure that hiding a tab is not possible. there are some other possible solutions, though. 1. change the navigation style from **Titled Tabs** to **History Tabs** , then handle navigation between pages with a textarea that is populated by your script. it's the simplest solution, but if you have super sensitive data in this analysis AND your users are accessing via the Analyst client, then a user could change the navigation style. 2. based on the user group, write a script that creates any pages with visualizations on the fly. this one is also at risk to users with Analyst plus scripting access, and is significantly more work to create and maintain (but also really cool and fun, if you like scripting!). 3. make a different analysis per "user group". probably not the best solution since you'd need to repeat any updates for each analysis. this gives you the most security but I think at the highest long-term cost (assuming that the analyses will change over time).
navigate folders with python Question: I have a folder ROOT and inside many different folders (let's assume N), that for sake of simplicity I call F1, F2 and so on... I need to work with the file inside these folders. If I have only one folder I know that I can do: os.chdir(".") #I'm workingo in ROOT for filename in glob.glob("*.txt"): #I can work with the i-th file... But what I need to do is something like this (pseudo-code like): os.chdir(".") #I'm working in ROOT for F-i-th in ROOT: #for each folder in the ROOT main folder for filename in F-i-th("*.txt"): #I select only the file with this extention #process data inside i-th file I mean that I need to go inside the first folder (F1) and process all the file (or if it is possible all the .txt file), after I should go inside the F2 and process all the file.... Answer: `os.walk` will perform recursion of a directory and `fnmatch.filter` will match filename patterns. Simple example: import os import fnmatch for path,dirs,files in os.walk('.'): for f in fnmatch.filter(files,'*.txt'): fullname = os.path.abspath(os.path.join(path,f)) print(fullname)
How to extract the historical tweets from twitter API? Question: We need the historical tweets for some movies. Right now, we tried the streaming API and search API from twitter. The streaming API could not give us a parameter to choose the time range we need and the search API could only give us data one or two weeks in advance. Is there a way for us to extract the historical tweets from 2014-05-01 to 2014-07-01 (For example)? I found the following ways that is possible to do that: 1: Twitter advanced search <https://twitter.com/search-advanced?lang=en> It could find the search result I need. But how could I download the search result? Is there anyway to write a code and save the search result? 2:Using the twitter analytic website like topsy. But it also has the difficulty to save the result. 3: It seems that some packages like twitter4J could help with that: <http://twitter4j.org/en/code-examples.html> Is there any python or R package could help us to do that? 4: We need this data to do a research. It is not a good choice to spend a long time for the extraction of the data. Is there anyway to buy this data from some professional website? Answer: You can use the following library <https://github.com/Jefferson- Henrique/GetOldTweets-python> to get old tweets in Twitter. Make GetOldTweets-python as the current directory in Python using cd GetOldTweets-python then do the following In Python, import got tweetCriteria = got.manager.TweetCriteria().setQuerySearch('search_term').setSince("2014-05-01").setUntil("2014-07-01").setMaxTweets(10000) tweet = got.manager.TweetManager.getTweets(tweetCriteria)[0] print tweet.text In terminal, python Exporter.py --querysearch 'search_term' --since 2014-05-01 --until 2014-07-01 --maxtweets 10000 Replace 'search_term' with the search term.
How to play three different audio files through three different speaker? Question: I have a project and I must play **3** different audio files through **3** different speakers. The start time of files are important (I mean they must start to play simultaneously). My first option is using **3** networked computer, one file per computers, and a program that control these three systems (One server and two clients for example). But I think it's really better to use a sound card with **4** channel for example. After some search I found that there are a lot of these sound cards. I want to know, is it possible to control the channel using Python or Matlab programs or any other way? Is there any library? Answer: The audioplayer function in MATLAB supports only 2 channels. But you can use the functionality in the DSP System Toolbox. The code snippet below can helps: hafr1 = dsp.AudioFileReader('myfile1.wav');% Can be other formats as well hafr2 = dsp.AudioFileReader('myfile2.wav'); hafr3 = dsp.AudioFileReader('myfile3.wav'); hap = dsp.AudioPlayer; hap.SampleRate = hafr1.SampleRate; % Assuming that all files have same sample rate or else you have to do some clever mixing. while ~isDone(hafr1) % assuming same size. You need to add some clever logic to adjust the number of channels if they are of different sizes data1 = step(hafr1); data2 = step(hafr2); data3 = step(hafr3); step(hap, [data1 data2 data3]); end This code will playback audio on the default output device. If this has three or more channels, you will hear tha audio on 3 separate channels. If not, depending on the platform, it will get mixed down into two channels. You can refer to the [doc](http://www.mathworks.com/help/dsp/ref/dsp.audioplayer- class.html?refresh=true) page for info. Dinesh
python 3d array like in C ++ Question: I'd like to make a 3 dimensional array like this one : treedarray = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] in this table, every value is (easily) accessible by using : treedarray [a] [b] [c] I'd like to know if there is a command to do that more easily. Thanks in advance. Answer: Using [Numpy](http://www.numpy.org/) and [numpy.zeros()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html) you can define the shape with a list of values as the first param. e.g. import numpy as np treedarray = np.zeros([3,3,3]) print treedarray Outputs: [[[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]] And can access the pretended value using, `treedarray[a][b][c]`.
Reading and formatting issues in python Question: New to the site, hopefully my question isn't missing to many details or being too vague. Essentially i'm running a netbackup script, to create a new file: subprocess.call('/usr/openv/netbackup/bin/goodies/available_media > /var/log/nbu/available_media' + adate, shell=True) [![The output of this file looks like this](http://i.stack.imgur.com/6tBwj.png)](http://i.stack.imgur.com/6tBwj.png) I want to then format this and input it into another file using out.write, that specifies the pool name e.g "Auth Pool", "Web Pool" etc. Use count to find out how many tapes are in a state of "AVAILABLE" "FULL" "FROZEN" for each pool. #Pool #Full #Avail #Frozen AUTH 100 5 23 All i've managed so far is the following: from datetime import datetime import subprocess import os import sys date = datetime.now() adate = '%s%s%s' % (date.year, date.month, date.day) subprocess.call('/usr/openv/netbackup/bin/goodies/available_media > /var/log/nbu/available_media' + adate, shell=True) log = open('/var/log/nbu/available_media' + adate, 'r') text = log.read() auth = text.split('Auth_Offsite', 1)[0] notapes = auth.count('AVAILABLE') Currently my knowledge restricts me to just counting AVAILABLE tapes for the first pool by using split. I'm new to python so please be gentle :P All help is greatly appreciated. Answer: Here's a quick and dirty that should roughly do what you want, assuming that your log file is tab separated. If you're new to python, some of the functions might be new to you, but it should give you some ideas about what you might want to google for at least. log = open('/var/log/nbu/available_media' + adate, 'r') # Splits on newline chars, skips the titles and ----- lines lines = log.readlines()[2:] # Break up each line by field lines = [line.strip().split('\t') for line in lines] # Going to form a dictionary mapping pool names to dictionaries of tape state counts states_dict = {} all_states = set() for line in lines: if len(line) == 1: current_pool = line[0] states_dict[current_pool] = {} elif len(line) > 1: state = line[-1] states_dict[current_pool][state] = states_dict[current_pool].setdefault(state, 0) + 1 all_states.add(state) all_states = sorted(list(all_states)) # write output with open('output_file_name.txt','wb') as outfile: outfile.write('Pool\t' + '\t'.join(all_states) + '\n') for pool in states_dict: outfile.write(pool) for state in all_states: outfile.write('\t' + states_dict[pool].setdefault(state, 0)) outfile.write('\n')
How to generate a random arange in python? Question: I want to generate a random arange of 10 values in Python. Here's my code. Is there any faster way or more elegant way to generate it ? Because the x in function **lambda** is actually never used. >>> import numpy as np >>> import random as rd >>> i = np.arange(0, 10) >>> noice = map(lambda x: rd.random(), i) >>> i array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> noice [0.040625208925370804, 0.3979391267477529, 0.36389993607597815, 0.5222540865995068, 0.4568532903714069, 0.9028000777629279, 0.6011546913245037, 0.4779160505869603, 0.9929389966510183, 0.7688424310182902] Answer: You can simply use `np.random.rand(10)`. See the [NumpPy docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand).
Save and Load GUI-tkinter Question: I want to save and load my GUI. I have made a GUI and I want that when I click on the save button. It should save the GUI in some blob of data and when I click on load button then it will load the same GUI again. My GUI has various text widgets, drop down Option Menu. I am new to python, so someone can help me on this, please? I have tried pickle module, too. Answer: You can't do what you want to do without doing the work yourself. You'll need to write a function that gathers all the data you need in order to restore the GUI, and then you can save that to disk. Then, when the GUI starts up you can read the data and reconfigure the widgets to contain this data. Tkinter gives you pretty much everything you need in order to accomplish it, but you have to do all the work yourself. Pickling the GUI won't work. Here's a contrived example. Enter a few expressions in the window that pops up. Notice that they are added to the combobox. When you exit, the current expression, the saved expressions, and the current value are all saved. The next time you start the GUI, these values will be restored. import Tkinter as tk import ttk import pickle FILENAME = "save.pickle" class Example(tk.Frame): def __init__(self, parent): self.create_widgets(parent) self.restore_state() def create_widgets(self, parent): tk.Frame.__init__(self, parent, borderwidth=9,relief="flat") self.previous_values = [] l1 = tk.Label(self, text="Enter a mathematical expression:", anchor="w") l2 = tk.Label(self, text="Result:", anchor="w") self.expressionVar = tk.StringVar() self.expressionEntry = ttk.Combobox(self, textvariable=self.expressionVar, values=("No recent values",)) self.resultLabel = tk.Label(self, borderwidth=2, relief="groove", width=1) self.goButton = tk.Button(self, text="Calculate!", command=self.calculate) l1.pack(side="top", fill="x") self.expressionEntry.pack(side="top", fill="x",padx = (12, 0)) l2.pack(side="top", fill="x") self.resultLabel.pack(side="top", fill="x", padx = (12, 0), pady=4) self.goButton.pack(side="bottom", anchor="e", pady=4) self.expressionEntry.bind("<Return>", self.calculate) # this binding saves the state of the GUI, so it can be restored later root.wm_protocol("WM_DELETE_WINDOW", self.save_state) def calculate(self, event=None): expression = self.expressionVar.get() try: result = "%s = %s" % (expression, eval(expression)) self.previous_values.append(expression) self.previous_values = self.previous_values[-8:] self.expressionVar.set("") self.expressionEntry.configure(values=self.previous_values) except: result = "invalid expression" self.resultLabel.configure(text=str(result)) def save_state(self): try: data = { "previous": self.previous_values, "expression": self.expressionVar.get(), "result": self.resultLabel.cget("text"), } with open(FILENAME, "w") as f: pickle.dump(data, f) except Exception as e: print "error saving state:", str(e) root.destroy() def restore_state(self): try: with open(FILENAME, "r") as f: data = pickle.load(f) self.previous_values = data["previous"] self.expressionEntry.configure(values=self.previous_values) self.expressionVar.set(data["expression"]) self.resultLabel.configure(text=data["result"]) except Exception as e: print "error loading saved state:", str(e) if __name__ == "__main__": root = tk.Tk() Example(root).pack(fill="both", expand=True) root.mainloop()
Queue and ProcessPoolExecutor in Tornado Question: I'm attempting to use the new [Tornado queue](http://tornadokevinlee.readthedocs.org/en/latest/queues.html) object along with [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html) to allow my webserver to pass off cpu-intensive tasks to other processes. I want to have access to the `Future` object that's returned from the `ProcessPoolExecutor` from the `concurrent.futures` module so that I can query its state to show on the front-end (e.g. show the process is currently running; show that it has finished). I seem to have two hurdles with this method: 1. How can I submit multiple `q.get()` objects to the `ProcessPoolExecutor` while also having access to the returned `Future` objects? 2. How can I let the `HomeHandler` get access to the `Future` object returned by the `ProcessPoolExecutor` so that I may show the state information on the front-end? Thanks for any help. from tornado import gen from tornado.ioloop import IOLoop from tornado.queues import Queue from concurrent.futures import ProcessPoolExecutor define("port", default=8888, help="run on the given port", type=int) q = Queue(maxsize=2) def expensive_function(input_dict): gen.sleep(1) @gen.coroutine def consumer(): while True: input_dict = yield q.get() try: with ProcessPoolExecutor(max_workers=4) as executor: future = executor.submit(expensive_function, input_dict) finally: q.task_done() @gen.coroutine def producer(input_dict): yield q.put(input_dict) class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", HomeHandler), ] settings = dict( blog_title=u"test", template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=True, ) super(Application, self).__init__(handlers, **settings) class HomeHandler(tornado.web.RequestHandler): def get(self): self.render("home.html") def post(self, *args, **kwargs): input_dict = {'foo': 'bar'} producer(input_dict) self.redirect("/") def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.current().start() def start_consumer(): tornado.ioloop.IOLoop.current().spawn_callback(consumer) if __name__ == "__main__": tornado.ioloop.IOLoop.current().run_sync(start_consumer) main() Answer: What are you trying to accomplish by combining a `Queue` and a `ProcessPoolExecutor`? The executor already has it's own internal queue. All you need to do is make the `ProcessPoolExecutor` a global (it doesn't have to be a global, but you'll want to do something similar to a global even if you keep the queue; it doesn't make sense to create a new `ProcessPoolExecutor` each time through `consumer`'s loop) and submit things to it directly from the handler. @gen.coroutine def post(self): input_dict = ... result = yield executor.submit(expensive_function, input_dict)
How to set an attribute to a vector in rpy2 Question: How to add attributes to vectors in python with rpy2. As an example how can I reproduce this R code: library(evir) pot<-c(2.0,3.2,4,5,6,7) ts<-c(1,6,7,19,20,30) attr(pot,"times")<-ts output<-decluster(pot,run=2) I can't find any help after searching several hours on the net. I guess Laurent has the answer ;-) Answer: Use the attribute `slots`. What is described about it in the doc for S4 objects applies to attributes (<http://rpy2.readthedocs.org/en/version_2.7.x/notebooks/s4class.html>). Here it should work with: from rpy2.robjects.vectors import FloatVector, IntVector pot = FloatVector((2.0, 3.2, 4, 5, 6, 7)) ts = IntVector((1,6,7,19,20,30)) pot.slots['times'] = ts For rpy2 < 2.7, you should use do_slot_assign : pot.do_slot_assign("times",ts)
Validating an email format in python Question: I'm trying to write a program that checks to see if the email is in the valid form. A valid form would be any combination of characters of letters or numbers followed by a `@` sign and then any combination of characters of letters again. I'm not even trying to have a domain such as "gmail.com" it can just be new@gmail for example. I've tried many things and can't seem to figure it out. email = "XXX@XXX" x = len(email) for i in range(x): if email[i][0] == "@": return False elif email[i][-1] == "@": return False elif not email[i].isalnum(): return False return True Answer: You can use this package: <https://pypi.python.org/pypi/validate_email> from validate_email import validate_email is_valid = validate_email('[email protected]')
Orange 3 - openSUSE 13.1 installation - No widgets Question: I am having trouble installing Orange3 from github on openSUSE 13.1. I have all requirements installed: gcc, g++, python 3-devel, pysci, pyqt4devel etc. I followed [these](https://github.com/biolab/orange3/wiki/Installation-on- openSUSE-13.2) instructions, everything seems to work (with many warnings when compiling), however when entering in `Orange.canvas`, there are no widgets at all. It seems they have been missing on installation/compilation. Any idea about what I did miss in the install or requirements? Answer: Thanks for the -l3 options. All the widgets get the same error on import File "./Orange/widgets/utils/overlay.py", line 10, in <module> import enum ImportError: No module named 'enum' Could not import 'orangecontrib.datafusion.widgets.owsamplematrix'`` I am not Python specialist, I will check for this module ..
Python Error importing package in windows Question: First off sorry about my English. Here's my question: I'm really new to programming and I really want to learn Python. That's why I've been reading this book: HeadFirst Python and also joined this website. Everything was great until I've stumbled into this error I keep getting everytime I import the nester package that I've created. Why is that happening? ERROR: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import nester File "C:\python\lib\site-packages\nester.py", line 1 Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32 ^ SyntaxError: invalid syntax Any answers from you guys will be of great help. Answer: The error message says that `nester.py` starts with a line saying `Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32`. It looks like you managed to put output of the interpreter into the file instead of your source code :-)