text
stringlengths
226
34.5k
why can't import pandas after installed successfully? Question: I have installed pandas with command 'pip3.4 install pandas'. Successfully installed pandas python-dateutil pytz numpy six Cleaning up... root@hwy:~# python3.4 Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pandas Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'pandas' Why can't import pandas in python3.4 after pandas been installed successfully? root@hwy:/home/debian8# pip3.4 show pandas --- Name: pandas Version: 0.17.1 Location: /usr/local/python3.4/lib/python3.4/site-packages Requires: python-dateutil, pytz, numpy root@hwy:/home/debian8# echo "import sys; print sys.path" import sys; print sys.path root@hwy:/home/debian8# python3.4 Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print(sys.path) ['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] Answer: Your `pandas` is installed here: /usr/local/python3.4/lib/python3.4/site-packages But this path is not in `sys.path`. As a workaround do: export PYTHONPATH=$PYTHONPATH:/usr/local/python3.4/lib/python3.4/site-packages and inside this terminal start Python again and do your import of `pandas`. If this works, add this line above (`export PYTHONPATH...`) to your `~/.bashrc` or equivalent if you use a different shell for a more permanent solution.
error importing QtGui from Pyside Question: I just downloaded and installed PySide and I am getting this error when I try to import QtGui from PySide $ python -c "from PySide import QtGui" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: dlopen(/Library/Python/2.7/site-packages/PySide/QtGui.so, 2): Symbol not found: __ZN7QLayout11adoptLayoutEPS_ Referenced from: /Library/Python/2.7/site-packages/PySide/QtGui.so Expected in: /Library/Frameworks/QtGui.framework/Versions/4/QtGui in /Library/Python/2.7/site-packages/PySide/QtGui.so any help would be greatly appreciated. Answer: Just installed PySide from pip yesterday. Checked "python -c "from PySide import QtGui" everything importing fine. Firs check if you have QtGui.so in "/Library/Python/2.7/site-packages/PySide/" directory, cause a have. Some month ago trying to install PyQt from sources got problem with compilation: everything looks fine, but some modules (including QtGui) was absent (can't remember but problem was in some config file).
Project "Gothonweb" in Learn Python the Hard Way ex50 works fine on Ubuntu, fails on win7 Question: I did the project in ex50. It works fine on ubuntu. However I can't get it run normally on win7. What's wrong with it? (My code is exactly the same as what it is in the book!) app.py import web urls = ( '/', 'Index' ) app = web.application(urls, globals()) render = web.template.render('templates/') class Index(object): def GET(self): greeting = "Hello World" return render.Index(greeting = greeting) if __name__ == "__main__": app.run() Traceback on win7:[traceback](http://i.stack.imgur.com/nxCeK.png) And my project here on github~ <https://github.com/ustcgcy/gothonweb> Answer: Don't use the trailing `/`on Windows. Instead of `render = web.template.render('templates/')` write `render = web.template.render('templates')`.
Migration of unique value isn't working Question: I'm trying to execute a migration where it add a `UUID` field to an existing table. I made the step by step of what is explained in the Django documentation (<https://docs.djangoproject.com/en/1.8/howto/writing- migrations/#migrations-that-add-unique-fields>), but it's not working for me. I'm working with version 1.8. The model is like this: class Event(models.Model): key_public = models.UUIDField(default=uuid.uuid4, unique=True) key_private = models.UUIDField(default=uuid.uuid4, unique=True) And I've 3 migrations file. Migration 1: from __future__ import unicode_literals from django.db import models, migrations import uuid class Migration(migrations.Migration): dependencies = [ ('events', '0007_auto_20151008_1313'), ] operations = [ migrations.AddField( model_name='Event', name='key_private', field=models.UUIDField(null=True, default=uuid.uuid4), ), migrations.AddField( model_name='Event', name='key_public', field=models.UUIDField(null=True, default=uuid.uuid4), ), ] Migration 2: from __future__ import unicode_literals from django.db import models, migrations import uuid class Migration(migrations.Migration): dependencies = [ ('events', '0008_auto_20151121_1642'), ] operations = [ migrations.AlterField( model_name='Event', name='key_private', field=models.UUIDField(default=uuid.uuid4, unique=True), ), migrations.AlterField( model_name='Event', name='key_public', field=models.UUIDField(default=uuid.uuid4, unique=True), ), ] Migration 3: from __future__ import unicode_literals from django.db import models, migrations import uuid def gen_uuid(apps, schema_editor): Event = apps.get_model('events', 'Event') for row in Event.objects.all(): row.key_private = uuid.uuid4() row.key_public = uuid.uuid4() class Migration(migrations.Migration): dependencies = [ ('events', '0009_auto_20151121_1644'), ] operations = [ migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop), ] Bellow the error: Traceback (most recent call last): File "event/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/migrations/executor.py", line 147, in apply_migration state = migration.apply(state, schema_editor) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 484, in alter_field old_db_params, new_db_params, strict) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 203, in _alter_field self._remake_table(model, alter_fields=[(old_field, new_field)]) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 147, in _remake_table self.quote_name(model._meta.db_table), File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 111, in execute cursor.execute(sql, params) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/evandrolg/.virtualenvs/event/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: events_event__new.key_private Answer: In migration #3 you need to do `row.save()`. You may also need to do migration #2 AFTER migration #3 as it changes the column to disallow nulls.
python numpy parse array to get items Question: Hi I tried taking distinct items of every sublist and making an array My input is a 2D list alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']] And output I want is an array of distinct items out = [1,2,3,5,15,657] I tried from numpy import np alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']] anarray = np.array(alist) newarray = [] for i in anarray: for j in i: if j in newarray: pass else: print j Answer: from itertools import chain alist = [['1', '2'], ['3', '5', '2'], ['15', '1'], ['5', '657', '3', '1']] # Flatten the list into a single-level list of all the values flattened_list = list(chain.from_iterable(alist)) # Use a set to remove the duplicates uniques = set(flattened_list) # Sort the unique values by the numeric value of each value sorted_results = sorted(uniques, key=lambda value: int(value)) print sorted_results
Is it necessary to call seed() when using random in Python? Question: I was looking at the following code: from random import choice for val in range(10): a = ','.join(str(choice(range(20))) for idx in range(4)) print a And realized that I hadn't used seed(). I've been taught to seed the random number generator if you intend to generate different psuedo-random sequences. I decided to run the code, expecting to the sequence repeated each time. But after several runs of the code, it appears to generate a different sequence each time. 1. Is it really necessary to seed the Python random number generator? or... 2. Is seed being called by default somewhere? or... 3. Am I doing something wrong and/or don't understand what's happening? Answer: I think seed is just meant to be used 1) so that you can get the same predictable sequence every time if you seed with the same number 2) to feed a better (eg hardware generated) random number in as a start value
compilation issue when running theano Question: I installed theano on windows 8, 64 bit. I am using anaconda implementation, python 3.4. Trying to install theano, I diligently followed all steps on this link (which helped on another computer with similar configuration): <http://rosinality.ncity.net/doku.php?id=python:installing_theano> (English and Korean) whenever I type 'import theano' on my IDE (pycharm) I get a long error message, but I believe the most meaningful portion is: import theano >>>>Exception: Compilation failed (return status=1): C:\Users\xxx\AppData\Local\Theano\compiledir_Windows-8-6.2.9200- Intel64_Family_6_Model_69_Stepping_1_GenuineIntel-3.4.3- 64\lazylinker_ext\mod.cpp:1: sorry, unimplemented: 64-bit mode not compiled in Would sincerely appreciate some input btw, I installed mignw64, msys, and all other dependencies. Answer: I found the problem. the path environment variable was not pointing to the correct mingw-w64 (which is needed to run theano on 64 bit windows) directory. The environment variable should always point to the bin subdirectory of the mingw-w64 directory, as in: C:\Users\xxxxx\Anaconda3\mingw-w64\mingw64\bin Again, the following post is VERY USEFUL to install theano on 64-bit windows (in English and Korean): <http://rosinality.ncity.net/doku.php?id=python:installing_theano>
Python:not getting Length of longest common subsequence of lists Question: I tried to implement in LCS in simplest way I can but I am not getting the right value. Instead of 4 I get . I am not sure whats wrong with my code: X= ['A','B','C','B','D','A','B'] Y= ['B','D','C','A','B','A','X','Y'] m= len(X) n= len(Y) c={} for i in range(1,m) : c[i,0]=0 for j in range(0,n): c[0,j]=0 for i in range (1,m): for j in range (1,n): if X[i]==Y[j]: c[i,j]=c[i-1,j-1]+1 elif c[i-1,j] >= c[i,j-1]: c[i,j]=c[i-1,j] else: c[i,j]=c[i,j-1] print c[m-1,n-1] print c Answer: Here is the implementation I used for LCS, it returns `(percent_in_common, sequence_in_common)` def longest_common_sequence(a,b): from collections import deque n1=len(a) n2=len(b) if not n1: if not n2: return 100.0, '' return 0.0, '' if not n2: return 0.0, '' previous=deque() for i in range(n2): previous.append((0,'')) over = (0,'') for i in range(n1): left = corner = (0,'') for j in range(n2): over = previous.popleft() if a[i] == b[j]: this = corner[0] + 1, corner[1]+a[i] else: this = max(over,left) previous.append(this) left, corner = this, over return round(200.0*this[0]/(n1+n2),2),this[1]
What configuration settings are required in Django and MySQL for supporting concurrent requests? Question: I have created a project called test123, following are settings.py and urls.py : MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'dbuser.cnf'), } }, } root@cdbe25bac912:~/test123/test123# cat urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^myapp/', include('myapp.urls')), ] And I have created an application called myapp. root@cdbe25bac912:~/test123/myapp# cat models.py from django.db import models class Package(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=50) root@cdbe25bac912:~/test123/myapp# cat serializers.py from myapp.models import * from rest_framework import serializers class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ( 'id', 'name', 'desc',) root@cdbe25bac912:~/test123/myapp# cat views.py from django.shortcuts import render from myapp.models import * from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from myapp.serializers import * class PackageViewList(APIView): def get(self, request, format=None): package = Package.objects.all() serializer = PackageSerializer(package, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = PackageSerializer(data = request.data) if serializer.is_valid(): print serializer.validated_data serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) root@cdbe25bac912:~/test123/myapp# cat urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^package/$', views.PackageViewList.as_view()), ] root@cdbe25bac912:~/test123/myapp# Following is a test script written using Django Test Framework, which creates multiple APIClient objects to simulate multiple users and fire POST operation from these objects. root@cdbe25bac912:~/test123/myapp# cat tests.py.bkup from django.test import TestCase from rest_framework.test import APIClient from rest_framework.test import APITestCase, APILiveServerTestCase from myapp.models import Package from multiprocessing import Process class ConcurrentTest(APILiveServerTestCase): def setUp(self): self.apiclient_list = [] self.num_clients=4 package = Package.objects.create(name='pack333', desc='package333') package.save() self.pack = {"name" : "pack", "desc" : "package"} #create number of APIClient objects and login. for client_id in range(self.num_clients): apiclient = APIClient() self.apiclient_list.append(apiclient) def post(self, apiclient, client_id, url, data): print 'Started POST Client ID = %s' % (str(client_id)) data['name'] = 'packpost' + str(client_id) data['desc'] = 'packdesc' + str(client_id) print data response = apiclient.post(url, data, format="json") self.assertEqual(response.status_code, 201) print 'Completed POST Client ID = %s' % (str(client_id)) def test_concurrent_restops(self): """ Description : Simulate multiple users and issue concurrent REST operations """ process_list = [] #Issue concurrent POST operations. for client_id in range(len(self.apiclient_list)): t = Process(target=self.post, args=(self.apiclient_list[client_id], client_id, '/myapp/package/', self.pack)) process_list.append(t) for process in process_list : process.start() for process in process_list : process.join() root@cdbe25bac912:~/test123/myapp# ## Problem symptoms: When I run the above test problem as: `python manage.py test myapp` At least one of the processes that are created in `test.py` will hang. I am assuming there are some configurations required in Django and MySQL to support concurrent operations from different users. Answer: It looks like the `LiveServerTestCase` is single threaded which would explain why processes/requests hang, because the server can only service a single request at a time: <https://github.com/django/django/blob/53ccffdb8c8e47a4d4304df453d8c79a9be295ab/django/test/testcases.py#L1319> <https://github.com/django/django/blob/53ccffdb8c8e47a4d4304df453d8c79a9be295ab/django/test/testcases.py#L1332> <https://github.com/django/django/blob/53ccffdb8c8e47a4d4304df453d8c79a9be295ab/django/test/testcases.py#L1255> * * * One thing i can think of why you aren't seeing blocking using sqlite is because sqlite is ran in memory for django unittest, drastically increasing speeds of test runs. Django `LiveServerTestServer` is kind of a "toy" and is probably not very suitable for load style tests. MySQL should easily be able to handle a good level of concurrency out-of-the box, but I'm not sure `LiveServerTestServer` can. If you run your code against `python manage.py runserver` which is now multithreaded (I believe) you should notice a difference. For an idea of how your application can handle load, it could be a good idea run your code as it will be deployed (using your prod webserver: apache, uwsgi, gunicorn, etc..)
Dependency injection in imported python module Question: My python module uses some functions from another module, but I have several implementations of that module interface. How to point out, which one to use? Simple example: A.py: import B def say_hi() print "Message: " + B.greeting() main.py: import A(B=my_B_impl) A.say_hi() my_B_impl.py: def greeting(): return "Hallo!" output: Message: Hallo! Answer: What you ask is not directly possible. There is no parameterisation capability built in to Python's module system. If you think about it, it's not clear how such a proposal ought to work: if modules `A` and `B` both import module `M`, but they supply different parameters, which parameter is used when `M` is imported? Is it imported twice? What would that mean for module-level configuration (as in `logging`)? It gets worse if a third module `C` attempts to import `M` without parameters. Also, the "open-world" idea that you could override _any_ `import` statement from the outside violates the language- design principle that "the code you wrote is the code that ran". Other languages have incorporated parameterised modules in a variety of ways (compare Scala's object model, ML's modules and signatures, and - stretching it - C++'s templates), but it's not clear that such a feature would be a good fit for Python. (That said, you could probably hack something resembling parameterised modules using `importlib` if you were determined and masochistic enough.) * * * Python does have very powerful and flexible capabilities for dynamic dispatch, however. Python's standard, day-to-day features like functions, classes, parameters and overriding provide the basis for this support. There are lots of ways to cut the cake on your example of a function whose behaviour is configurable by its client. A function parameterised by a value: def say_hi(greeting): print("Message: " + greeting) def main(): say_hi("Hello") A class parameterised by a value: class Greeter: def __init__(self, greeting): self.greeting = greeting def say_hi(self): print("Message: " + self.greeting) def main(): Greeter("Hello").say_hi() A class with a virtual method: class Greeter: def say_hi(self): print("Message: " + self.msg()) class MyGreeter(Greeter): def msg(self): return "Hello" A function parameterised by a function: def say_hi(greeting): print("Message: " + greeting()) def make_greeting(): return "Hello" def main(): say_hi(make_greeting) There are more options (I'm avoiding the Java-y example of objects invoking other objects) but you get the idea. In each of these cases, the selection of the behaviour (the passing of the parameter, the overriding of the method) is decoupled from the code which uses it and could be put in a different file. The right one to choose depends on your situation (though here's a hint: the right one is always the simplest one that works). * * * **Update** : in a comment you mention that you'd like an API which sets up the dependency at the module-level. The main problem with this is that the dependency would be _global_ \- modules are singletons, so anyone who imports the module has to use the same implementation of the dependency. My advice is to provide an object-oriented API with "proper" (per-instance) dependency injection, and provide top-level convenience functions which use a (configurable) "default" set-up of the dependency. Then you have the option of _not_ using the globally-configured version. This is roughly [how `asyncio` does it](https://docs.python.org/3/library/asyncio-eventloops.html#event-loop- functions). # flexible object with dependency injection class Greeter: def __init__(self, msg): self.msg = msg def say_hi(self): print("Message: " + self.msg) # set up a default configuration of the object to be used by the high-level API _default_greeter = Greeter("Hello") def configure(msg): global _default_greeter _default_greeter = Greeter(msg) # delegate to whatever default has been configured def say_hi(): _default_greeter.say_hi()
Trouble with ReadProcessMemory in python to read 64bit process memory Question: I'm getting error code 998 (ERROR_NOACCESS) when using ReadProcessMemory to read the memory of a 64bit process (Minesweeper). I'm using python 3.5 64bit on windows 7 64bit. The strange thing is, this error only happens with addresses that are higher up, like for example 0x 0000 0000 FF3E 0000. Lower addresses, like 0x 0000 0000 0012 AE40 don't throw an error and return correct Minesweeper data. When I write the same program using nearly identical code in C#.NET and look at the same addresses, it works and I don't get an error! I know the address I'm looking at is correct because I can see it with Cheat Engine and VMMap. I don't know if it's relevant, but the higher address I'm looking at is the base module address of the MineSweeper.exe module in Minesweeper. Why is the python code not working? Python code (throws error for higher addresses but works for lower): import ctypes, struct pid = 3484 # Minesweeper processHandle = ctypes.windll.kernel32.OpenProcess(0x10, False, pid) addr = 0x00000000FF3E0000 # Minesweeper.exe module base address buffer = (ctypes.c_byte * 8)() bytesRead = ctypes.c_ulonglong(0) result = ctypes.windll.kernel32.ReadProcessMemory(processHandle, addr, buffer, len(buffer), ctypes.byref(bytesRead)) e = ctypes.windll.kernel32.GetLastError() print('result: ' + str(result) + ', err code: ' + str(e)) print('data: ' + str(struct.unpack('Q', buffer)[0])) ctypes.windll.kernel32.CloseHandle(processHandle) # Output: # result: 0, err code: 998 # data: 0 C#.NET code (64bit project, no errors): [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] static extern Int32 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead); [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr hObject); static void Main(string[] args) { var pid = 3484; // Minesweeper var processHandle = OpenProcess(0x10, false, pid); var addr = 0x00000000FF3E0000; // Minesweeper.exe module base address var buffer = new byte[8]; IntPtr bytesRead; var result = ReadProcessMemory(processHandle, new IntPtr(addr), buffer, (uint)buffer.Length, out bytesRead); Console.WriteLine("result: " + result); Console.WriteLine("data: " + BitConverter.ToInt64(buffer, 0).ToString()); CloseHandle(processHandle); Console.ReadLine(); } // Output: // result: 1 // data: 12894362189 Answer: It's good to be explicit when using `ctypes`. Setting `argtypes` and `restype` appropriately will help check number and type of arguments, just like the `DllImport` statements in C#. Here's a pedantic example: import ctypes as c from ctypes import wintypes as w pid = 4568 # Minesweeper k32 = c.windll.kernel32 OpenProcess = k32.OpenProcess OpenProcess.argtypes = [w.DWORD,w.BOOL,w.DWORD] OpenProcess.restype = w.HANDLE ReadProcessMemory = k32.ReadProcessMemory ReadProcessMemory.argtypes = [w.HANDLE,w.LPCVOID,w.LPVOID,c.c_size_t,c.POINTER(c.c_size_t)] ReadProcessMemory.restype = w.BOOL GetLastError = k32.GetLastError GetLastError.argtypes = None GetLastError.restype = w.DWORD CloseHandle = k32.CloseHandle CloseHandle.argtypes = [w.HANDLE] CloseHandle.restype = w.BOOL processHandle = OpenProcess(0x10, False, pid) addr = 0x00000000FF900000 # Minesweeper.exe module base address data = c.c_ulonglong() bytesRead = c.c_ulonglong() result = ReadProcessMemory(processHandle, addr, c.byref(data), c.sizeof(data), c.byref(bytesRead)) e = GetLastError() print('result: {}, err code: {}, bytesRead: {}'.format(result,e,bytesRead.value)) print('data: {:016X}h'.format(data.value)) CloseHandle(processHandle) Output: result: 1, err code: 0, bytesRead: 8 data: 0000000300905A4Dh Also note that you can pass the address of a data variable instead of creating a buffer and unpacking it with the `struct` module.
Python response to JavaScript Question: I have an AJAX request to my Python file like so $ajax({ type: "post", url: " name.py", data: { param: "hello" } }).done(function(obj){ alert(obj); }); I want to get that request from my Python file and send a response to it - "world". But, I can't use the library Requests. Please help me do this without using the library Requests Can also use a different way in the JavaScript code. Answer: You don't need `requests` for that, you need an HTTP server. Flask is a simple web framework, it embeds his own HTTP server. Here is a basic example on how to answer an http request, using flask : # main.py from flask import Flask app = Flask(__name__) @app.route("/") def index(): return 'Hi' @app.route("/hello") def hello(): return "Hello World!" if __name__ == "__main__": app.run() Install flask using pip: python -m pip install flask Then simply run your application development server using python : python main.py And visit : http://[YOUR SERVER IP]/ and http://[YOUR SERVER IP]/hello
AttributeError: 'int' object has no attribute 'x' Question: I realize this is a common topic for posts here, however, I can't seem to find one example that really helped me fix the problem. I'm trying to run a script that will add two new fields (x and y coords) to a shapefile then populate those fields with X and Y coords using the code block. This is for AcrGIS 10.2.2, but I don't think the problem is a ArcGIS problem. Script below: # Add new fields for "New_X" and "New_Y" for new points to be added # Calculate values for those new fields based on distance along line import arcpy, arcpy.mapping from arcpy import env env.workspace = r"G:\Geocomputation_Project\Section_C\Model_Shapes" env.overwriteOutput = True # Set local Variables in_table = 'Points.shp' field_x = 'New_X' field_y = 'New_Y' expression = "getXY(!Shape!, !ITEMID!, !CHAINAGE!)" code_block_x = """def getXY (point, id, d2add): mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd") lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0] q='"ITEMID"=%s%s%s' %(r"'",id,"'") pNew = 0 with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor: for row in cursor: line=row[0];break pointPos=line.measureOnLine(point)+d2add pNew+=line.positionAlongLine(pointPos).firstPoint pNew.X""" code_block_y = """def getXY (point, id, d2add): mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd") lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0] q='"ITEMID"=%s%s%s' %(r"'",id,"'") pNew = 0 with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor: for row in cursor: line=row[0];break pointPos=line.measureOnLine(point)+d2add pNew+=line.positionAlongLine(pointPos).firstPoint pNew.Y""" # Execute AddField for each new X and Y coord arcpy.AddField_management(in_table, field_x, "Double") arcpy.AddField_management(in_table, field_y, "Double") # Execute CalculateField to each new X and Y field arcpy.CalculateField_management(in_table, field_x, expression, "PYTHON_9.3", code_block_x) arcpy.CalculateField_management(in_table, field_y, expression, "PYTHON_9.3", code_block_y) I keep getting AttributeError: 'int' object has no attribute 'X'. Answer: Assuming the error in the title is correct, and not the one in the post body, here's your problem: pNew = 0 # ... pNew.Y It should be pretty obvious that's not going to work
Pickle in python, writing to files Question: if group == 10G2: file_name='10G2 Scores.txt' fileObject = open(file_Name,'wb') pickle.dump(+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject) fileObject.close() This is part of a maths quiz and I am trying to write scores to a text file. It says there is a syntax error on the 10G2? All of the variables have been defined and I have imported pickle Thanks in advance. BTW, I'm doing GCSE computing. This is my whole code: #Maths Quiz noq=0 score=0 import math import pickle import random import time import pickle def write(name, finalscore, totalquestions, score, file_Object): pickle.dump ((str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,file_Object) return group=input("What mentor group are you in?: ") name=input("What is your name?: ") print ("Hello " + name + ". How many questions would you like to do?:") totalquestions=int(input(" ")) for i in range (0,(totalquestions)): noq=noq+1 print ("Question " +str(noq)) numberone=random.randint(1, 10) numbertwo=random.randint(1, 10) answer=int(numberone) + int(numbertwo) print ("What is " +str(numberone) + "+" + str(numbertwo) + "?:") uanswer=int(input("")) if answer==uanswer: print("That is correct!!!") score=score +1 print ("Your score is.....") time.sleep(0.5) print("" +str(score) + " out of " + str(i+1)) time.sleep(1) else: print ("Sorry, that is wrong!!!") score=score print ("Your score is.....") time.sleep(0.5) print ("" +str(score) + " out of " + str(i+1)) time.sleep(1) time.sleep(0.5) print ("Your final score is.....") finalscore=score/totalquestions finalscore=finalscore*100 time.sleep(3) print ("" +str(finalscore)+ " percent") #file write############################################################################### if group == 10G2: file_name='10G2 Scores.txt' fileObject= open(file_Name,'w') pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject) fileObject.close() elif group == 10G1: file_name='10G1 Scores.txt' fileObject = open(file_Name,'w') pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject) fileObject.close() elif group == 10G3: file_name='10G3 Scores.txt' fileObject = open(file_Name,'w') pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject) fileObject.close() elif group == 10G4: file_name='10G4 Scores.txt' fileObject = open(file_Name,'w') write () fileObject.close() elif group == 10G5: file_name='10G5 Scores.txt' fileObject = open(file_Name,'w') write () fileObject.close() elif group == 10G6: file_name='10G6 Scores.txt' fileObject = open(file_Name,'w') write () fileObject.close() elif group == 10G7: file-name='10G7 Scores.txt' fileObject = open(file_Name,'w') write () fileObject.close() Answer: Try changing this line if group == 10G2: to: if group == '10G2':
Python class variable dependencies Question: If have a class that looks something like import numpy as np class Test(object): def __init__(self, args): self.x = args[0] self.y = args[1] self.values = np.array([self.x, self.y]) And I want to be able to update both `x` and `values[0]` with a single call a = Test((1., 2.)) a.x = 2. so that `a.x = 2.` and `a.values[0] = 2.` I am sort of new when it comes to OOP, so please excuse me if this is obvious. Answer: You'll need to write a function to do this: def SetX(value): self.x = value self.values[0] = value
Python setuptools package_data - pip fails on subfolders Question: I am trying to make my own pip package installation to work and I have troubles with subfolders in additional data specified in package_data. Everything seems to be fine (all data are included in produced .zip file), but when I run "pip install myapp", it says: "error: can't copy 'myapp\web\styles': doesn't exist or not a regular file" Dirtree: projectDir setup.py myapp __init__.py webapp.py web index.html styles style.css setup.py: from setuptools import setup setup ( zip_safe = False, name = "myapp", version = "0.1", packages = ["myapp"], include_package_data = True, package_data = { "myapp": ["web/*", "web/styles/*"] } ) Command to create package: python setup.py sdist Command to install: pip install myapp-0.1.zip I have even try to specify MANIFEST.in (with no success): include myapp/web/*.* include myapp/web/styles/*.* When I specify only MANIFEST.in withou package_data, installation success, but there are no files in site-packages/myapp/web so no package_data were copied. I am quite desperate because I haven't found any suggestion what I am doing wrong and I have spent long time to make it work. Thaks for any advice. Answer: Ok, so I have a solution: I have used only MANIFEST.in and removed package_data from setup.py and everything works fine. I thought I have tried this before, but I was wrong.
Server/Client continuous connection in python? (Python 3x) Question: Hi everyone this is my firs post here and I have a question about python server/client continuous connection where I can write as a client and comes back to the server, and it shouldn't stop till i type "end". > **This is my server:** from socket import * def main(): s=socket(AF_INET, SOCK_STREAM) s.bind((' ', 10530)) s.listen(1) conn, (rmip, rmpt) = s.accept() while 1: print ("Connected by ", str(rmip)+": " +str(rmpt)) data = conn.recv(1024) print ("What was delivered: ", data.decode()) if not data: break conn.close() main() > **This si my client:** from socket import * def main(): s = socket(AF_INET, SOCK_STREAM) s.connect(('localhost',10530)) sendme = input("What do you want to send\n") s.send(sendme.encode()) main() Now all I want is this connection to continue so I can write something else again and again client-server, until the client ends the connection, [Like shown in the picture here](http://i.stack.imgur.com/KWGwN.jpg) Thank you very much for help! :) Answer: You have a `while` loop in your server which keeps going until an empty payload is received. You don't have any looping construct in your client, however, so it will exit after one message. Add a loop to your client as well, and check for an input of `end`, at which point you can break out of the loop.
Customize pyuic's resource import statement? Question: When I use this command on windows: python -m PyQt4.uic.pyuic user_interface.ui -o user_interface.py After that, I add a resource: pyrcc4.exe -py3 images.qrc -o images.py And I end up with two beautiful files, **user_interface.py** , and **images.py**. The problem is that the **user_interface.py** file ends with this line of code: ... all QT stuff here. import images_re And because this is a module that is called from many parents, it has to be imported like this: import myapp.gui.images_re When I change the line of code it works perfectly, but every time I modify the user_interface.ui file and then execute the batch, it will be overwritten, and I will have to change it manually every time. Is there any way to tell pyuic what to write in that import statement? Or any batch code that can be executed after the pyuic and changes that line of code? Or some tweak on the .py file that calls **user_interface.py** for example to change the default directory so it imports images_re from there? Answer: If you save the resource file in the same package directory as the ui file, then you can use the [\--from_imports](http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#cmdoption- pyuic4--from-imports) option. This will add the following import line to the ui file: from . import resources_rc And the command would look something like this: pyuic4 --from-imports --output file.py file.ui (NB: the `pyuic` executable name may differ, depending on the platform).
etree import not working- Python 2.7.5 Question: I'm trying to use elementtree to parse xml but the import is giving me an error. **No module named etree** I've tried : from xml.etree import ElementTree as ET import xml.etree.ElementTree as ET I have elementtree downloaded in my python library on mac. Am I missing something? Thank you Answer: [ElementTree is a part of the standard Python library](https://docs.python.org/2/library/xml.etree.elementtree.html), you shouldn't need to install anything to get it to work. Using a [standard install from IdeOne, shows your first line works, with no extra libraries](https://ideone.com/Ywik3H). from xml.etree import ElementTree as ET print ET gives: > Success time: 0.03 memory: 44896 signal:0 > > > <module 'xml.etree.ElementTree' from '/usr/lib/pypy/lib- > python/2.7/xml/etree/ElementTree.py'> > Something has gone wrong with your install, or you are trying to use a [third party library like lXML](http://lxml.de/tutorial.html). * * * Alternatively, [you have a file named xml.py](http://stackoverflow.com/a/10324708/764357) in your project that is overriding your Python install. You can check this by running the following code in your file _before_ any other imports. import xml print xml.__file__ If the path doesn't look like this, and shows a path to your local project thats your problem. /usr/lib/python2.7/xml/__init__.pyc
IPython notebook: how to reload all modules in a specific Python file? Question: I define many modules in a file, and add `from myFile import *` to the first line of my ipython notebook so that I can use it as dependency for other parts in this notebook. Currently my workflow is: 1. modify `myFile` 2. restart the Ipython kernel 3. rerun all code in Ipython. Does anyone know if there is a way to reload all modules in `myFile` without need to restart the Ipython kernel? Thanks! Answer: From the ipython docs: In [1]: %load_ext autoreload In [2]: %autoreload 2 In [3]: from foo import some_function In [4]: some_function() Out[4]: 42 In [5]: # open foo.py in an editor and change some_function to return 43 In [6]: some_function() Out[6]: 43 You can also configure the auto reload to happen automatically by doing this: `ipython profile create` and adding the following to `~/.config/ipython/profile_default/ipython_config.py` c.InteractiveShellApp.extensions = ['autoreload'] c.InteractiveShellApp.exec_lines = ['%autoreload 2'] c.InteractiveShellApp.exec_lines.append('print("Warning: disable autoreload in ipython_config.py to improve performance.")') Note: If you rename a function, you need to rerun your `import` statement
QuantLib cpibond bond example in Python Question: I am trying to get the official C++ cpibond example working in Python. The original example is here: <https://github.com/lballabio/quantlib/blob/master/QuantLib/test- suite/inflationcpibond.cpp> and for scala here: <https://github.com/lballabio/quantlib/blob/master/QuantLib- SWIG/Scala/examples/CPIBond.scala> When I run what I have attempted I get this error: > RuntimeError: 1st iteration: failed at 1st alive instrument, maturity > September 1st, 2010, reference date September 1st, 2009: 2nd leg: Missing UK > RPI fixing for September 1st, 2009 Here is my attempt: import QuantLib as ql calendar = ql.UnitedKingdom() dayCounter = ql.ActualActual(); convention = ql.ModifiedFollowing today = ql.Date(20, 11, 2009) evaluationDate = calendar.adjust(today) ql.Settings.instance().setEvaluationDate(evaluationDate) yTS = ql.YieldTermStructureHandle(ql.FlatForward(evaluationDate, 0.05, dayCounter)) from_date = ql.Date(20, ql.July, 2007); to_date = ql.Date(20, ql.November, 2009); tenor = ql.Period(1, ql.Months) rpiSchedule = ql.Schedule(from_date, to_date, tenor, calendar, convention, convention, ql.DateGeneration.Backward, False) cpiTS = ql.RelinkableZeroInflationTermStructureHandle() inflationIndex = ql.UKRPI(False, cpiTS) fixData = [206.1, 207.3, 208.0, 208.9, 209.7, 210.9, 209.8, 211.4, 212.1, 214.0, 215.1, 216.8, 216.5, 217.2, 218.4, 217.7, 216, 212.9, 210.1, 211.4, 211.3, 211.5, 212.8, 213.4, 213.4, 213.4, 214.4,213.4, 214.4] dte_fixings=[dtes for dtes in rpiSchedule] print len(dte_fixings) print len(fixData) #must be the same length inflationIndex.addFixings(dte_fixings, fixData) observationLag = ql.Period(2, ql.Months) zciisData =[( ql.Date(25, ql.November, 2010), 3.0495 ), ( ql.Date(25, ql.November, 2011), 2.93 ), ( ql.Date(26, ql.November, 2012), 2.9795 ), ( ql.Date(25, ql.November, 2013), 3.029 ), ( ql.Date(25, ql.November, 2014), 3.1425 ), ( ql.Date(25, ql.November, 2015), 3.211 ), ( ql.Date(25, ql.November, 2016), 3.2675 ), ( ql.Date(25, ql.November, 2017), 3.3625 ), ( ql.Date(25, ql.November, 2018), 3.405 ), ( ql.Date(25, ql.November, 2019), 3.48 ), ( ql.Date(25, ql.November, 2021), 3.576 ), ( ql.Date(25, ql.November, 2024), 3.649 ), ( ql.Date(26, ql.November, 2029), 3.751 ), ( ql.Date(27, ql.November, 2034), 3.77225), ( ql.Date(25, ql.November, 2039), 3.77 ), ( ql.Date(25, ql.November, 2049), 3.734 ), ( ql.Date(25, ql.November, 2059), 3.714 )] lRates=[rtes/100.0 for rtes in zip(*zciisData)[1]] baseZeroRate = lRates[0] zeroSwapHelpers = [ql.ZeroCouponInflationSwapHelper(a[1]/100,observationLag, a[0], calendar, convention, dayCounter, inflationIndex) for a in zciisData] cpiTS.linkTo(ql.PiecewiseZeroInflation( evaluationDate, calendar, dayCounter, observationLag, inflationIndex.frequency(), inflationIndex.interpolated(), baseZeroRate, yTS, zeroSwapHelpers, 1.0e-12, ql.Linear())) notional = 1000000 fixedRates = [0.1] fixedDayCounter = ql.Actual365Fixed() fixedPaymentConvention = ql.ModifiedFollowing fixedPaymentCalendar = ql.UnitedKingdom() contractObservationLag = ql.Period(3, ql.Months) observationInterpolation = ql.CPI.Flat settlementDays = 3 growthOnly = True baseCPI = 206.1 startDate = ql.Date(2, 10, 2007) endDate = ql.Date(2, 10, 2052) fixedSchedule = ql.Schedule(startDate, endDate, ql.Period(6, ql.Months), fixedPaymentCalendar, ql.Unadjusted, ql.Unadjusted, ql.DateGeneration.Backward, False) bond = ql.CPIBond(settlementDays, notional, growthOnly, baseCPI, contractObservationLag, inflationIndex, observationInterpolation, fixedSchedule, fixedRates, fixedDayCounter, fixedPaymentConvention) bondEngine=ql.DiscountingBondEngine(yTS) bond.setPricingEngine(bondEngine) print bond.NPV() print bond.cleanPrice() Most of my problem is that I am finding it difficult to get to grips with how the objects fit together. Answer: got the above example working: import QuantLib as ql import datetime as dt calendar = ql.UnitedKingdom() dayCounter = ql.ActualActual(); convention = ql.ModifiedFollowing lag = 3 today = ql.Date(5,3,2008) evaluationDate = calendar.adjust(today) issue_date = calendar.advance(evaluationDate,-1, ql.Years) maturity_date = ql.Date(2,9,2052) fixing_date = calendar.advance(evaluationDate,-lag, ql.Months) ql.Settings.instance().setEvaluationDate(evaluationDate) yTS = ql.YieldTermStructureHandle(ql.FlatForward(evaluationDate, 0.05, dayCounter)) tenor = ql.Period(1, ql.Months) from_date = ql.Date(20, ql.July, 2007); to_date = ql.Date(20, ql.November, 2009); rpiSchedule = ql.Schedule(from_date, to_date, tenor, calendar, convention, convention, ql.DateGeneration.Backward, False) # this is the going to be holder the inflation curve. cpiTS = ql.RelinkableZeroInflationTermStructureHandle() inflationIndex = ql.UKRPI(False, cpiTS) fixData = [206.1, 207.3, 208.0, 208.9, 209.7, 210.9, 209.8, 211.4, 212.1, 214.0, 215.1, 216.8, 216.5, 217.2, 218.4, 217.7, 216, 212.9, 210.1, 211.4, 211.3, 211.5, 212.8, 213.4, 213.4, 213.4, 214.4] dte_fixings=[dtes for dtes in rpiSchedule] print len(fixData) print len(dte_fixings[:len(fixData)]) #must be the same length #inflationIndex.addFixings(dte_fixings[:len(fixData)], fixData) #Current CPI level #last observed rate fixing_rate = 214.4 inflationIndex.addFixing(fixing_date, fixing_rate) observationLag = ql.Period(lag, ql.Months) zciisData =[( ql.Date(25, ql.November, 2010), 3.0495 ), ( ql.Date(25, ql.November, 2011), 2.93 ), ( ql.Date(26, ql.November, 2012), 2.9795 ), ( ql.Date(25, ql.November, 2013), 3.029 ), ( ql.Date(25, ql.November, 2014), 3.1425 ), ( ql.Date(25, ql.November, 2015), 3.211 ), ( ql.Date(25, ql.November, 2016), 3.2675 ), ( ql.Date(25, ql.November, 2017), 3.3625 ), ( ql.Date(25, ql.November, 2018), 3.405 ), ( ql.Date(25, ql.November, 2019), 3.48 ), ( ql.Date(25, ql.November, 2021), 3.576 ), ( ql.Date(25, ql.November, 2024), 3.649 ), ( ql.Date(26, ql.November, 2029), 3.751 ), ( ql.Date(27, ql.November, 2034), 3.77225), ( ql.Date(25, ql.November, 2039), 3.77 ), ( ql.Date(25, ql.November, 2049), 3.734 ), ( ql.Date(25, ql.November, 2059), 3.714 )] #lRates=[rtes/100.0 for rtes in zip(*zciisData)[1]] #baseZeroRate = lRates[0] zeroSwapHelpers = [ql.ZeroCouponInflationSwapHelper(rate/100,observationLag, date, calendar, convention, dayCounter, inflationIndex) for date,rate in zciisData] # the derived inflation curve jj=ql.PiecewiseZeroInflation( evaluationDate, calendar, dayCounter, observationLag, inflationIndex.frequency(), inflationIndex.interpolated(), zciisData[0][1],#baseZeroRate, yTS, zeroSwapHelpers, 1.0e-12, ql.Linear()) cpiTS.linkTo(jj) notional = 1000000 fixedRates = [0.1] fixedDayCounter = ql.Actual365Fixed() fixedPaymentConvention = ql.ModifiedFollowing fixedPaymentCalendar = ql.UnitedKingdom() contractObservationLag = ql.Period(3, ql.Months) observationInterpolation = ql.CPI.Flat settlementDays = 3 growthOnly = False baseCPI = 206.1 fixedSchedule = ql.Schedule(issue_date, maturity_date, ql.Period(ql.Semiannual), fixedPaymentCalendar, ql.Unadjusted, ql.Unadjusted, ql.DateGeneration.Backward, False) bond = ql.CPIBond(settlementDays, notional, growthOnly, baseCPI, contractObservationLag, inflationIndex, observationInterpolation, fixedSchedule, fixedRates, fixedDayCounter, fixedPaymentConvention) #bond2= ql.QuantLib.C bondEngine=ql.DiscountingBondEngine(yTS) bond.setPricingEngine(bondEngine) print bond.NPV() print bond.cleanPrice() compounding = ql.Compounded yield_rate = bond.bondYield(fixedDayCounter,compounding,ql.Semiannual) y_curve = ql.InterestRate(yield_rate,fixedDayCounter,compounding,ql.Semiannual) ##Collate results print "Clean Price:", bond.cleanPrice() print "Dirty Price:", bond.dirtyPrice() print "Notional:", bond.notional() print "Yield:", yield_rate print "Accrued Amount:", bond.accruedAmount() print "Settlement Value:", bond.settlementValue() #suspect there's more to this for TIPS print "Duration:", ql.BondFunctions.duration(bond,y_curve) print "Convexity:", ql.BondFunctions.convexity(bond,y_curve) print "Bps:", ql.BondFunctions.bps(bond,y_curve) print "Basis Point Value:", ql.BondFunctions.basisPointValue(bond,y_curve) print "Yield Value Basis Point:", ql.BondFunctions.yieldValueBasisPoint(bond,y_curve) print "NPV:", bond.NPV() # get the cash flows: #cf_list=[(cf.amount(),cf.date()) for cf in bond.cashflows()] def to_datetime(d): return dt.datetime(d.year(),d.month(), d.dayOfMonth()) for cf in bond.cashflows(): try: amt=cf.amount() rte=jj.zeroRate(cf.date()) zc=yTS.zeroRate(cf.date(),fixedDayCounter,compounding,ql.Semiannual).rate() except: amt=0 rte=0 zc=0 print to_datetime(cf.date()),amt,rte,zc The issue it seems was that the inflationIndex object needed one date instead of multiple index points. My assumption was it would pull out the latest valid point. The way the pricer works is that the real coupons are increased by the inflation rate curve term structure, zciisData. The result therefore becomes a nominal future cash flow. To price then the bondpricer simply discounts these by the nominal term structure. I added some additional code to print the determined cash flows and the "growth factor" and then the discount rate.
Getting Camera model information of an image using Python Question: I am working on python automation in which I have to collect the camera model (canon, Nikon etc.) information of an image. I searched a lot but I am getting only pixel resolution, size and other data of an image. Is there any API or library in which we can find the camera related each and every information or a particular API which gives camera model information.? Answer: The Python [`EXIF`](https://github.com/ianare/exif-py) library can be used to extract a lot of information from a JPG image, including the `Image Make` and `Image Model`, for example: import EXIF with open(r"sample.jpg", 'rb') as f_jpg: tags = EXIF.process_file(f_jpg, details=True) print tags['Image Make'] print tags['Image Model'] This could display something like: Panasonic DMC-TZ20 Note, I have not tested this with the latest version.
python array manipulation and rearranging Question: I am trying to manipulate an array and perform operations. My input is an array a= [['f' '0' '1' '0' '1' '0'] ['o' '0' '0' '1' '0' '0'] ['o' '0' '1' '0' '1' '1'] ['!b' '1' '0' '1' '0' '0'] ['a' '0' '0' '1' '0' '0'] ['r' '0' '1' '0' '1' '1']] If I take the first row, my output should just be the columns in which 1 is present. Similarly, I do for each row and get output. So my output should be an array. output = [['f' '1' '1' 'o' '0' '0' 'o' '1' '1' '!b' '0' '0' 'a' '0' '0' 'r' '1' '1' ] ['f' '0' 'o' '1' 'o' '0' '!b' '1' 'a' '1' 'r' '0' ] ['f' '1' '1' '0' 'o' '0' '0' '0' 'o' '1' '1' '1' '!b' '0' '0' '0' 'a' '0' '0' '0' 'r' '1' '1' '1'] ['f' '0' '0' 'o' '0' '1' 'o' '0' '0' '!b' '1' '1' 'a' '0' '1' 'r' '0' '0' ] ['f' '0' 'o' '1' 'o' '0' '!b' '1' 'a' '1' 'r' '0' ] ['f' '1' '1' '0' 'o' '0' '0' '0' 'o' '1' '1' '1' '!b' '0' '0' '0' 'a' '0' '0' '0' 'r' '1' '1' '1']] Here's my Code output = [] for i in a: for j in i: if j == 1: output = a[0:] output.append([n][j]) for n in len(i) else: pass Answer: For each row, produce a matrix that has only the columns that have a `'1'` in this row. import numpy as np a = np.array([['f', '0', '1', '0', '1', '0'], ['o', '0', '0', '1', '0', '0'], ['o', '0', '1', '0', '1', '1'], ['!b', '1', '0', '1', '0', '0'], ['a', '0', '0', '1', '0', '0'], ['r', '0', '1', '0', '1', '1']]) l = [] for r in a: l.append(a[:, [i for i, c in enumerate(r) if i == 0 or c == '1']]) print l This works but perhaps someone more familiar with numpy might be able to do better. Produces: [array([['f', '1', '1'], ['o', '0', '0'], ['o', '1', '1'], ['!b', '0', '0'], ['a', '0', '0'], ['r', '1', '1']], dtype='|S2'), array([['f', '0'], ['o', '1'], ['o', '0'], ['!b', '1'], ['a', '1'], ['r', '0']], dtype='|S2'), array([['f', '1', '1', '0'], ['o', '0', '0', '0'], ['o', '1', '1', '1'], ['!b', '0', '0', '0'], ['a', '0', '0', '0'], ['r', '1', '1', '1']], dtype='|S2'), array([['f', '0', '0'], ['o', '0', '1'], ['o', '0', '0'], ['!b', '1', '1'], ['a', '0', '1'], ['r', '0', '0']], dtype='|S2'), array([['f', '0'], ['o', '1'], ['o', '0'], ['!b', '1'], ['a', '1'], ['r', '0']], dtype='|S2'), array([['f', '1', '1', '0'], ['o', '0', '0', '0'], ['o', '1', '1', '1'], ['!b', '0', '0', '0'], ['a', '0', '0', '0'], ['r', '1', '1', '1']], dtype='|S2')]
Python: Average a list and append to dictionary Question: I have a dictionary of names with a number (a score) assigned to them. The file is laid out as so: Person A,7 Peron B,6 If a name is repeated in the file e.g. Person B occurred on 3 lines with 3 different scores I want to calculate the mean average of these scores then append this result to a dictionary in the form of a list. However, I keep encountering an error when i try to sort the dictionary. Code below. else: for key in results: keyValue = results[key] if len(keyValue) > 1: # Line below this needs modification keyValue = list(sum(keyValue)/len(keyValue)) newResults[key] = keyValue # Error in above code... else: newResults[key] = keyValue print(newResults) print(sorted(zip(newResults.values(), newResults.keys()), reverse=True)) Results is a dictionary of the people (the keys) and their scores (the values) where the values are lists so that: results = {'Bob':[7],'Jane':[8,9]} Answer: If you're using Python 3.x you can use its `statistics` library which contains a function `mean`. Now assuming that your dict looks like: `results = {'Bob': [7], 'Jane': [8, 9]}` you can create a `newResults` dict like this: from statistics import mean newResults = {key: mean(results[key]) for key in results} This is called dict comprehension and as you can see it's kinda intuitive. Starting with `{` you're telling that dict is going to be created. Then with `key: value` you're defining its structure. Lastly, with `for` loop you iterate over a collection that will be used for the dict creation. You can achieve the same with: newResults = {} for key in results: newResults[key] = mean(results[key]) You want to sort the dict in the end. Unfortunately it's not possible. You can either create an `OrderedDict`, which remembers the items insertion order or a list which will contain sorted keys to your dict. The latter will look like: sortedKeys = sorted(newResults, key=lambda x: newResults[x])
TAB Key in Python Question: I'm working on a Python application that asks the user for two inputs, but in order for them to go to the next input, they need to hit ENTER/RETURN, is it possible to also use the TAB key? Right now, if the user hits TAB, it'll just add a space to the text. [EDIT] I did try the sys.stdin method but all I get is a blank screen. Answer: As stated [here](http://stackoverflow.com/questions/19084223/python-raw-input- use-tab-instead-of-enter), if you use `raw_input` or `input` it is not possible and you would have to read from `stdin` directly import sys def input_with_tab(): text = "" while True: char = sys.stdin.read(1) # read 1 character from stdin if char == '\t': # if a tab was read break text += char return text print("Write something:") text = input_with_tab() print(text)
Printing UTF32 Symbols in Word Macros Question: I am playing around with VBA for Word, and I am working on a project to do a batch find/replace in a word document. I imported a list of find/replace terms from a .csv. The issue I'm running into is that I want to replace words with symbols that represent the words. For example, if I use the word bread, I want to replace it with the UTF-32 symbol for bread (Unicode decimal 127838/ hex 0x1f35e). When I was doing this manually using the built in MS-Word find/replace, this worked fine, I would simply type in alt+127838 in the replace box and it would work without a hitch, but doing UTF-32 find/replace in batch seems to be giving me trouble. If I use ChrW() it will be out of range because ChrW only accepts values up to 65,535. It can't handle the 17th bit. It gives me a runtime error if I try plugging that in. I tried using a \U escape character, but then it only replaced it literally with "\U127838" which isn't very helpful. Not sure if VBA even supports the unicode escape character. If I don't put it in quotes, it gives me a syntax error. Although I am not new to programming, I am new to VBA and VB. I checked online, and it seems the UTF32Encoding class for VB doesn't work with VBA <https://msdn.microsoft.com/en- us/library/system.text.utf32encoding(v=vs.90).aspx> It could be that I'm unfamiliar with the nuances between VB and VBA, but when I tried the initializer: Dim u32LE As New UTF32Encoding(False, True) It gave me a syntax error in my VBA code. I tried using the Imports statement, but that also confused my compiler. I'm not sure if I'm doing something wrong, or if VBA doesn't support this class. Let me know if VBA just doesn't support printing out UTF32 characters and I should try using something like Python or Java instead. Your help is much appreciated! Here is a look at the function I'm writing. I commented out the Imports line because it gave me an error (it says method or member not found highlighting ".Text") Sub findReplaceUnicode(ByVal findItem As String, unicode As Long) 'Imports System.Text Dim u32LE As New UTF32Encoding(False, True) Selection.find.ClearFormatting Selection.find.Replacement.ClearFormatting With Selection.find .Text = findItem .Replacement.Text = ChrW(unicode) .Replacement.font.Name = "Segoe UI Symbol" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.find.Execute replace:=wdReplaceAll End Sub Answer: Well, to begin with you cannot use .NET namespaces in your VBA code. It is a false lead to use a VB class in a VBA program. There is no compatibility. The way to solve this problem is to not use UTF32. However, many of these symbols also have a dual UTF-16 encoding. For example, the bread symbol (UTF-32 0x1f35e) can also be typed by two UTF-16 entries: 0xD83C 0xDF5E (d83cdf5e). <http://www.fileformat.info/info/unicode/char/1f35e/index.htm> File Format.info is a useful site in finding that translation. A way to replace a symbol with over 17 bits would be to enter: .Replacement.Text = ChrW(first) & ChrW(second) Where first is the first half of the composite UTF-16 entry and second is the second half of the composite UTF-16 entry. A good rule of thumb is when in doubt, record a macro manually, then reverse engineer the results.
send POST request to web services in python Question: I need to consume a several's SOAP web services, if I send a xml file as request I get the response without issues. But I want to send only some arguments and not all the xml file To make a request I send like the using REQUESTS library: import requests with open("/home/WSProject/xmlws/media/QueryTest.xml","r") as request_data = archivo.read() target_url = "http://1.1.1.1:4384/services/BbServices?wsdl" headers = {'Content-type':'text/xml'} data_response = requests.post(target_url, data=request_data, headers=headers).text print data_response The xml file I send as request is like this: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:bbs="http://example.com/bme/interface/bbservices" xmlns:cbs="http://example.com/bme/interface/cbscommon" xmlns:bbc="http://example.com/bme/interface/bbcommon"> <soapenv:Header/> <soapenv:Body> <bbs:QueryCDRRequestMsg> <RequestHeader> <cbs:Version>1</cbs:Version> <!--Optional:--> <cbs:BusinessCode>1</cbs:BusinessCode> <cbs:MessageSeq>${=new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(new Date())}</cbs:MessageSeq> <!--Optional:--> <cbs:OwnershipInfo> <cbs:BEID>1</cbs:BEID> <!--Optional:--> <cbs:BRID>1</cbs:BRID> </cbs:OwnershipInfo> <cbs:AccessSecurity> <cbs:LoginSystemCode>985</cbs:LoginSystemCode> <cbs:Password>xyYSFeOmUQ==</cbs:Password> <!--Optional:--> <cbs:RemoteIP>1.1.1.1</cbs:RemoteIP> </cbs:AccessSecurity> <!--Optional:--> <cbs:OperatorInfo> <cbs:OperatorID>5098</cbs:OperatorID> <!--Optional:--> <cbs:ChannelID>1</cbs:ChannelID> </cbs:OperatorInfo> <cbs:TimeFormat> <cbs:TimeType>1</cbs:TimeType> <!--Optional:--> <cbs:TimeZoneID>1</cbs:TimeZoneID> </cbs:TimeFormat> </RequestHeader> <QueryCDRRequest> <bbs:SubAccessCode> <bbc:Identity>98705702</bbc:Identity> </bbs:SubAccessCode> <bbs:BillCycle>20151001</bbs:BillCycle> <bbs:TotalCDRNum>0</bbs:TotalCDRNum> <bbs:BeginRowNum>0</bbs:BeginRowNum> <bbs:FetchRowNum>100</bbs:FetchRowNum> </QueryCDRRequest> </bbs:QueryCDRRequestMsg> </soapenv:Body> </soapenv:Envelope> I get the value of the arguments from a HTML form, the arguments are Identity and BillCycle <bbs:SubAccessCode> <bbc:Identity>98705702</bbc:Identity> </bbs:SubAccessCode> <bbs:BillCycle>20151001</bbs:BillCycle> Now I am overwritten a file with the value of the arguments and post the file as request. I tried send only some arguments or get a list of all the methods from the web service but I get an error using SUDS > suds.transport.TransportError: HTTP Error 403: Forbidden If possible send only the arguments instead of the whole file using SUDS or REQUESTS? Answer: Time has passed, but maybe someone finds it useful: This is snippet from my project. You can add parameters directly to method. SUDS is very powerful in that way, and of course check out [docs](https://fedorahosted.org/suds/wiki/Documentation). from tkinter import * from tkinter import ttk import sys from suds.client import * class SoapClass: def __init__(self, master): self.client = Client('http://www.webservicex.net/ConvertWeight.asmx?WSDL', username='', password='', faults=False) Button(master, text='Call', command=self.request).pack() def request(self): methodName = 'ConvertWeight' params = [80, 'Kilograms', 'Grams'] MethodToExecute = getattr(self.client.service, methodName) try: response = MethodToExecute(*params) except WebFault as e: response = e print(response) root = Tk() app = SoapClass(root) root.mainloop()
Python script works in librarys examples folder, but not in parent directory Question: I have a newbie problem. I have a Raspberry Pi 2 computer. I connected DHT11 sensor to GPIO PIN 4. Next, I've installed Adafruit_DHT_python library by running setup.py file using command: sudo ./setup.py After installation i ran example from /examples folder by: sudo ./AdafruitDHT.py 11 4 It works like charm. This scriptis using installed library by importing it: import Adafruit_DHT When i write my own code in examples folder - it works. When I execute this code from parent folder, it returns this error: ImportError: No module named Raspberry_Pi_2_Driver When I installed this library in my system, should it work from any location in file system? Also, when i try to execute script in examples folder as normal user(it have all needed premissions), it returns this error: ImportError: No module named Adafruit_DHT Answer: I had the same issue, just used import sys import sys sys.path.append("/home/me/mypy") to the path of the Adafruit_Python_DHT module (replace "/home/me/mypy"). Basically, we just have to tell python where it is. Something isn't installing properly.
getting invoking module's name in Python Question: Is there a more straight-forward way of getting the name of the invoking module than this: script_file_path = sys.argv[0] top_module_name = None for frame in reversed(inspect.stack()): if frame[1] == script_file_path: top_module_name = inspect.getmodule(frame[0]).__name__ Answer: I think both of the following are certainly more efficient, and the first seems a bit more straightforward (at least, you deal with fewer indices, file paths, etc.). I think the first would work most of the time (but I have not tested it fully): import inspect def get_invoking_module(): frame = inspect.currentframe() return frame.f_back.f_globals["__name__"] This should work all the time: def get_invoking_module(): frame = inspect.currentframe() current_module = inspect.getmodule(frame) while inspect.getmodule(frame) == current_module: frame = frame.f_back # walk back up the frames if frame: return frame.f_globals["__name__"]
Finding and uninstalling PIL on Mac Question: I want to install Pillow and have read in many places this only works if PIL is removed. Somewhere I have PIL installed but I am unable to find it or remember how it was installed. I'm pretty much a ctrl+c and ctrl+v guy when it comes to installing things through terminal, so I imagine I had some trouble installing it in the first place. I have tried pip uninstall PIL easy_install uninstall PIL brew uninstall PIL and run out of ideas. I can't even find any file with name "PIL" with spotlight. Just want to find a way to get rid of PIL and install Pillow so I can add text to a few hundred images. Running python 2.7 on El Capitan Answer: To find where PIL is located on your machine, use Python to import it and have it print out its location: $ python Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import PIL >>> PIL.__file__ On my system, this gives: '/Library/Python/2.7/site-packages/PIL/__init__.pyc' From this you can see where your `site-packages` directory is located. Now exit python, go into `/Library/Python/2.7/site-packages/` (your exact path may differ from mine) and delete the folder `PIL`. That should get rid of it. cd /Library/Python/2.7/site-packages/ sudo rm -rf PIL
Python PeeWee IntegerField - Default value of unix timestamp Question: I would like to manage timestamps in my database using seconds since epoch using a PeeWee IntegerField rather than a DateTimeField. I know that the field definition can take a default value using a callable, but I would need to do something like: timestamp = IntegerField(default=int(datetime.datetime.now().strftime('%s'))) Which I suppose is incorrect since the default value should not actually invoke the callable. I also tried wrapping this in a function and passing that function as a callable: def get_timestamp(): return int(datetime.datetime.now().strftime('%s')) timestamp = IntegerField(default=get_timestamp) However this did not work either. Is there a way to accomplish this, or do I have to retro-fit my data to use DateTimeFields instead? Answer: I see you mentioned that you tried wrapping your function call, I'm surprised that didn't work for you, because it appears to work fine for me: >>> from datetime import datetime >>> from peewee import * >>> db = SqliteDatabase(':memory:') >>> def get_ts(): ... return int(datetime.now().strftime('%s')) >>> get_ts() 1448471382 >>> class TestModel(Model): ... ts = IntegerField(default=get_ts) ... class Meta: ... database = db >>> TestModel.create_table() >>> tm = TestModel.create() >>> tm.ts 1448471421 >>> ts_from_db = TestModel.get(TestModel.id == tm.id) >>> ts_from_db.ts 1448471421 The reason you need to wrap it is because the default param takes a _callable_ , and if you pass just the result of a function call, it interprets it as just another static value.
When registering a table using the %pyspark interpreter in Zeppelin, I can't access the table in %sql Question: I am using Zeppelin 0.5.5. I found this code/sample here for python as I couldn't get my own to work with %pyspark <http://www.makedatauseful.com/python-spark-sql-zeppelin-tutorial/>. I have a feeling his %pyspark example worked because if you using the original %spark zeppelin tutorial the "bank" table is already created. This code is in a notebook. %pyspark from os import getcwd # sqlContext = SQLContext(sc) # Removed with latest version I tested zeppelinHome = getcwd() bankText = sc.textFile(zeppelinHome+"/data/bank-full.csv") bankSchema = StructType([StructField("age", IntegerType(), False),StructField("job", StringType(), False),StructField("marital", StringType(), False),StructField("education", StringType(), False),StructField("balance", IntegerType(), False)]) bank = bankText.map(lambda s: s.split(";")).filter(lambda s: s[0] != "\"age\"").map(lambda s:(int(s[0]), str(s[1]).replace("\"", ""), str(s[2]).replace("\"", ""), str(s[3]).replace("\"", ""), int(s[5]) )) bankdf = sqlContext.createDataFrame(bank,bankSchema) bankdf.registerAsTable("bank") This code is in the same notebook but different work pad. %sql SELECT count(1) FROM bank org.apache.spark.sql.AnalysisException: no such table bank; line 1 pos 21 ... Answer: I found the problem to this issue. Prior to 0.6.0 the sqlContext variable is sqlc in %pyspark. Defect can be found here: <https://issues.apache.org/jira/browse/ZEPPELIN-134> > In Pyspark, the SQLContext is currently available in the variable name sqlc. > This is incosistent with the documentation and with the variable name in > scala which is sqlContext. > > sqlContext can be used as a variable for the SQLContext, in addition to sqlc > (for backward compatibility) > > Related code: <https://github.com/apache/incubator- > zeppelin/blob/master/spark/src/main/resources/python/zeppelin_pyspark.py#L66> The suggested workaround is simply to do the following in your %pyspark script sqlContext = sqlc Found here: <https://mail-archives.apache.org/mod_mbox/incubator-zeppelin- users/201506.mbox/%3CCALf24sazkTxVd3EpLKTWo7yfE4NvW032j346N+6AuB7KKZS_AQ@mail.gmail.com%3E>
Tkinter unable to alloc 71867 bytes Question: so, I am playing with GUI and with Tkinter, I was trying to make a notepad in python. my code so far: from Tkinter import * def hello(): print "hello!" ventana = Tk() barra_menu=Menu(ventana) barra_menu.add_command(label="Archivos") barra_menu.add_cascade(label="Guardar", menu =barra_menu) ventana.config(menu=barra_menu) notepad =Text() notepad.pack() ventana.mainloop() and when I run the script this error shows up: unable to alloc 71867 bytes This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Answer: I'm not sure what you want to achieve but it looks like this line barra_menu.add_cascade(label="Guardar", menu =barra_menu) is creating an infinite loop, as it is using itself as a parameter. The loop presumably ends when your system runs out of memory and hence the error. An immediate fix is to remove the `menu` parameter. If you want a menu attached to that button use a different menu.
pysnmp snmp get with managed objects Question: I'm trying to figure out how to load mibs and get the sysObjectID of a cisco switch and then resolve it into something human readable. Right now my code works but what is confusing me is are the arguments for getCmd(), instead of sending a string with OID how do I send a managed object? how can I change the following line in my code '1.3.6.1.2.1.1.2.0', To be something like 'sysObjectdID.0' but as a managed object #!/bin/env python from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.smi import view from pysnmp.smi.rfc1902 import ObjectType, ObjectIdentity cmdGen = cmdgen.CommandGenerator() print "Loading & Indexing MIB Modules..." mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibPath = mibBuilder.getMibPath() + ('/Users/jeffrey.dambly/Documents/mibs',) mibBuilder.setMibPath(*mibPath) cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.loadModules('CISCO-SMI', 'CISCO-PRODUCTS-MIB') mibView = view.MibViewController(mibBuilder) print 'Done' #print 'MIB symbol name lookup by name: ' #oid, label, suffix = mibView.getNodeName((1, 3, 6, 1, 4, 1, 9, 1, 12)) #print oid, label, suffix print 'Done' errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData('xxxxxxxx'), cmdgen.UdpTransportTarget(('192.168.8.10', 161)), '1.3.6.1.2.1.1.2.0', lookupNames=True, lookupValues=True, ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?' ) ) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) Answer: If you are using pysnmp 4.2.*, pass your MIB object to the MibVariable class instance. Or better use pysnmp 4.3 where [ObjectType/ObjectIdentity](http://pysnmp.sourceforge.net/docs/api- reference.html#mib-variables) classes are used for this purpose. Example code (pysnmp 4.3): getCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
Get spotify currently playing track Question: **EDIT : Let's try to clarify all this.** I'm writing a python script, and I want it to tell me the song that Spotify is currently playing. I've tried looking for libraries that could help me but didn't find any that are still maintained and working. I've also looked through Spotify's web API, but it does not provide any way to get that information. The only potential solution I found would be to grab the title of my Spotify (desktop app) window. But I didn't manage to do that so far. So basically, what I'm asking is whether anyone knows : * How to apply the method I'm already trying to use (get the window's title from a program), either in pure python or using an intermediary shell script. OR * Any other way to extract that information from Spotify's desktop app or web client. * * * **Original post :** I'm fiddling with the idea of a python status bar for a linux environment, nothing fancy, just a script tailored to my own usage. What I'm trying to do right now is to display the currently playing track from spotify (namely, the artist and title). There does not seem to be anything like that in their official web API. I haven't found any third party library that would do that either. Most libraries I found are either deprecated since spotify released their current API, or they are based on said API which does not do what I want. I've also read a bunch of similar question in here, most of which had no answers, or a deprecated solution. I thought about grabbing the window title, since it does diplay the information I need. But not only does that seem really convoluted, I also have difficulties making this happen. I was trying to get it by running a combination of the linux commands xdotools and xprop inside my script. It's worth mentionning that since I'm already using the psutil lib for other informations, I already have access to spotify's PID. Any idea how I could do that ? And in case my method was the only one you can think of, any idea how to actually make it work ? Your help will be appreciated. Answer: The Spotify client on Linux implements a D-Bus interface called MPRIS - Media Player Remote Interfacing Specification. <http://specifications.freedesktop.org/mpris-spec/latest/index.html> You could access the title (and other metadata) from python like this: import dbus session_bus = dbus.SessionBus() spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2") spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties") metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata") # The property Metadata behaves like a python dict for key, value in metadata.items(): print key, value # To just print the title print metadata['xesam:title']
Python Threading loop Question: I am have problem with this THREDING example. I have it working pretty good, but my problem is after it shows all 100 student threads. I am trying to put 20 random students in five different classes, but no matter what I do I can't seem to get the loop to work. If someone could please give me any direction on this, I would greatly appreciate it. import random, time from threading import Thread class Students(Thread): ''' Represents a sleepy thread.''' def __init__(self, number, sleepMax): ''' Creates a thread with a given Name and a random sleep interval less than the maximum. ''' Thread.__init__(self, name = "Student " + str(number)) self._RequestInterval = random.randint(1, sleepMax) def run(self): '''Prints the thread's name and sleep interval and sleep for that interval. Print the name again at wake-up. ''' count = 1 course = 1 print(" %s, Awaiting Request: %d seconds" % \ ( self.getName(), self._RequestInterval)) time.sleep(self._RequestInterval) if count == 20: print("%s Has A Spot Obtained in Class" % self.getName(), + course) print("Class", course, "has reached it limit!") count += 1 course =+ 1 else: #print("Class ", course, " is full.") print("%s Has A Spot Obtained in Class" % self.getName(), + course) def main(): ''' Creates the user's number of threads with sleep interval less than the user's maximum. Then start the threads''' NumberOfStudents = 100 RequestTimer = 5 threadList = [] for count2 in range(NumberOfStudents): threadList.append(Students(count2 + 1, RequestTimer)) for thread in threadList: thread.start() main() I have even tried running my variable outside the class, but crashes. Answer: There are several problems with this. 1. The `count` and `course` variables are only in the `run` function, so they are local to that function only. This means that threads are not sharing this information. The solution: move them outside so that they are _class_ variables (that is, they are now `Students.count` and `Students.course`). 2. Your print statements are a bit messed up. Using `print(a,b,c,...)` will print each of `a,b,c,...` on a separate line. The solution, enclose the thread's name and course number in a tuple and modify the format string slightly. 3. `course =+ 1` would've set `course` to `1` (because it's the same thing as `course = +1`) had that part of the if statement ever been executed (which it wasn't because of problem #1). Solution: flip the `=+` so that it's `course += 1`. 4. `count += 1` only happens when `count` is 20. You want this in the **else** part of the if statement. Also, in the **then** part, add the the line `count = 0` to reset the count. 5. Because these threads are running asynchronously, it can and does happen that `count` will go from 19 to 21 before you check `if count == 20`. Fixing this requires somewhat more advanced thread handling. Below is the code with each of these problems fixed, except the last one (where I changed `count == 20` to `count >= 20` to at least show something interesting happen). import random, time from threading import Thread class Students(Thread): ''' Represents a sleepy thread.''' count = 1 course = 1 def __init__(self, number, sleepMax): ''' Creates a thread with a given Name and a random sleep interval less than the maximum. ''' Thread.__init__(self, name = "Student " + str(number)) self._RequestInterval = random.randint(1, sleepMax) def run(self): '''Prints the thread's name and sleep interval and sleep for that interval. Print the name again at wake-up. ''' print(" %s, Awaiting Request: %d seconds" % \ ( self.getName(), self._RequestInterval)) time.sleep(self._RequestInterval) if Students.count >= 20: print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course)) print("Class", Students.course, "has reached it limit!") Students.course += 1 Students.count = 0 else: #print("Class ", course, " is full.") print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course)) Students.count += 1 def main(): ''' Creates the user's number of threads with sleep interval less than the user's maximum. Then start the threads''' NumberOfStudents = 100 RequestTimer = 5 threadList = [] for count2 in range(NumberOfStudents): threadList.append(Students(count2 + 1, RequestTimer)) for thread in threadList: thread.start() main()
inconsistent plot between matplotlib and seaborn in Python Question: i am trying to add errorbars using `plt.errorbar` to a `pointplot` in seaborn: import matplotlib import matplotlib.pylab as plt import seaborn as sns import pandas sns.set_style("white") data = pandas.DataFrame({"x": [0.158, 0.209, 0.31, 0.4, 0.519], "y": [0.13, 0.109, 0.129, 0.250, 1.10], "s": [0.01]*5}) plt.figure() sns.pointplot(x="x", y="y", data=data) plt.errorbar(data["x"], data["y"], yerr=data["s"]) plt.show() however the two plots look totally different even though the identical data is being plotted. what explains this and how can errorbars be added to a pointplot? Answer: It seems that `sns.pointplot` simply uses an array of `[0...n-1]` as x values and then uses the x values that you provide to label the ticks on the x-axis. You can check that by looking at `ax.get_xlim()` which outputs `[-0.5, 4.5]`. Therefore, when you provide the actual x values to `plt.plot` they just seem to be at a wrong position. I wouldn't say that this is a bug, since seaborn considers the input to `pointplot` to be categorial (here's the [documentation](http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.pointplot.html) for more info) You can solve this for your simple example by mimicking `seaborn`s behavoir: import matplotlib import matplotlib.pylab as plt import seaborn as sns import pandas import numpy as np sns.set_style("white") data = pandas.DataFrame({"x": [0.158, 0.209, 0.31, 0.4, 0.519], "y": [0.13, 0.109, 0.129, 0.250, 1.10], "s": [0.05]*5}) plt.figure() sns.pointplot(x="x", y="y", data=data) plt.errorbar(np.arange(5), data["y"], yerr=data["s"], color='r') plt.show() [![enter image description here](http://i.stack.imgur.com/HA34G.png)](http://i.stack.imgur.com/HA34G.png)
How to use a template html in different folder on Google App Engine python? Question: I am trying to use a templated html file in a different folder on python and I am running into file not found error. For example, index_path = os.path.join (os.path.join(os.path.dirname( __file__ ), '..', 'html'), 'index.html') index.html is in html folder. My python handler code is in handlers folder. . ├── app.yaml ├── handlers ├── html How does the project structure look like when it is deployed in Google App Engine? _Note_ : I am using: from google.appengine.ext.webapp import template template.render(index_path, {}) I modified the code based on suggestions below, still no luck: **handlers/index.py:** jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname('html'))) index_file = 'index.html' template = jinja_environment.get_template(index_file) content = template.render({}) self.response.out.write(content) **html/index.html:** **From app.yaml:** libraries: - name: jinja2 version: latest Answer: The preferred way of rendering templates in GAE is to use Jinja2. Jinja2 makes use of [loaders](http://jinja.pocoo.org/docs/dev/api/#loaders). > Loaders are responsible for loading templates from a resource such as the > file system You'll want to modify `app.yaml` so your application has access to Jinja2. libraries: - name: jinja2 version: latest then prep a template environment and a loader to help get templates from your `html` folder import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('html')) template = env.get_template('index.html') ... template.render(template_values) * * * EDIT : Make the handlers folder a package by adding a `__init__.py`. With a dir structure such as: . ├── app.yaml ├── handlers │   ├── hello.py │   └── __init__.py └── html └── index.html Then in the `handlers` section of `app.yaml` something akin to the following should do: handlers: - url: /.* script: handlers.hello.app # with app defined in hello.py ... libraries: - name: jinja2 version: latest
Merging numpy array elements using join() in python Question: Want to convert the following numpy array a a = [ array([['x', 'y', 'k'], ['d', '2', 'z'], ['a', '15', 'r']], dtype='|S2'), array([['p', '49'], ['l', 'n']], dtype='|S2'), array([['5', 'y'], ['33', 'u'], ['v', 'z']], dtype='|S2'), array([['f', 'i'], ['c', 'm'], ['u', '98']] dtype='|S2') ] into output b b = x!y.d!2.a!15 * x!k.d!z.a!r , p!49.l!n , 5!y.33!u.v!z , f!i.c!m.u!98 Consider each sub-array like this #x #y #k #d #2 #z #a #15 #r Then merge 0 and 1 columns with '!' and each row with '.' Then merge 0 and 2 column. And so on. Here **0,1** and **0,2** columns are merged using '*' And ',' is used to merge the sub-arrays Just merging the strings using `'!' '.' '*' ','` I tried the following code. Couldnt get the result though temp = [] for c in a: temp = a[0:] b = " * ".join(".".join(var1+"!"+var2 for var1,var2 in zip(temp,a) for row in a) print b print " , " Answer: How I understand, your solution maybe like this: import numpy as np a = [ np.array([['x', 'y', 'k'], ['d', '2', 'z'], ['a', '15', 'r']], dtype='|S2'), np.array([['p', '49'], ['l', 'n']], dtype='|S2'), np.array([['5', 'y'], ['33', 'u'], ['v', 'z']], dtype='|S2'), np.array([['f', 'i'], ['c', 'm'], ['u', '98']], dtype='|S2') ] aa = [] for k in a: bb = [] for i in range(len(k[0]) - 1): cc = [] for j in range(len(k)): cc.append('!'.join([k[j][0], k[j][i + 1]])) bb.append('.'.join(cc)) aa.append(' * '.join(bb)) b = ' , '.join(aa) print b If it's wrong, please, clarify your algorithm.
Sort timestamp in python dictionary Question: mydict = [{'Counted number': '26', 'Timestamp': '8/10/2015 13:07:38'},{'Counted number': '14','Timestamp': '8/10/2015 11:51:14'},{'Counted number': '28','Timestamp': '8/10/2015 13:06:27'}, {'Counted number': '20','Timestamp': '8/10/2015 12:53:42'}] How to sort this dict based on timestamp? Answer: This should work import time mydict.sort(key=lambda x:time.mktime(time.strptime(x['Timestamp'], '%d/%m/%Y %H:%M:%S')))
Python decorator for permission Question: it is my first time to use a decorator and I want to show something like this import functools def checkUser(tag): def dec(f0): @functools.wraps(f0) def wrapper(userName, loggedinUser): if userName == loggedinUser: return "You are allowed to view this page" else: return "Error" return wrapper return dec @checkUser def test2(userName, loggedinUser): return userName, loggedinUser print test2() and I am pretty sure it wouldn't work, this is just my idea. I just copied this codes and edited. I am really new to this. Answer: For the code you given, if you just want to check the user, there is no need for you to use the decorator, why not just compare them directly? Since you want to use decorator the check for permission. I think you may want to do this way: import functools def check_user(username, password): def dec(f): @functools.wraps(f) def wrapper(login_user, login_password): f(login_user, login_password) if username == login_user and password == login_password: return "You are allowed to view this page" else: return "Check your password and username" return wrapper return dec @check_user('jhon', 'passwd') def test2(login_user, login_password): print "hello, {0}".format(login_user) print test2('jhon', 'foobar') print test2('jhon', 'passwd') and the output should be: hello, jhon Check your password and username hello, jhon You are allowed to view this page you can see that on the first time, input the wrong password will give us the warning, but when we input the right info, it is showing us the success message.
Python - Selenium Locate elements by href Question: I am trying to find (and click) specific pages for my Python program using selenium. I have tried driver.findElement(By.cssSelector("a[href*='text']")).click(); And driver.findElement(By.partialLinkText("text")).click(); With `text` what I am searching for. These do not work with the error AttributeError: 'WebDriver' object has no attribute 'findElement' I can only assume that it can't do find element because that's for Java, not Python. The only distinguishing factor to the links on the website is the href attributes. All the other tags have repeats. There is no way I can 100% guess the right link, so I additionally need the locator to be by partial text. Is there anyway to start this? Could I use other programs? Has anybody successfully done this? I tried searching but nobody has even asked this. Answer: You can try: from selenium.webdriver.common.by import By ... driver.find_element(By.PARTIAL_LINK_TEXT, 'text').click() or from selenium import webdriver ... driver.find_element_by_partial_link_text("text").click() **EDIT:** For partial text search on the href itself try: from selenium import webdriver ... driver.find_element_by_xpath("//a[contains(@href,'text')]").click() Sources: <http://selenium-python.readthedocs.org/faq.html?highlight=click#how-to-auto- save-files-using-custom-firefox-profile> <http://selenium-python.readthedocs.org/locating-elements.html#locating- elements>
Python regular expressions and Excel Question: Im trying to perform regular match on data that came from excel to python array using openpyxl but the data came as unicode and "None" is allways given by python. The data in Hebrew and i whant to convert the strings from excel to strings that can be matched using regex.. what can be done? import re from openpyxl import load_workbook file_name = 'excel.xlsx' wb = load_workbook(file_name) ws = wb[u'beta'] li = [] li2 = [] #readin the cells from excel into an array for i in range(1,1500): li2.append(ws["A"+str(i)].value) for i in li2: if i != None: li.append(i) #deliting the unwanted list for making memory del li2 r = re.match("א",li[1]) r == None >>> True the wanted resault is r.string = "somthing..." and not r == None Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> >>> li[1] u"\u05d0\u05d1\u05d5 \u05d2'\u05d5\u05d5\u05d9\u05d9\u05e2\u05d3 (\u05e9\u05d1\u05d8)" >>> print li[1] אבו ג'ווייעד (שבט) >>> r = re.match(u'א',li[1]) >>> r ==None True >>> r = re.match(ur'א',li[1]) >>> r = re.match(u'',li[1]) >>> r.string u"\u05d0\u05d1\u05d5 \u05d2'\u05d5\u05d5\u05d9\u05d9\u05e2\u05d3 (\u05e9\u05d1\u05d8)" >>> unicode('א') Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> unicode('א') UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128) >>> u'א' u'\xe0' >>> u'א'.encode("utf8") '\xc3\xa0' >>> u"א" u'\xe0' >>> Answer: I put the Hebrew letter specified in your code into several cells, and then ran this code: # -*- coding: utf-8 -*- import re from openpyxl import load_workbook file_name = 'worksheet.xlsx' wb = load_workbook(file_name) ws = wb[u'beta'] li = [] li2 = [] #readin the cells from excel into an array for i in range(1,1500): li2.append(ws["A"+str(i)].value) for i in li2: if i != None: li.append(i) #deliting the unwonted list for clearing memory del li2 print "Non-empty cells: " print li r = re.search(u"א", li[1]) print "Match in: " print r.string.encode('utf-8') print "Position: " print r.span() Output: Non-empty cells: [u'Hebrew letter test 1 \u05d0', u'Hebrew letter test 2 \u05d0', u'Hebrew letter test 3 \u05d0', u'Hebrew letter test 4 \u05d0'] Match in: Hebrew letter test 2 ÎÉ Position: (21, 22) Please let me know if that's what you needed.
R summary() equivalent in numpy Question: Is there an equivalent of `R`'s `summary()` function in `numpy`? `numpy` has std, mean, average functions separately, but does it have a function that sums up everything, like `summary` does in `R`? If found [this](http://stackoverflow.com/questions/27637281/what-are-python- pandas-equivalents-for-r-functions-like-str-summary-and-he) question which relates to `pandas` and [this](http://mathesaurus.sourceforge.net/r-numpy.html) article with R-to- numpy equivalents, but it doesn't have what I seek for. Answer: **No**. You'll need to use `pandas`. R is for language for statistics, so many of the basic functionality you need, like `summary()` and `lm()`, are loaded when you boot it up. Python has many uses, so you need to install and import the appropriate statistical packages. `numpy` isn't a statistics package - it's for numerical computation more generally, so you need to use packages like `pandas`, `scipy` and `statsmodels` to allow Python to do what R can do out of the box.
Python:Understanding inheritance Question: Am new to Python and was exploring Classes and Object. I have created a class,defined few function in it. Then I have created another class and was trying to inherit from the first class but got some error. **Error:** class CTC(Salary): NameError: name 'Salary' is not defined **Base Class:** class Salary: monthly=0.00 name = "" def __init__(self,name,monthly): self.name = name self.monthly = monthly def display(self): print("name: ", self.name, "Monthly Salary: ", self.monthly) **Derived Class:** class CTC(Salary): tax=0.00 ctc=0.00 def __init__(self,name,monthly,tax): Salary.__init__(self,name,monthly) self.tax = tax def calculateCTC(self): yearly = monthly*12 totalTax= tax *12 ctc = yearly - totalTax print("Total CTC: ", self.ctc) obj = CTC("Rishi",28700.00,1295.00) obj.display(self) Can anyone explain me the root cause for the error? Answer: I put all code in one file (with minor modifiactions) and it works form me. class Salary: def __init__(self, name, monthly): self.name = name self.monthly = monthly def display(self): print("name: ", self.name, "Monthly Salary: ", self.monthly) class CTC(Salary): def __init__(self, name, monthly, tax): Salary.__init__(self, name, monthly) self.tax = tax self.ctc = 0.00 # create with default value def calculateCTC(self): yearly = self.monthly*12 # with `self` totalTax = self.tax*12 # with `self` self.ctc = yearly - totalTax # with `self` print("Total CTC: ", self.ctc) # without indentation obj = CTC("Rishi", 28700.00, 1295.00) obj.display() # without `self` if you need it in separated files salary.py class Salary: def __init__(self, name, monthly): self.name = name self.monthly = monthly def display(self): print("name: ", self.name, "Monthly Salary: ", self.monthly) main.py from salary import Salary class CTC(Salary): def __init__(self, name, monthly, tax): Salary.__init__(self, name, monthly) self.tax = tax self.ctc = 0.00 def calculateCTC(self): yearly = self.monthly*12 # with `self` totalTax = self.tax*12 # with `self` self.ctc = yearly - totalTax # with `self` print("Total CTC: ", self.ctc) # without indentation obj = CTC("Rishi", 28700.00, 1295.00) obj.display() # without `self`
How to replace the underscores with chosen letters in hangman Question: In my piece of code, I am having trouble replacing the underscores displayed by the length of the word with the correct letters. How do I solve this?. Below is a example of my code being run. print("Welcome to Python Hangman") print() import random # Needed to make a random choice from turtle import * #Needed to draw line WORDS= ("variable", "python", "turtle", "string", "loop") word= random.choice(WORDS)#chooses randomly from the choice of words print ("The word is", len(word), "letters long.")# used to show how many letters are in the random word space = len(word) underscore = ("_ " * space) print(underscore) for i in range(1, 9):#gives the amount of guesses allocated letter = input("Guess a letter ") if letter in word: print ("Correct", letter)#if guesses letter is correct print correct else: print ("Incorrect", " ",letter) #if its wrong print incorecct ​ Answer: Sadly, it's not possible to replace the underscores after you printed them to a console window. Your options are: 1. to implement a [GUI](https://en.wikipedia.org/wiki/Graphical_user_interface "Graphical User Interface \(Wikipedia\)"), which allows you to change the text after it is displayed 2. to print a lot of empty lines to make the old version of your output text disappear (which gives the impression that the output has changed) 3. to print an updated version each time your output text needs to be changed (which is what I would recommend). See my description of this option below. * * * For option 3 your output may look like this: Welcome to Python Hangman The word is 6 letters long. _ _ _ _ _ _ Guess a letter t Correct t t _ _ t _ _ Guess a letter u Correct u t u _ t _ _ Guess a letter e Correct e t u _ t _ e Guess a letter To achieve this, you should have a list like this: output = ['_'] * len(word) Now you can replace the spaces in this list each time a user finds a correct letter by doing: for i,x in enumerate(word): if x is letter: output[i] = letter and print the updated list using a function: def print_output(): print ''.join([str(x)+" " for x in output]) Which gives you the desired output. Complete solution: print "Welcome to Python Hangman" print import random # Needed to make a random choice WORDS = ("variable", "python", "turtle", "string", "loop") word = random.choice(WORDS)#chooses randomly from the choice of words print "The word is", len(word), "letters long." # used to show how many letters are in the random word output = ['_'] * len(word) # function to print the output list def print_output(): print print ''.join([x+" " for x in output]) for i in range(1, 9):#gives the amount of guesses allocated print_output() letter = raw_input("Guess a letter ") if letter in word: print "Correct", letter #if guesses letter is correct print correct # now replace the underscores in the output-list with the correctly # guessed letters - on the same position the letter is in the # secret word of course for i,x in enumerate(word): if x is letter: output[i] = letter else: print "Incorrect", " ", letter #if its wrong print incorecct
Correct way of "Absolute Import" in Python 2.7 Question: * Python 2.7.10 * In virtualenv * Enable `from __future__ import absolute_import` in each module The directory tree looks like: Project/ prjt/ __init__.py pkg1/ __init__.py module1.py tests/ __init__.py test_module1.py pkg2/ __init__.py module2.py tests/ __init__.py test_module2.py pkg3/ __init__.py module3.py tests/ __init__.py test_module3.py data/ log/ * * * I tried to use the function `compute()` of `pkg2/module2.py` in `pkg1/module1.py` by writing like: # In module1.py import sys sys.path.append('/path/to/Project/prjt') from prjt.pkg2.module2 import compute But when I ran `python module1.py`, the interpreter raised an ImportError that `No module named prjt.pkg2.module2`. 1. What is the correct way of "absolute import"? Do I have to add the path to `Project` to `sys.path`? 2. How could I run `test_module1.py` in the interactive interpreter? By `python prjt/pkg1/tests/test_module1.py` or `python -m prjt/pkg1/tests/test_module1.py`? Answer: ### How python find module _python will find module from`sys.path`, and the first entry `sys.path[0]` is '' means, python will find module from the current working directory_ import sys print sys.path and python find third-party module from `site-packages` so to absolute import, you can **append your package to the`sys.path`** import sys sys.path.append('the_folder_of_your_package') import module_you_created module_you_created.fun() **export PYTHONPATH** the PYTHONPATH will be imported into sys.path before execution export PYTHONPATH=the_folder_of_your_package import sys [p for p in sys.path if 'the_folder_of_your_package' in p] > How could I run test_module1.py in the interactive interpreter? By python > Project/pkg1/tests/test_module1.py or python -m > Project/pkg1/tests/test_module1.py? you can use `if __name__ == '__main__':` idiomatic way, and use `python Project/pkg1/tests/test_module1.py` if __name__ = '__main__': main()
Python: how can I ingest arguments from JSON file? Question: I have a block of python code that ingests command-line arguments, e.g.: import argparse if __name__ == "__main__": # myScript.py parser = argparse.ArgumentParser() parser.add_argument("-i", "--int", help="Int with default", type=int, default=20) parser.add_argument("-swd", "--strwdef", help="string with default", type=str, default="DEFAULTSTRING") parser.add_argument("-snd", "--strnodef", help="string without default", type=str) parser.add_argument("-f", "--flag", help="binary flag", action='store_true') args = parser.parse_args() i = args.i swd = args.swd snd = args.snd f = args.flag So this would work for a command like this: python myScript.py -swd SomeString --int 35 -f I want to read these arguments from a JSON file instead. Questions: 1. Are there built-in capabilities in `python 2.7` to set this up, instead of writing my own custom code of parsing results of `json.load()` to handle argument types, defaults etc? 2. If there is, what would be the proper format for a JSON file for the example above, and the way to populate the variables `i`, `swd`, etc? Thank you! Answer: `args` from the parser is an `argparse.Namespace` object, with is easily turned into a dictionary with vars(args) `-swd SomeString --int 35 -f` would then produce something like `namespace(swd='SomeString', int=35, f=True)`, and `{'swd':'SomeString', 'int':35, 'f':True}`. The equivalent JSON would decode to a similar dictionary. A dictionary can be turned (back) into a namespace with: In [2]: dd={'swd':'SomeString', 'int':35, 'f':True} In [3]: dd Out[3]: {'f': True, 'int': 35, 'swd': 'SomeString'} In [4]: argparse.Namespace(**dd) Out[4]: Namespace(f=True, int=35, swd='SomeString') As far as I know there isn't a package that would apply `argparse` like reasoning to a dictionary (which may have been created by `json.loads`). Someone else recently asked if there was a way of recreating the `sys.argv` string based on a `namespace`. You might look that up. I can recreate a `sys.argv` like list with this code In [22]: def foo(k,v): if len(k)==1: k = '-'+k else: k = '--'+k if isinstance(v,bool): return (k,) else: return k,str(v) ....: In [23]: argv=[] In [24]: for k,v in dd.items(): argv.extend(foo(k,v)) ....: In [25]: argv Out[25]: ['-f', '--int', '35', '--swd', 'SomeString'] This could then be passed to your parser with: args = parser.parse_args(argv) ======================== Another thing you could do is create a dictionary with the default values, and update it from the JSON dictionary: In [27]: defaultd=dict(int=20, strwdef='DEFAULTSTRING',snd=None,flag=False) In [28]: defaultd Out[28]: {'strwdef': 'DEFAULTSTRING', 'snd': None, 'int': 20, 'flag': False} In [29]: defaultd.update(dd) In [30]: defaultd Out[30]: {'strwdef': 'DEFAULTSTRING', 'f': True, 'flag': False, 'swd': 'SomeString', 'snd': None, 'int': 35} I just noticed a problem. For `defaultd` I used the long name 'flag' name, but in the JSON dict I used the short 'f' name. I could selectively copy from the JSON dict with something like: In [32]: for k in defaultd: ....: if k in dd: ....: defaultd[k]=dd[k] ....: In [33]: defaultd Out[33]: {'strwdef': 'DEFAULTSTRING', 'snd': None, 'int': 35, 'flag': False} Dealing with 'bad' values or aliases will be more complicated.
creating a new copy of a python class each time it's called Question: I need some guidance on how to set this up correctly for what I'm trying to do. I have a class called Attribute Block which I'll then use to create 3 or 4 Attribute block Objects. As seen below... class AttributeBlock(): def __init__(self, key, label, isClosed, isRequired, attributes): self.key = key self.label = label self.isClosed = isClosed self.isRequired = isRequired self.attributes = attributes if attributes is not None else {} 3 attributeBlock objects AttributeBlock( key="Sphere", isRequired=True, attributes=[ ''' Other class objects ''' BoolProperty("ishidden", False, "Hidden"), ] ) AttributeBlock( key="Box", isRequired=True, attributes=[ ''' Other class objects ''' BoolProperty("ishidden", True, "Hidden"), ] ) AttributeBlock( key="Circle", isRequired=False, attributes=[ ''' Other class objects ''' BoolProperty("ishidden", True, "Hidden"), ] ) What I then want to do is be able to add one of these AttributeBlocks to an Object, making sure when it's added, its a new instance of the AttributeBlock so its sub attribute objects are new instances. This is the object I will add my attribute blocks to. class ToyBox(): def __init__(self, name="", attributes=[]): self.name = name self.attributes = attributes[:] newToyBox = ToyBox() newToyBox.name = "Jimmy" **pseudo code** def add_attribute_block(toybox = None, key = "" ): if an AttributeBlock with the matching key exists: add it to toybox.attributes add_attribute_block( newToyBox, "Box" ) print newToyBox >> ToyBox name="Jimmy" attributes=[ AttributeBlock( key="Box", isRequired=True, attributes=[ BoolProperty("ishidden", True, "Hidden"), ] ), AttributeBlock( key="Sphere", isRequired=True, attributes=[ BoolProperty("ishidden", True, "Hidden"), ] ) ] Answer: If you want to make sure the Attribute instance added to your ToyBox is a copy, the easiest way is to use the [standard copy module](https://docs.python.org/2/library/copy.html) import copy ... class ToyBox(object): ... def add_attribute(self, attribute): self.attributes.append(copy.deepcopy(attribute))
Resizing matrix getting rid of 0 entries - Python Question: I have my matrix `E`, which I have been filling in some way (it is not important how, the important thing is that the entries are all different from 0). The dimension of the matrix is `n_x*n_y` X `n_x*n_y`, where n_x = 4 n_y = 8 Now I set some of the entries to 0: step = 4. for i in range(n_x): for j in range(n_y): if ((i or j)%step != 0): e[i][j] = 0. Then I want to get rid of the entries that are equal to 0., resizing my matrix. The way I do that is: filter(lambda a: a != 0., E) but what I get is filter(lambda a: a != 0., E) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Can someone explain me what is happening and how to solve it? EDIT: I realised I made a mistake in my code, in the part where I am setting to 0 certain entries of my matrix. I will correct this in the following: step = 4. for i in range(n_x): for j in range(n_y): if ((i%step != 0) or (j%step !=0)): e[i][j] = 0. Answer: I've adapted and completed your code a little bit, and it's working fine (see below). I believe the problem you're seeing is that you are iterating over lists (1 dimension), rather than iterating over the items in the list (2 dimensions / matrix). You need to `map` your `filter` over the lists that make up your matrix. n_x = 4 n_y = 8 step = 4. e = [['x' for _ in range(n_y)] for _ in range(n_x)] # e: # [['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'], # ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'], # ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'], # ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']] for i in range(n_x): for j in range(n_y): if ((i or j)%step != 0): e[i][j] = 0. # e: # [['x', 0.0, 0.0, 0.0, 'x', 0.0, 0.0, 0.0], # [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], # [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], # [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]] # map + filter no_zeroes = list(map(lambda x: list(filter(lambda a: a != 0., x)), e)) # no_zeroes: # [['x', 'x'], [], [], []] In case a list comprehension is clearer, this is equivalent: # list comprehensions (equivalent) no_zeroes_lc = [[col for col in row if col != 0.] for row in e] # no_zeroes_lc: # [['x', 'x'], [], [], []] no_zeroes == no_zeroes_lc # True
Changing title of image to display many images simultaneously using open cv and python Question: Hi I am using open cv 2 library with python ver 2.7.6 I have written the code which basically takes a image as input but the output shows only 1 window ... not n windows. Can any one please tell how i can display all the split images in multiple windows simultaneously. The code is as follows import numpy as np import cv2 def dr(img,direction,n): roi=[0] * 69 r,cv,c = img.shape print h,w,c return(roi) if __name__ == "__main__": img = cv2.imread('image.jpg') img_roi=dr(img,0,65) cv2.waitKey(025) cv2.destroyAllWindows() Answer: I needed to change the window name for each different window. So I replaced cv2.imshow('title',roi[i]) with cv2.imshow('image %d' % (i,), roi[i])
Using pysed in script Question: I can run successfully on command line but having problems in python script. It complains of the second double quote. pysed -r "192.168.33.10" "$NEW_IP" FILE --write ^ SyntaxError: invalid syntax How can I run this inside a script? Answer: It's true that the module has no documentation for using it as a library. But digging around the source, you can figure out how to use it. For example: import shlex from pysed import main as pysedmain pattern = '192.168.33.10' new_ip = '192.168.0.1' filename = '/path/to/my/file.txt' command_line_args = '-r "{pattern}" "{replacement}" {filename}'.format(pattern=pattern, replacement=new_ip, filename=filename) args = shlex.split(command_line_args) isWrite = True with open(filename, 'rU') as f: data = f.read() pysedmain.executeArguments(args, data, filename, isWrite)
Implementation of Dijkstra's algorithm with Networkx, reveicing a print error Question: I'm trying to read a file with source target weight values respectively to find the shortest path and print that path with the final weight. I'm using Networkx to use the Dijkstra function. However, when I execute, I receive this notice: `<function shortest_path at 0x7f9a13c39230> <function bidirectional_dijkstra at 0x7f9a13c48140>` I initially used just the `shortest_path` function thinking I somehow messed up using it, thus using the `bidirectional_dijkstra` function. The file in question has dummy data titled example.txt: ` D1 D5 7 D1 D2 6 D5 D4 7 D5 D3 7 D5 D3 3 D5 D2 4 D2 D2 1 D4 D3 1` My method in Python: #!/usr/bin/env python import os.path import networkx as nx from sys import argv #!script, filename = argv #assigns example to open the file example.txt example = open("example.txt", "r") print("\n This is what we have in our file:\n") #prints the open file print example.read() G =nx.Graph() for line in example: source, target, weight = line.split() nx.shortest_path(G,[source, target, weight]) print ( nx.shortest_path) print ( nx.bidirectional_dijkstra) #for some reason, this is printing: # #<function shortest_path at 0x7fe480d56230> #<function bidirectional_dijkstra at 0x7fe480d65140> Answer: So, I was receiving the message because I had not properly defined an edge. Here's the updated code: import os.path import networkx as nx from sys import argv #!script, filename = argv #assigns example to open the file example.txt example = open("/example.txt", "r") G =nx.Graph() for line in example: line = line.split() G.add_edge(line[0], line[1], weight=line[2]) #nx.shortest_path(G,[source, target, weight]) print nx.shortest_path(G) print nx.average_shortest_path_length(G)
Catch bash/git fatal in python Question: I would like to write a simple python script which will be able to clone a git repository into desired directory. I used try...except construction to be able to catch all exceptions however it looks like I am not able to handle 'fatal' properly. #!/usr/bin/env python import subprocess try: subprocess.check_call(['git', 'clone', 'git clone git@some_repo', '/tmp/some_directory']) except Exception: print "There was a problem during repository configuration" The output of the script above: > fatal: repository 'git clone git@some_repo' does not exist > > There was a problem during repository configuration To be more specific, I was rather expecting to get only the "There was a ..." message. Why do I get a 'fatal' message also? Answer: The message you are seeing is produced by the `git` command. If you want to prevent that message from appearing you should redirect either standard error or all output to `/dev/null` through a shell, like: subprocess.check_call(['git', 'clone', 'git clone git@some_repo', '/tmp/some_directory', '2&>/dev/null'], shell=True) However, I'd recommend against that practice since you lose information on the actual cause of error.
Python file keyword argument? Question: In command line I am able to pass arguments to a python file as: python script.py arg1 arg2 I can than retrieve `arg1` and `arg2` within `script.py` as: import sys arg1 = sys.argv[1] arg2 = sys.argv[2] However, I would like to send keyword arguments to a python script, and retrieve them as a dictionary: python script.py key1=value1 key2=value2 Then I would like to access the keyword arguments as a dictionary within python: {'key1' : 'value1', 'key2' : 'value2'} Is this possible? Answer: I think what you're looking for is the argparse module <https://docs.python.org/dev/library/argparse.html>. It will allows you to use command line option and argument parsing. e.g. Assume the following for script.py import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--arg1') parser.add_argument('--arg2') args = parser.parse_args() print args.arg1 print args.arg2 my_dict = {'arg1': args.arg1, 'arg2': args.arg2} print my_dict Now, if you try: $ python script.py --arg1 3 --arg2 4 you will see: 3 4 {'arg1': '3', 'arg2': '4'} as output. I think this is what you were after. But read the documentation, since this is a **_very_** watered down example of how to use argparse. For instance the '3' and '4' I passed in are viewed as str's not as integers
Cross-platform IDE for cross-platform high-level language with easy GUI creation (to replace VB .NET) Question: Suppose that you wish to show somebody who is not familiar with any programming language and he/she will (probably) not be involved in professional programming, some basics concepts: you would like to provide idea of loops, conditional statements and allow to create few simple programs with good-looking GUI. For that purpose, I found Visual Studio with Visual Basic (or C#) as a quite good solution. It allows to simply drag and drops some objects to form, easily set their preferences and with IntelliSense easily program events. However, I see some quite important drawbacks. First of all, it is only for Windows (okay, I know about Visual Studio Code, but it doesn't support easy GUI designing). I tested also that trying to open even very simple project in Monodevelop under Linux is not smooth process (VS adds some references not needed in Mono). Secondly, VS environment is extremely huge for somebody who is going to create simple window application. If this is possible, I would like to replace current IDE and redesign course. Personally I like Python, but any other high-level language is okay for me. I would like to avoid lower-level languages (for example C) since I wish to present everything as simple as possible (and correct me if I'm wrong, but creating GUI in ANSI C is always tricky). I am not aware of any cross-platform IDE which allows to do everything (GUI visual designing + coding + setting project properties) in one application like VS. For example, you design GUI in [Qt Designer](http://stackoverflow.com/questions/5313/cross-platform-language- agnostic-gui-markup-language), but write code in pyCharm, Eclipse (with Python plugin) or Geany. [Ninja IDE](http://www.ninja-ide.org/home/) looks very visually attractive. This might be my choice, but I don't see any GUI designer here. Could you tell me what are your thoughts about right tool, please? I am fully aware that by asking this question, I'm risking closing it and marking as 'opinion-based'. However...hope that it will be not. Answer: For cross-platform, you should have a look at Xojo (formerly CrossBasic, RealBasic, RealStudio...). It's free to play with, but you can't compile or deploy without a license. With a license, it allows compilation of Windows, OSX, iOS, and Linux binaries from a single source. I did use RealStudio 7 for a bit, it was alright really, no major complaints. Of course it will not be as complete a framework as .NET or mono is, but what was there was plenty for simple cross platform apps, certainly enough for beginners to chew on for a while, while learning object-oriented programming. Apart from the cross platform and size of VS though, Visual Studio is by far more complete and more standard.
How do I compare a response.data serialized object using Python / Django when unittesting? Question: This is my view: class ChatViewSet(viewsets.ModelViewSet): serializer_class = ChatSerializer def get_queryset(self): return Chat.objects.filter(users__in=[self.request.user]) This is my Serializer: class ChatSerializer(serializers.ModelSerializer): class Meta: model = Chat def validate_users(self, value): for user in value: if user in self.context['request'].user.userextended.follow.all() or user == self.context['request'].user: pass else: raise serializers.ValidationError('You cannot chat with a user you are not following.') if self.context['request'].user not in value: value.append(self.context['request'].user) return value This is my model: class Chat(models.Model): users = models.ManyToManyField(User) This is my unittest: from django.test import TestCase # Create your tests here. # Importing this from the DRF example of APIClient unittesting. from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase from django.contrib.auth.models import User from CMSApp.models import Chat from CMSApp.serializers import ChatSerializer class ChatTests(APITestCase): def setUp(self): User.objects.create_user(username='a', password='a', email='[email protected]') def test_get_chat_list(self): """ Ensure only authenticated users can get their own chat list. """ a = User.objects.get() url = reverse('chat-list') self.client.login(username='a', password='a') Chat.objects.create() Chat.objects.get().users.add(a) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) # Now, I want to either see if the id of resopnse.data is 1 # or somehow verify that the chat which was received / created # == the first chat created (chat who's pk / id is 1). How # Would I do this? I tried: self.assertEqual(response.data.id, 1) But got this error: AttributeError: 'ReturnList' object has no attribute 'id' When I do `print(response.data)` I get: [OrderedDict([('id', 1), ('users', [1])])] I also tried this: self.assertEqual(response.data, ChatSerializer(Chat.objects.get())) but got this error: self.assertEqual(response.data, ChatSerializer(Chat.objects.get())) AssertionError: [OrderedDict([('id', 1), ('users', [1])])] != ChatSerializer(<Chat: Chat object>): [134 chars]ll()) Any idea how I can accomplish what I want? Answer: As you noticed the returned datatype is list of Orderdict so to access the same you've to use index. :) response_data = simplejson.loads(response.content) expected_keys = set(['id', 'user']) # Here first we test if the keys are same in response # Notice we are checking the 0 index self.assertEqual(expected_keys, set(response_data[0].keys())) # To match the value self.assertEqual(response_data[0]['id'], 1)
Using turtle.onscreenclick to find coordinates of a mouse click Question: I simply want to use the turtle method onscreenclick to find the coordinates of a mouse click. Currently, I have a grid on which I am playing Othello. I already have the algorithm to convert the raw coordinates to specific grid coordinates that can be interpreted by the game. I cannot seem to get the onscreenclick method working. On the docs, it says to use a 'fun' function with two arguments. I believe I have this, but it is not working. I am a beginner with python and turtle so any help would be appreciated :) import turtle xclick = 0 yclick = 0 def getcoordinates(): turtle.onscreenclick(modifyglobalvariables()) def modifyglobalvariables(rawx,rawy): global xclick global yclick xclick = int(rawx//1) yclick = int(rawy//1) print(xclick) print(yclick) getcoordinates() Answer: You got so close! import turtle xclick = 0 yclick = 0 def getcoordinates(): turtle.onscreenclick(modifyglobalvariables) # Here's the change! def modifyglobalvariables(rawx,rawy): global xclick global yclick xclick = int(rawx//1) yclick = int(rawy//1) print(xclick) print(yclick) getcoordinates() Catch the change? Syntactically, remove the parentheses after modfiyglobalvariables. **What you want is to pass the function, what you are doing is passing the output of the function.** If you ran the code, you would get an exception (TypeError) saying you haven't passed the correct arguments; that's because it's trying to actually call modifyglobalvariables. Reduced, what you wanted was bind_to_mouseclick( my_function ) In which case, at each mouse click, `my_function` will be called. At that point, it may or may not have the correct arguments supplied. Instead you said bind_to_mouseclick( my_function() ) Python evaluates `my_function` and binds the _result of the call_ to the mouse click. If `my_function` happens to return a function, that's great (maybe what we intended). If it returns an integer or a string, no good. The key is the exception, as noted above; if the function had required no arguments, this may have been subtler to detect
ImportError by standalone executable created by Python's Freeze tool Question: I have installed python2.7.10 in Linux Ubuntu.(I use source tarball) ./configure make I want to get an executable binary file to use in a remote server that does not have Python installed. I used the command python freeze.py -o ./dist_time Test_time.py source code of 'Test_time.py': import datetime now = datetime.datetime.now() print print "Current date and time using str method of datetime object:" print str(now) print print "Current date and time using instance attributes:" print "Current year: %d" % now.year print "Current month: %d" % now.month print "Current day: %d" % now.day print "Current hour: %d" % now.hour print "Current minute: %d" % now.minute print "Current second: %d" % now.second print "Current microsecond: %d" % now.microsecond print print "Current date and time using strftime:" print now.strftime("%Y-%m-%d %H:%M") I receive 'Test_time' executable binary. I moved the binary file(Test_time) to the remote server (where Python is not installed). When I execute 'Test_time'binary file there, I get this error message: ./Test_time Traceback (most recent call last): File "Test_time.py", line 3, in <module> ImportError: No module named datetime Why is the datetime module not built into the executable? How do I include the module in the executable file? Answer: You can use `cx_freeze` to create an executable from your script, it will generate a directory containing an executable and its dependances. You need to create a `setup.py` in the same directory. import sys from cx_Freeze import setup, Executable base = None if sys.platform == "posix": base = "Linux" setup( name = "times", version = "0.1", description = "My demo application!", executables = [Executable("time.py", base=base)]) Then run it with this command `python setup.py build`.
python opencv import libraries error Question: I'm trying to run the facedetect.py sample code : [here ](https://github.com/Itseez/opencv/blob/master/samples/python2/facedetect.py) but I don't really understand what are these two line in the import section from video import create_capture from common import clock, draw_str this error is displayed : from video import create_capture ImportError: No module named video What are these libraries and how can I install them? Answer: i think you are using opencv samples..to run it you copy video.py and common.py files from the folder to C:\Python34\Lib\site-packages\ or you need to have these files in the same folder so that python can detect it is available. they have used functions from video module so you need to include them.
python flask normal function to decoration Question: I have this python `flask` code : @app.errorhandler(404) def not_found(e): logg = open("server_log_404.txt", 'a') logg.write("\r\n\r\n========================\n") logg.write("%s\n" % datetime.datetime.today().ctime()) logg.write("%s\n" % request.url ) logg.write("%s" % request.headers) logg.write("%s\n" % str(request.form)) logg.write("%s\n" % str(request.args)) logg.close() return render_template('404.html'), 404 I need change function `logg` in decoration for logging more pages. I need function like this : @app.errorhandler(404) @make_logg def not_found(e): return render_template('404.html'), 404 Is possible ? Answer: Just transform it into a decorator: from functools import wraps def make_logg(f): @wraps(f) def wrapper(*args, **kwargs): logg = open("server_log_404.txt", 'a') logg.write("\r\n\r\n========================\n") logg.write("%s\n" % datetime.datetime.today().ctime()) logg.write("%s\n" % request.url ) logg.write("%s" % request.headers) logg.write("%s\n" % str(request.form)) logg.write("%s\n" % str(request.args)) logg.close() return f(*args, **kwargs) return wrapper
How to get VNC security type from server with sockets on Python? Question: How to create a script for Python , which will be connect to specific ip with port , and print/return , which security type VNC connection have? import socket def check(ip,port): vnc = socket.socket(socket.AF_INET,socket.SOCK_STREAM) vnc.connect((ip,int(port))) vnc_ver = vnc.recv(12) print(vnc_ver) vnc.send(vnc_ver) print(vnc.recv(1024)) check("127.0.0.1","5900") I just get output:"RFB 003.008" Answer: IETF RFC 6143 (The Remote Framebuffer Protocol) defines that security handshake occurs after version handshake (see <https://tools.ietf.org/rfc/rfc6143.txt> paragraph 7.1.2). In the first phase of the security handshake, the VNC server is supposed to: * send 1 byte containing the number of supported security types * followed by the supported security types (each security type coded on one byte) So a Python script (similar to the one in your question) could display the supported security types that way: import socket def displaySecurityType(sec_type): switcher = { 0: "Invalid", 1: "NONE", 2: "VNC Authentication" } print(' security type: ' + str(sec_type) + ' (' + switcher.get(sec_type,"Not defined by IETF") +')' ) def check(ip,port): vnc = socket.socket(socket.AF_INET,socket.SOCK_STREAM) vnc.connect((ip,int(port))) vnc_ver = vnc.recv(12) print(vnc_ver) vnc.send(vnc_ver) nb_sec_types = ord(vnc.recv(1)) print("Nb security types: " + str(nb_sec_types)) for i in xrange(0,nb_sec_types): sec_type = ord(vnc.recv(1)) displaySecurityType(sec_type) check("127.0.0.1","5900")
Matplotlib Legends for barh Question: I am a beginner with python and matplotlib. I want to create a horizontal bar chart with a legend. My code: import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) clr = ('blue', 'forestgreen', 'gold', 'red', 'purple') h = plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4, label=people, color=clr) plt.yticks(y_pos, people) plt.xlabel('Performance') plt.title('How fast do you want to go today?') plt.legend(handles=[h]) plt.show() But in the legend I have only one element. But I want a legend with one element for each person with a rectangle in the rigth color. Thanks. Geosucher Answer: Pass the handles to your bars and the legend labels separately to `plt.legend`: plt.legend(h, people) [![enter image description here](http://i.stack.imgur.com/Ki9lZ.png)](http://i.stack.imgur.com/Ki9lZ.png)
How to extract timing info like HH:MM:SS from a given list using for loop in Python without importing any module Question: ['From', '[email protected]', 'Sat', 'Jan', '5', '09:14:16', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '18:10:48', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '16:10:39', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '15:46:24', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '15:03:18', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '14:50:18', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '11:37:30', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '11:35:08', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '11:12:37', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '11:11:52', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '11:11:03', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '11:10:22', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '10:38:42', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '10:17:43', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '10:04:14', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '09:05:31', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '07:02:32', '2008', 'From:', '[email protected]', 'From', '[email protected]', 'Fri', 'Jan', '4', '06:08:27', '2008', 'From:', '[email protected]', 'From', '[email protected]',] Is there any of extracting a string of specific type like hh:mm:ss from a list? I want to extract this information without importing any module. Answer: RegEx way: >>> [i for i in your_list if re.match('\d{2}:\d{2}:\d{2}', i)] ['09:14:16', '18:10:48', '16:10:39', '15:46:24', '15:03:18', '14:50:18', '11:37:30', '11:35:08', '11:12:37', '11:11:52', '11:11:03', '11:10:22', '10:38:42', '10:17:43', '10:04:14', '09:05:31', '07:02:32', '06:08:27', '04:49:08', '04:33:44', '04:07:34', '19:51:21', '17:18:23', '17:07:00', '16:34:40', '16:29:07', '16:23:48'] >>>
Using Python Exscript to connect to an AIX box Question: Here is the code that I am using. For some reasons it is not working, what am I missing? Not sure what else I can add to my post but the site is asking me to add more details account = Account(name= 'MiniMe', password = 'password') conn = SSH2() conn.debug=5 try: print "Attempting a connection to 1.1.1.1" conn.connect('1.1.1.1') print (conn.response) except: e = sys.exc_info()[0] print "Error connecting to host:", e conn="N/A" try: print "Authenticating to 1.1.1.1" conn.login(account) print (conn.response) except: e = sys.exc_info()[0] print e conn.execute('ls -la') print (conn.response) The output looks like this Attempting a connection to 1.1.1.1. generic: Rejecting ssh-rsa host key for 1.1.1.1: 3432432j4k32j4k32j42j34kj432 generic: Attempting to authenticate MiniMe generic: Authenticating with _paramiko_auth_password None Authenticating to 1.1.1.1 generic: Attempting to app-authenticate MiniMe. generic: waiting for: ['[\\r\\n][^\\r\\n]*(?:bad secrets|denied|invalid|too short|incorrect|connection timed out|failed|failure)', 'login as:', '(?:s\\/key|otp-md4) (\\d+) (\\S+)', 'password:? *$', '[\\r\\n](?:[^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\\ \\\t\\\n\\\r\\\x0b\\\x0c]*|[\\x1b\\x07\\x00]*)[\\[\\<]?\\w+(?:(?:(?:[\\w+\\-]+)\\@)?(?:[\\w+\\-\\.]+))?:?(?:(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)|~(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)?)?[: ]?(?:(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)|~(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)?)?(?:\\((?:[\\w\\+\\-\\._]+)\\))?[\\]\\-]?[#>%\\$\\]] ?[^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\\ \\\t\\\n\\\r\\\x0b\\\x0c]*\\Z'] generic: Expecting a prompt generic: Expected pattern: <generator object <genexpr> at 0x000000000349C990> aix: Protocol: driver replaced: generic -> aix aix: Protocol.app_authenticate(): driver replaced aix: waiting for: ['[\\r\\n][^\\r\\n]*(?:bad secrets|denied|invalid|too short|incorrect|connection timed out|failed|failure)', 'login as:', '(?:s\\/key|otp-md4) (\\d+) (\\S+)', "[\\r\\n]\\w+\\'s Password: $", '[\\r\\n](?:[^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\\ \\\t\\\n\\\r\\\x0b\\\x0c]*|[\\x1b\\x07\\x00]*)[\\[\\<]?\\w+(?:(?:(?:[\\w+\\-]+)\\@)?(?:[\\w+\\-\\.]+))?:?(?:(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)|~(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)?)?[: ]?(?:(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)|~(?:(?:(?:[\\w\\+\\-\\._]+))?(?:/(?:[\\w\\+\\-\\._]+))*/?)?)?(?:\\((?:[\\w\\+\\-\\._]+)\\))?[\\]\\-]?[#>%\\$\\]] ?[^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\\ \\\t\\\n\\\r\\\x0b\\\x0c]*\\Z'] aix: Expecting a prompt aix: Expected pattern: <generator object <genexpr> at 0x000000000349C9D8> aix: Sending 'ls -la\r' <class 'Exscript.protocols.Exception.TimeoutException'> aix: Expecting a prompt aix: Expected pattern: <generator object <genexpr> at 0x000000000349CAB0> Answer: Here are the key lines from the output: Attempting a connection to 1.1.1.1. # ... (messages from AIX) None # ... (messages from AIX) Authenticating to 1.1.1.1 # ... (messages from AIX) <class 'Exscript.protocols.Exception.TimeoutException'> # ... (messages from AIX) These are the printed messages from the two try/except statements. Here's the **most important line:** print (conn.response) #=> None ... happens after an attempted connection. The connection isn't working. The connection receives a blank response, i.e. `None`, and then it prints it out. That also explains the `TimeoutException` lower down. `Timeout` essentially means "I asked for Internet, and received silence." (The way this program is written, it will attempt to authenticate even when the initial connection fails. Don't worry, it's easily fixed.) Maybe the IP address is mistyped? Alternatively, try adding `http://` in front of the URL.
Find substrings in PyMongo Question: I wanted to find sub-strings within a field in MongoDB using PyMongo. The following query works fine and is what I require: db.collection.find({ "Animal": /cat|Dog/i}) However, if I try passing the value `/cat|Dog/i` as a string in Python, it doesn't work. Is there a way to replicate the query in **PyMongo**? Note: `/cat|Dog/i` is value of field from another collection. It is in the form 'cat Dog'. Basically, I want to match substrings in one field with substrings in another. Answer: You need to compile your regular expression pattern using [`re.compile()`](https://docs.python.org/3.5/library/re.html#re.compile) function into a regular expression object. import re pat = re.compile(r'cat|Dog', re.I) db.collection.find({ "Animal": {'$regex': pat}})
Paho Python Client with HiveMQ Question: i am developing a module in python that will allow me to connect my raspberry pi to a version of hivemq hosted on my pc. it connects normally but when i add hivemq's file auth plugin it doesnt seem to work im using the username_pw_set to set my username and password here is what my code currently looks like: import paho.mqtt.client as mqtt client = mqtt.Client() #The callback for when the client recieves a CONNACK response from the server def on_connect(client, userdata, flags, rc): print("connected with the result code "+str(rc)) #Define any topics you would like the pi to #automatically subscribe to here #The callback for when this client publishes to the server. def on_publish(client, userdata, mid): print("message published") #The callback for when a PUBLISH message is recieve from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) def on_log(client, userdata, level, buf): print(str(level)+" "+str(buf)) #set callbacks def setup(): client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish client.on_log = on_log #setup connection to broker def connect(username, password): client.username_pw_set(username, password) client.connect("10.19.109.152") def publish(topic, message): client.publish(topic, message) def loop(): client.loop() could it be something to do with the way the python client formats the connect request? Edit: Server gives me error message: 2015-11-26 09:50:53,723 ERROR - Could not get valid results from the webservice org.apache.http.NoHttpResponseException: The target server failed to respond at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(Default HttpResponseParser.java:143) and my client(on_connect function) outputs a connack message with code 5 which is for refused connection as its not authorised. Answer: The error from hivemq states that the http server you have pointed it at to do the authentication has not responded. You should check that those details are correct and that it responds as expected when you use something like curl to test it.
IOError: Errno 13 Permission denied for specific files Question: I'm running a flask API which can be used to upload jpg files. It's been working fine for about a year, but today, out of the blue, uploaded files are rejected for a specific user of the API. There's actually not any difference in the treatment of the request from one user to another, but the same file gets rejected for user A and accepted for user B, and user A never had this problem before. It's driving me crazy ! Here's the code in the flask API : from werkzeug.utils import secure_filename ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/uploadFile/', methods=['POST']) @auth.login_required def newImage(): if request.method == 'POST': if request.files: file = request.files['file'] if allowed_file(file.filename): ImageId = request.args.get('ImageId') newImage = DB_Image() newImage.ObjectId = ImageId filename = secure_filename(file.filename) pictureName, fileExtension = os.path.splitext(filename) fullFileNameToBeSaved = str(newImage.ObjectId) + fileExtension imagesPath = os.path.join(app.static_folder, 'images') file.save(os.path.join(imagesPath, fullFileNameToBeSaved)) (...) Everything works fine until the file.save, where I get the following error when user A tries to upload a file: mod_wsgi (pid=14170): Exception occurred processing WSGI script '/var/www/myApi/wsgi/myapivenv.wsgi'. Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/usr/local/lib/python2.7/dist-packages/flask_httpauth.py", line 61, in decorated return f(*args, **kwargs) File "/var/www/myApi/code/ImageUpload.py", line 227, in newImage file.save(os.path.join(imagesPath, fullFileNameToBeSaved)) File "/usr/local/lib/python2.7/dist-packages/werkzeug/datastructures.py", line 2576, in save dst = open(dst, 'wb') IOError: [Errno 13] Permission denied: '/var/www/path_to_upload_folder/files/images/2a6d85db-7ef0-40e3-8031-b7ed490bc512.jpg' The permissions were set when I installed the API, for the unix user created specifically to run the API : $ sudo usermod -a -G myApi $USER $ sudo chown -R $USER:myApi var/www/path_to_upload_folder/ path_to_upload_folder/files/images $ sudo chmod -R g+w var/www/path_to_upload_folder/ path_to_upload_folder/files/images But the users of the API are managed in a database, they have nothing to do with unix users, so I highly doubt the problem is from there. What could cause an error like this on some specific files sent by a specific user ? I'm using Werkzeug 0.9.4 and flask 0.10.1. Answer: I did some more digging, and it turns out I was trying to overwrite some files that were previously added by the root user (the myApi user didn't have overwrite permissions on them). Checking if the problematic files were already on the server was the first thing I did, but I did it by searching for the files with the Finder and Transmit (on Mac), which was apparently not as efficient as using the "ls" command, in a folder containing hundreds of files. Using "ls -l" I saw that the problematic files were owned by the root user, and not the myApi user (I actually had to move those files from one server to this one some time ago, which explains why the myApi user is not the owner). Now I'll try to find a UNIX command to change the permissions of every file added by the root user in that folder, or change the permissions of the myApi user so it can overwrite any file in that folder... Edit: I changed the permissions using $sudo chown -R myApi:myApi files/images
Is it a good idea to define my own random.randbool? Question: Python does not have a `random.randbool` function, although it has `randint`, `randrange` and `random`. If I wanted to use a `randbool` function, nothing stops me from using the following code: import random random.randbool = lambda: random.random() >= 0.5 Is it recommended to do this? Is it 'pythonic'? Is it much slower? This definitely allows for ease of understanding in later code, since instead inlining `random.random() >= 0.5` or `random.choice([False, True])` could be more confusing. The alternative is, of course, just using a regular function - def randbool(): return random.random() >= 0.5 Which is better? Edit: Some `timeit` benchmarks: > python -m timeit -s "import random" -s "def randbool():" -s " return random.random() >= 0.5" "randbool() 1000000 loops, best of 3: 0.275 usec per loop > python -m timeit -s "import random" "random.random() >= 0.5" 10000000 loops, best of 3: 0.152 usec per loop > python -m timeit -s "import random" -s "random.randbool = lambda: random.random() >= 0.5" "random.randbool()" 1000000 loops, best of 3: 0.322 usec per loop > python -m timeit -s "import random" "random.choice([False, True])" 100000 loops, best of 3: 2.03 usec per loop > python -m timeit -s "import random" "random.randint(0, 1)" 100000 loops, best of 3: 2.9 usec per loop So, the fastest is inlining, followed by a regular function, then defining `random.randbool`. `choice` and `randint` are far slower. Answer: In **Ruby** quite common is to implement mixins, that enhance methods available for classes from _standard library_. Lot of Rails stuff is built that way. But I didn't see any indications that would show that this is good practice in Python. If standard modules lack some feature, it's quite common to create your own module. The advantage of that is you do not to create impression that some function/method comes from standard set for anyone else who may look into your code. I think most _Pythonistas_ trust imports they see at the beginning of the module. I can't answer if your approach is slower. I had to '_patch_ ' original Python libraries in the past by using meta-programming, but that was done to make sure we have consistent interface for test methods.
How do I run both these turtle scripts one after another Question: import random import turtle spiral = turtle.Turtle() turtle.bgcolor("black") spiral.color("cadet blue") randomfive = random.randint(5,15) spiral.pensize(randomfive) randomfour = random.randint(20,75) spiral.speed (randomfour) randomthree = random.randint(200,500) randomtwo = random.randint(5,20) random = random.randint(10,360) spiral.pendown() for i in range(randomthree): spiral.forward(i * randomtwo) spiral.right(random) def christmas (): turtle.bgcolor("black") for i in range(2): turtle.speed (9999999) coordone = random.randint (-300,300) coordtwo = random.randint (-300,300) right = random.randint (1,360) turtle.penup() turtle.goto (coordone,coordtwo) turtle.pendown() turtle.right(right) for y in range (10): turtle.speed(9999) turtle.right(36) for x in range (50): turtle.color("red") turtle.speed(99999) turtle.pensize(x/5) turtle.forward (x-(x-1)) turtle.penup() turtle.goto (coordone,coordtwo) turtle.pendown() turtle.right(18) for z in range (10): turtle.speed(9999) turtle.right(36) for w in range (50): turtle.color("green") turtle.speed(99999) turtle.pensize(w/3) turtle.forward (w-(w-1)) turtle.penup() turtle.goto (coordone,coordtwo) turtle.pendown() christmas() When I try this python says "AttributeError: 'int' object has no attribute 'randint'" (By the way, this is the whole code). Please help with this issue. The name of this is droplets.py so that wouldn't be the issue. Answer: import turtle import random def spiral(): turtle.bgcolor("black") spiral = turtle.Turtle() spiral.color("cadet blue") randomfive = random.randint(5, 15) spiral.pensize(randomfive) randomfour = random.randint(0, 11) spiral.speed(randomfour) randomthree = random.randint(200, 500) randomtwo = random.randint(5, 20) randomone = random.randint(10, 360) spiral.pendown() for i in range(randomthree): spiral.forward(i * randomtwo) spiral.right(randomone) spiral.penup() def christmas(): turtle.bgcolor("black") turtle.speed("fastest") for i in range(2): coordinate = random.randint(-300, 300), random.randint(-300, 300) right = random.randint(1, 360) turtle.penup() turtle.goto(coordinate) turtle.pendown() turtle.right(right) for y in range(10): turtle.right(36) for x in range(50): turtle.color("red") turtle.pensize(x / 5) turtle.forward(1) turtle.penup() turtle.goto(coordinate) turtle.pendown() turtle.right(18) for z in range(10): turtle.right(36) for w in range(50): turtle.color("green") turtle.pensize(w / 3) turtle.forward(1) turtle.penup() turtle.goto(coordinate) turtle.pendown() spiral() christmas() turtle.done()
Creating an Azure Web App with Postgresql database (is that possible?) Question: I use Heroku to host a Django web app with a postgres back-end. I'm now looking to migrate this web app to Azure, taking advantage of a great deal Azure recently offered me. But I'm confused about one thing: how can I create a Django website on Azure with **postgresql as the database**? I successfully created a Django website, connected it to git, but I can't seem to change it's DB to postgresql. Hence, when I do `git push azure master`, I get the error: **Command python setup.py egg_info failed with error code 1 in D:\home\site\wwwroot\env\build\psycopg2** It fails on psycopg2 (postgresql). Secondly, once I do successfully install postgresql on an Azure Web App, I'd need to tweak its postgresql.conf file to tune the settings (defaults are too low). How would I do that? * * * The documentation only talks about how to install PG for an Azure VM with Linux, not an Azure Web App: <https://azure.microsoft.com/en- us/documentation/articles/virtual-machines-linux-postgresql/> Answer: Azure Web Apps Service is a PaaS which provides several services to host your web site apps. And we have limit permission to install PostgreSQL on it. Currently, to host PostgreSQL on Azure, you can leverage virtual machines with linux as @theadriangreen mentioned. And you can use SSH command `ssh user@VMhost` to remote on your linux VM and set your PG configurations. You may refer to [YoLinux Tutorial: The PostgreSQL Database and Linux](http://www.yolinux.com/TUTORIALS/LinuxTutorialPostgreSQL.html) for more about PG on Linux. And additionally, you can create a docker contain with PostgreSQL image in Azure add-on market. Login preview manage portal, click new=>search “postgres” in search bar, you can find the postgres service provided by docker. [![enter image description here](http://i.stack.imgur.com/4CP5k.png)](http://i.stack.imgur.com/4CP5k.png) You also can remote to this VM via SSH to set your PG configurations. If you want a direct tcp connection to the PG server, you need to add 5432 port in the Inbound security rules. In “All settings” of the VM server you created above, click “Network interfaces”=>click the interface in use=>click the network security group name in use, you can find the Inbound security rules in the settings page. [![enter image description here](http://i.stack.imgur.com/YDtNM.png)](http://i.stack.imgur.com/YDtNM.png) Then you can test the connection of your PG service: import psycopg2 try: conn = psycopg2.connect(database="postgres", user="postgres", password="{password}", host="{host_ip}", port="5432") print "Opened database successfully" cur = conn.cursor() cur.execute("SELECT ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]"); rows = cur.fetchall() print(rows) conn.commit() print "Records created successfully"; conn.close() except Exception, e: print "I am unable to connect to the database"
Are classobjects singleton in python? Question: If we have `x = type(a)` and `x == y`, does it necessarily imply that `x is y`? Here is a counter-example, but it's a cheat: >>> class BrokenEq(type): ... def __eq__(cls, other): ... return True ... >>> class A(metaclass=BrokenEq): ... pass ... >>> a = A() >>> x = type(a) >>> x == A, x is A (True, True) >>> x == BrokenEq, x is BrokenEq (True, False) And I could not create a counterexample like this: >>> A1 = type('A', (), {}) >>> A2 = type('A', (), {}) >>> a = A1() >>> x = type(a) >>> x == A1, x is A1 (True, True) >>> x == A2, x is A2 (False, False) To clarify my question - _without overriding equality_ operators to do something insane, is it possible for a class to exist at two different memory locations or does the import system somehow prevent this? If so, how can we demonstrate this behavior - for example, doing weird things with [reload](https://docs.python.org/2/library/functions.html#reload) or `__import__`? If not, is that guaranteed by the language or documented anywhere? * * * **Epilogue** : # thing.py class A: pass Finally, this is what clarified the real behaviour for me (and it's supporting the claims in Blckknght answer) >>> import sys >>> from thing import A >>> a = A() >>> isinstance(a, A), type(a) == A, type(a) is A (True, True, True) >>> del sys.modules['thing'] >>> from thing import A >>> isinstance(a, A), type(a) == A, type(a) is A (False, False, False) So, although code that uses [`importlib.reload`](https://docs.python.org/3/library/importlib.html?highlight=reload#importlib.reload) could break type checking by class identity, it will also break `isinstance` anyway. Answer: No, there's no way to create two class objects that compare equal without being identical, except by messing around with metaclass `__eq__` methods. This behavior though is not something unique to classes. It's the default behavior for any object without an `__eq__` method defined in its class. The behavior is inherited from `object`, which is the base class for all other (new-style) classes. It's only overridden for builtin types that have some other semantic for equality (e.g. container types which compare their contents) and for custom classes that define an `__eq__` operator of their own. As for getting two different refernces to the same class at different memory locations, that's not really possible due to Python's object semantics. The memory location of the object _is_ its identity (in cpython at least). Another class with identical contents can exist somewhere else, but like in your `A1` and `A2` example, it's going to be seen as a different object by all Python logic.
Django reporting 404 error on simple view? Question: I'm just barely getting started with Python and Django. I've created my modules, migrated, added my modules to the admin section, etc. Now, I need to create my first view. I've been following [this guide](https://docs.djangoproject.com/en/1.6/intro/tutorial03/) (Yes the machine I'm on is running 1.6) My views.py file in the app (setup) looks like this... from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Setup Index") My app'a urls.py looks like this... from django.conf.urls import patterns, url from setup import views urlpatterns = patterns('', url(r'^$', views.index, name='index') ) And my root urls.py looks like this... from django.views.generic import TemplateView from django.views.generic.base import RedirectView from django.conf.urls import include, patterns, url from django.contrib import admin as djangoAdmin from admin.controller import ReportWizard from admin.forms import reportDetailsForm, reportDataViewsForm from setup import views djangoAdmin.autodiscover() urlpatterns = patterns('', url(r'^django-admin/', include(djangoAdmin.site.urls)), #New User Wizard URL url(r'^setup/', include('setup.urls')), ) As far as I can tell I have followed the guide to the letter, but I am recieving a 404 error when navigating to myIP/setup. There are no error messages on the 404 page. What is the issue? [![enter image description here](http://i.stack.imgur.com/XclnI.png)](http://i.stack.imgur.com/XclnI.png) Answer: For some reason your settings seem to override the default for either [`APPEND_SLASH`](https://docs.djangoproject.com/en/1.8/ref/settings/#append- slash) or [`MIDDLEWARE_CLASSES`](https://docs.djangoproject.com/en/1.8/ref/settings/#middleware- classes). Opening `http://example.com/setup` should cause a redirect to `http://example.com/setup/`, but somehow it doesn't for you. Note that the latter URL is matched by your `urls.py` while the former is not (as should be the case). The above should work if 'CommonMiddleWare`is enabled and`APPEND_SLASH`is set to`True`.
frame difference using python Question: I'm trying to do frame difference this is my code below import numpy as np import cv2 current_frame =cv2.VideoCapture(0) previous_frame=current_frame while(current_frame.isOpened()): current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY) previous_frame_gray= cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY) frame_diff=cv2.absdiff(current_frame_gray,previous_frame_gray) cv2.imshow('frame diff ',frame_diff) cv2.waitKey(1) current_frame.copyto(previous_frame) ret, current_frame = current_frame.read() current_frame.release() cv2.destroyAllWindows() my problem is that I tried to create empty frame to save the first frame from current_frame previous_frame=np.zeros(current_frame.shape,dtype=current_frame.dtype) But I think it is not correct , then I tried to pass current_frame like this: previous_frame=current_frame Now I'm getting this error : > current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY) > TypeError: src is not a numpy array, neither a scalar so what should I do for this ? Thanks for help Answer: You have mixed the VideoCapture object and the frame. I've also made small changes in the frame copy and waitkey. import cv2 cap = cv2.VideoCapture(0) ret, current_frame = cap.read() previous_frame = current_frame while(cap.isOpened()): current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY) previous_frame_gray = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY) frame_diff = cv2.absdiff(current_frame_gray,previous_frame_gray) cv2.imshow('frame diff ',frame_diff) if cv2.waitKey(1) & 0xFF == ord('q'): break previous_frame = current_frame.copy() ret, current_frame = cap.read() cap.release() cv2.destroyAllWindows()
Flask __init__.py import error Question: I can not import functions from other files to `__init__.py` in a flask. Importing something from a file gets an error 500. **__init__.py** from flask import Flask from fel import fel app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': app.run(debug=True) **fel.py** def fel(a,b): c = a+b return (c) If I delete the following line in the `__init__.py` file from fel import fel Everything is OK. `__init__.py` and `fel.py` are in the same directory I am working in Python 3.4 Where is the mistake? edit: structures FlaskApp\ __init__.py fel.py Answer: use relative import from .fel import fel fel(something) Explanation: > The problem of import fel is that you don't know whether its an absolute > import or a relative import. fel could a module in python's path, or a > package in the current module. Source <http://programmers.stackexchange.com/questions/159503/whats-wrong- with-relative-imports-in-python>
Python crawler which than sends out results via email Question: thanks for helping. So I tried to make a little crawler which checks out the gif page of reddit, than writes down all the gifs + titles, puts them in a list and than sends this list via email _(to my work colleagues)_. So far so good, works perfectly, BUT the list it send looks like this e.g: > '1. Old man dancing at electronic music festival: > <http://i.imgur.com/2EtphXY.gifv>', '2. Generation text..: > <http://i.imgur.com/fH6eV2B.gifv>', '3. Porcupine climbs up for warmth: etc... **What do I want?** I want that the titles + links are printed by single row in the email + i wanne add a text to it. like this > Hello friends welcome to daily gifs > > 1. title1: link1 > 2. title2: link2 > 3. title3: link3 > This is my code so far: import requests from bs4 import BeautifulSoup import urllib2 import smtplib import time import random import datetime opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] url = 'https://www.reddit.com/r/gifs/?count=26&before=t3_3u4mnz' response = opener.open(url) page = response.read() soup = BeautifulSoup(page, "lxml") list = [] variable = 1 for link in soup.findAll('a', {'class': 'title may-blank '}): href = link.get('href') name = link.string #print str(variable) + ". " + name + " : " + href list.append(str(str(variable) + ". " + name + ": " + href)) variable += 1 GMAIL_USERNAME = "[email protected]" GMAIL_PASSWORD = "xxxxxxxx" email_subject = "Lunchtime gifs of the day: " + str(time.strftime("%d/%m/%Y")) recipient = "[email protected]" body_of_email = str(list)[1:-1] session = smtplib.SMTP('smtp.gmail.com', 587) session.ehlo() session.starttls() session.login(GMAIL_USERNAME, GMAIL_PASSWORD) headers = "\r\n".join(["from: " + GMAIL_USERNAME, "subject: " + email_subject, "to: " + recipient, "mime-version: 1.0", "content-type: text/html"]) content = headers + "\r\n\r\n" + body_of_email session.sendmail(GMAIL_USERNAME, recipient, content) print "Email send!" Answer: An email's content type is determined using the `Content-Type` header. You've specified that that content type for your email is `text/html` and clients that read this email will interpret the bits as HTML. So, make the bits that you're sending look like HTML. I would use `<br />` or `<ol />` `<li />` tags. Alternatively, send the email as `text/plain` and your `\n` characters will be interpreted as you would expect. Personally, for emails like this, I prefer for them to be in `text/plain` format.
Pythonic way to use context manager conditionally Question: This is something I think must come up quite often but I haven't been able to find a good solution for it. Say I have a function which may be passed an open resource as an argument (like a file or database connection object) or needs to create one itself. If the function needs to open a file on its own, best practice is usually considered something like: with open(myfile) as fh: # do stuff with open file handle... to ensure the file is always closed when the `with` block is exited. However if an existing file handle is passed in the function should probably not close it itself. Consider the following function which takes either an open file object _or_ a string giving a path to the file as its argument. If it is passed a file path it should probably be written as above. Otherwise the `with` statement should be omitted. This results in duplicate code: def foo(f): if isinstance(f, basestring): # Path to file, need to open with open(f) as fh: # do stuff with fh... else: # Assume open file fh = f # do the same stuff... This could of course be avoided by defining a helper function and calling it in both places, but this seems inelegant. A better way I thought of was to define a context manager class that wraps an object like so: class ContextWrapper(object): def __init__(self, wrapped): self.wrapped = wrapped def __enter__(self): return self.wrapped def __exit__(self, *args): pass def foo(f): if isinstance(f, basestring): cm = open(f) else: cm = ContextWrapper(f) with cm as fh: # do stuff with fh... This works but unless there's a built-in object that does this (I don't think there is) I either have to copy-paste that object everywhere or always have to import my custom utilities module. I'm feeling like there's a simpler way to do this that I've missed. Answer: However, I prefer, I don't know how pythonic it is, but it's straightforward def foo(f): if isinstance(f, basestring): f = open(f) try: # do the stuff finally: f.close() the problem could be solved nicer with [singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch) from python 3.4 from functools import singledispatch @singledispatch def foo(fd): with fd as f: # do stuff print('file') @foo.register(str) def _(arg): print('string') f = open(arg) foo(f) foo('/tmp/file1') # at first calls registered func and then foo foo(open('/tmp/file2', 'r')) # calls foo
Remove duplicates from nested list using list as keys Question: I use to have two lists, `files` and `g_list` which were both regular lists. I wanted to remove the duplicates from `files` and have `g_list` match. I found this solution; from collections import OrderedDict as odict od = odict.fromkeys(zip(files, g_list)) files, g_list = zip(*od) I have since modified `g_list` to be a nested list, but now when I run the above code I get this `TypeError`: File "/usr/lib/python2.7/collections.py", line 199, in fromkeys self[key] = value File "/usr/lib/python2.7/collections.py", line 58, in __setitem__ if key not in self: TypeError: unhashable type: 'list' How do I remedy this? Or is there another way to do what I desire? **Edit:** Input: files = ['red', 'green', 'blue', 'green', 'yellow'] g_list = [['x','y'], ['z'], ['q','r','x'], ['z'], ['x', 'r']] Desired Output: files = ['red', 'green', 'blue', 'yellow'] g_list = [['x','y'], ['z'], ['q','r','x'], ['x', 'r']] Answer: Lists cannot be used as keys in dictionaries as they are _mutable_ , they can be changed, so they can't be hashed. Well, they _could_ be hashed, but _that hash might change_. As a dictionary relies on hashing its keys to be efficient, hashes must stay constant. The solution, then, is to use a **tuple** , which is exactly like a list except that it's immutable. To convert a list `L` to a tuple, simply do `tuple(L)`.
Shedskin can't locate module numpy Question: I'm using shedksin to convert a python file (that is dependent on numpy) to a C++ file. When executing through command prompt I get the error. Any ideas on what might be the problem ? Answer: I have found an answer. From Shedskin implementation: # Library Limitations Programs to be compiled with **Shed Skin** cannot freely use the Python standard library. Only about 17 common modules are currently supported. Note that **Shed Skin** can be used to build an extension module, so the main program can use arbitrary modules (and of course all Python features!). See Compiling an Extension Module. In general, programs can only import functionality that is defined in the **Shed Skin** lib/ directory. The following modules are largely supported at the moment: * bisect * collections * ConfigParser * copy * datetime * fnmatch * getopt * glob * math * os (some functionality missing under Windows) * os.path * random * re * socket * string * sys * time
How to solve no such table: user in Heroku application? Question: I have deploy the application but its showing me an internal server error . the same application I have run on localhost but now I am trying to run through heroku but its not giving me an output. the application is there on the link given below <http://flask.pocoo.org/> File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:31:28.153486+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:31:28.153487+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 2015-11-26T06:31:28.153488+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 2015-11-26T06:31:28.153489+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args) 2015-11-26T06:31:28.153491+00:00 app[web.1]: [username], one=True) 2015-11-26T06:31:28.153491+00:00 app[web.1]: File "/app/minitwit.py", line 63, in query_db 2015-11-26T06:31:28.153493+00:00 app[web.1]: OperationalError: no such table: user 2015-11-26T06:31:28.153486+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:31:28.153486+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:31:28.153487+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 2015-11-26T06:31:28.153488+00:00 app[web.1]: rv = self.dispatch_request() 2015-11-26T06:31:28.153490+00:00 app[web.1]: File "/app/minitwit.py", line 125, in user_timeline 2015-11-26T06:31:28.153489+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args) 2015-11-26T06:31:28.153491+00:00 app[web.1]: [username], one=True) 2015-11-26T06:31:28.153491+00:00 app[web.1]: File "/app/minitwit.py", line 63, in query_db 2015-11-26T06:31:28.153492+00:00 app[web.1]: cur = get_db().execute(query, args) 2015-11-26T06:31:28.153493+00:00 app[web.1]: OperationalError: no such table: user 2015-11-26T06:31:28.153486+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:31:28.153486+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:31:28.153487+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 2015-11-26T06:31:28.153490+00:00 app[web.1]: File "/app/minitwit.py", line 125, in user_timeline 2015-11-26T06:31:28.153491+00:00 app[web.1]: [username], one=True) 2015-11-26T06:31:28.153491+00:00 app[web.1]: File "/app/minitwit.py", line 63, in query_db 2015-11-26T06:31:28.153486+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:31:28.153488+00:00 app[web.1]: rv = self.dispatch_request() 2015-11-26T06:31:28.153488+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 2015-11-26T06:31:28.153486+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:31:28.153486+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:31:28.153487+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 2015-11-26T06:31:28.153488+00:00 app[web.1]: rv = self.dispatch_request() 2015-11-26T06:31:28.153490+00:00 app[web.1]: File "/app/minitwit.py", line 125, in user_timeline 2015-11-26T06:31:28.153491+00:00 app[web.1]: File "/app/minitwit.py", line 63, in query_db 2015-11-26T06:31:28.153492+00:00 app[web.1]: cur = get_db().execute(query, args) 2015-11-26T06:41:02.282478+00:00 heroku[router]: at=info method=GET path="/public" host=minitwittest.herokuapp.com request_id=a93d6057-f7de-4a9b-876c-a13372c31cbc fwd="103.5.187.166" dyno=web.1 connect=1ms service=8ms status=500 bytes=244 2015-11-26T06:41:02.272442+00:00 app[web.1]: [2015-11-26 06:41:02 +0000] [9] [ERROR] Error handling request /public 2015-11-26T06:41:02.272445+00:00 app[web.1]: Traceback (most recent call last): 2015-11-26T06:41:02.272447+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 130, in handle 2015-11-26T06:41:02.272448+00:00 app[web.1]: self.handle_request(listener, req, client, addr) 2015-11-26T06:41:02.272448+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 171, in handle_request 2015-11-26T06:41:02.272452+00:00 app[web.1]: return self.wsgi_app(environ, start_response) 2015-11-26T06:41:02.272454+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception 2015-11-26T06:41:02.272456+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app 2015-11-26T06:41:02.272457+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request 2015-11-26T06:41:02.272458+00:00 app[web.1]: rv = self.handle_user_exception(e) 2015-11-26T06:41:02.272459+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:41:02.272460+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:41:02.272461+00:00 app[web.1]: rv = self.dispatch_request() 2015-11-26T06:41:02.272462+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 2015-11-26T06:41:02.272469+00:00 app[web.1]: order by message.pub_date desc limit ?''', [PER_PAGE])) 2015-11-26T06:41:02.272470+00:00 app[web.1]: cur = get_db().execute(query, args) 2015-11-26T06:41:02.811154+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=minitwittest.herokuapp.com request_id=3b9d3742-4940-493a-ba29-579865ca6b40 fwd="103.5.187.166" dyno=web.1 connect=2ms service=5ms status=500 bytes=244 2015-11-26T06:41:02.801367+00:00 app[web.1]: [2015-11-26 06:41:02 +0000] [10] [ERROR] Error handling request /favicon.ico 2015-11-26T06:41:02.801371+00:00 app[web.1]: Traceback (most recent call last): 2015-11-26T06:41:02.801372+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 130, in handle 2015-11-26T06:41:02.801373+00:00 app[web.1]: self.handle_request(listener, req, client, addr) 2015-11-26T06:41:02.801374+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 171, in handle_request 2015-11-26T06:41:02.801375+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response) 2015-11-26T06:41:02.801376+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ 2015-11-26T06:41:02.801377+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app 2015-11-26T06:41:02.801378+00:00 app[web.1]: response = self.make_response(self.handle_exception(e)) 2015-11-26T06:41:02.801379+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception 2015-11-26T06:41:02.801380+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app 2015-11-26T06:41:02.801382+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request 2015-11-26T06:41:02.801384+00:00 app[web.1]: rv = self.handle_user_exception(e) 2015-11-26T06:41:02.801384+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:41:02.801385+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:41:02.801386+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 2015-11-26T06:41:02.801386+00:00 app[web.1]: rv = self.dispatch_request() 2015-11-26T06:41:02.801387+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args) 2015-11-26T06:41:02.801388+00:00 app[web.1]: File "/app/minitwit.py", line 125, in user_timeline 2015-11-26T06:41:02.801389+00:00 app[web.1]: [username], one=True) 2015-11-26T06:41:02.801389+00:00 app[web.1]: File "/app/minitwit.py", line 63, in query_db 2015-11-26T06:41:02.801390+00:00 app[web.1]: cur = get_db().execute(query, args) 2015-11-26T06:41:02.801391+00:00 app[web.1]: OperationalError: no such table: user 2015-11-26T06:41:02.801384+00:00 app[web.1]: rv = self.handle_user_exception(e) 2015-11-26T06:41:02.801385+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:41:02.801387+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 2015-11-26T06:41:02.801388+00:00 app[web.1]: File "/app/minitwit.py", line 125, in user_timeline 2015-11-26T06:41:02.801387+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args) 2015-11-26T06:41:02.801389+00:00 app[web.1]: [username], one=True) 2015-11-26T06:41:02.801391+00:00 app[web.1]: OperationalError: no such table: user 2015-11-26T06:41:02.801384+00:00 app[web.1]: rv = self.handle_user_exception(e) 2015-11-26T06:41:02.801384+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 2015-11-26T06:41:02.801385+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2015-11-26T06:41:02.801387+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 2015-11-26T06:41:02.801386+00:00 app[web.1]: rv = self.dispatch_request() 2015-11-26T06:41:02.801387+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args) 2015-11-26T06:41:02.801389+00:00 app[web.1]: File "/app/minitwit.py", line 63, in query_db 2015-11-26T06:41:02.801390+00:00 app[web.1]: cur = get_db().execute(query, args) 2015-11-26T06:41:02.801391+00:00 app[web.1]: OperationalError: no such table: user Answer: I assume you are using `Flask-SQLAlchemy` In that case you have to create database table first. To do that you have to enter into `heroku run python` and `from app import db` and `db.create_all()`.
Python cassandra-driver: The C extension needed to use libev was not found Question: I have Cassandra python driver version 2.5.1 installed with all required dependencies that is libev4, libev-dev, gcc, python-dev. However I am getting following error while importing `LibevConnection` > "The C extension needed to use libev was not found. This probably means that > you didn't have the required build dependencies when installing the driver" I tried reinstalling and even installed latest version of the driver with no success. I am using Ubuntu 12.04. Answer: When I checked I had all the dependencies installed but probably not when I installed the driver. Before I tried reinstalling I tried installing newest version which made conflict with existing installation. **So the problem was:** Not having dependency installed before installing python driver and then multiple installation of the driver. **Solution** Remove all the version of Cassandra python driver completely from the system (Delete the relevant eggs). Make sure you have all the [dependencies installed](http://datastax.github.io/python- driver/installation.html#c-extensions). After that simply install the required version.
kill process and its sub/co-processes by getting their parent pid by python script Question: i am using MULTIPROCESSING to find my requirement. And when that runs i am getting a pid(may be parent! i don't know what to call that) then co processes with their own pid and reference id of first process. Now i need to kill all those processes BY ONLY KILLING THE FIRST PROCESS then which will be the best way to do that. THAT ALSO IN PYTHONIC WAY. Scenario is like ps -ef |grep py i am getting 2222 0001 first.py #0001 is os process 4323 2222 second.py 4324 2222 third.cgi 4324 2222 fourth.py 4325 2222 fifth.cgi 4326 2222 sixth.py 2223 0001 newfirst.py ############new first process from another script started 4327 2223 newsecond.cgi 4328 2223 newthird.py 4329 2223 newfourth.cgi now i am killing process by (when a stop button is pressed) kill -6 2222 ###from terminal then only first.py is getting killed and the remaining co-processes still running. Of course i can kill other processes from terminal,,but i want to do it in a more pythonic way(by running a script which will trigger when someone press a STOP button form front-end designed to run .py files ) Now how can i kill all those co-process as soon as i kill first.py (as i don't want its co's to run anymore) but the other newfirst.py and its co's should not get disturbed. what i come up to is this far import os pid = os.getpid() os.system('kill -9 ' + pid) so how to filter out co-processes from that first process id 2222 and kill them. i have also tried using psutil,but passing name after name to kill is not very convincing. I have checked subprocess.popen method but failed and now i am out of logic,please suggest. If any other info is needed,please do comment. Answer: From your question, I am not able to understand; however I am assuming that you have process id handy e.g. in your example, you have process id 2222. Then you can try this: #Assuming you have parent_pid i.e. from your example you have 2222 pname = psutil.Process(parent_pid) cpid = pname.get_children(recursive=True) for pid in cpid: os.kill(pid.pid, signal_num) #signal_num is the signal you want to send i.e. 9 as per your example Please take care of exception handling e.g. check if process/child-process exist before you kill it etc using `try - except` block.
Compute a CRC32C (Castagnoli) which uses the generator polynomial 1EDC6F41h following Rocksoft Model CRC Algorithm in Python Question: I did explore Crcmod python library but couldnt use it as my gen poly- 0x1EDC6F41 is not considered a 32 bit poly :( Is there a way to tweak it or any other python lib that I can use to do this? Name : "CRC-32C" Width : 32 Poly : 1EDC6F41h Init : FFFFFFFFh RefIn : True RefOut : True XorOut : FFFFFFFFh Check : E3069283h Here is what I tried- import crcmod f = crcmod.mkCrcFun(0x1EDC6F41) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\Lib\site-packages\crcmod\crcmod.py", line 281, in mkCrcFun (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut) File "C:\Python27\Lib\site-packages\crcmod\crcmod.py", line 405, in _verifyParams sizeBits = _verifyPoly(poly) File "C:\Python27\Lib\site-packages\crcmod\crcmod.py", line 302, in _verifyPoly raise ValueError(msg) ValueError: The degree of the polynomial must be 8, 16, 24, 32 or 64 Answer: Usually CRC polynomials are specified without the most significant bit, which is always 1. But it looks like the crcmod library expects this bit to be specified. So you should use the polynomial `0x11EDC6F41`. (adding a 1 to the left).
Changing language typing direction using selenium Question: I am trying to change the typing direction of text using selenium Python to right to left. The normal Key sequence in the keyboard for that is CTRL+SHIFT (both right). I have tried the following: from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import ActionChains def testLangDirChange(self): self.driver.get("http://unixpapa.com/js/testkey.html") XPathTB='//textarea[@name="t"]' WebDriverWait(self.driver, 15).until(EC.presence_of_element_located((By.XPATH, XPathTB))) TB=self.driver.find_element_by_xpath(XPathTB) TB.click() actionChains=ActionChains(self.driver) actionChains.key_down(Keys.CONTROL).key_down(Keys.SHIFT).key_up(Keys.CONTROL).key_up(Keys.SHIFT).perform() I see the correct Key sequence in the tester, but the typing direction does not change (I still get left to right). I also tried: firefoxProfile.native_events_enabled = False firefoxProfile.set_preference("intl.accept_languages", 'he-IL') But it did not help. (You must have a right to left keyboard layout such as Hebrew in order to test this) **UPDATE 1** : I just enabled the following checkboxes on the testing site: modifiers, DOM 3, old DOM 3 and compared the two outputs. what I see is that in the selenium typing it is location=1 and in the keyboard test it is location=2. Maybe Selenium types LEFT SHIFT when I do Keys.SHIFT(although the key LEFT SHIFT is separately specified in Keys)? **UPDATE 2:** I found inside the module selenium.webdriver.common.keys.Keys the following: SHIFT = '\ue008' LEFT_SHIFT = SHIFT so they are indeed defined the same. how do I specify RIGHT SHIFT in there? Answer: I'm not really sure your WebDriver can send commands to OS level, I think what it does is to operate within the browser only. Instead why don't you try inputting the other language directly with sendKeys(otherLang) ?
Speech recognition for Python 3.4 thats easy to work? Question: I wish to get a simple speech recognition that works. I have been looking at this on speech_recognition, When I execute the code the following error occurs import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: print("You said " + r.recognize(audio)) except LookupError: print("You said " + r.recognize(audio)) # recognize speech using Google Speech Recognition AttributeError: 'Recognizer' object has no attribute 'recognize' print("Could not understand audio") This was copied from their examples on their web page Answer: I got it working. import speech_recognition as sr # obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) print(r.recognize_google(audio))
Python3. Prompt requires ctrl+c and halts script Question: I'm writing a small script that runs through a directory and attempts to obtain version numbers by running "filename --version". Now for the most part it works or fails in a manageable way. However I've come across one file "iptables-restore" in /sbin/ that fails when --version is passed to it. However the failure leaves the prompt in a state that requires a ctrl+z or ctrl+c to return to the prompt, and thus halts my script. Here's the code: try: subOut = subprocess.check_output([fname, "--version"]) except subprocess.CalledProcessError as cpE: fObj.write('{0:25}RETURN CODE:{1:15}\t\t{2:30}\n'.format(fnamecolon, cpE.returncode, cpE.output)) fnamecolon = '' pass except Exception as e: pass I just wondered if there's an elegant way to handle this - either via a return code or perhaps an Exception. I'm fairly new to Python and am doing this for practice really - so any guidance is greatly appreciated. Thanks all! Answer: So this works better - probably still some things I'm not understanding though... try: # devnull=open(os.devnull, 'w') try: from subprocess import DEVNULL # Python 3 except ImportError: DEVNULL = open(os.devnull, 'r+b', 0) subOut = Popen([fname, "--version"], stdin=DEVNULL, stdout=PIPE, stderr=STDOUT, close_fds=True) output = subOut.stdout.read() except subprocess.CalledProcessError as cpE: fObj.write('{0:25}RETURN CODE:{1:15}\t\t{2:30}\n'.format(fnamecolon, cpE.returncode, cpE.output)) fname = '' pass except Exception as e: # fObj.write('{0:30}{1:30}{2:30}\n'.format(fname, e.returncode, e.output)) pass
Python libtorrent creates empty torrent with magnet link Question: I tried to download a torrent (the specific .torrent file) given _only_ an info_hash. I know this was discussed here before, I even searched and modified my code accordingly. The result is the following: import libtorrent as lt import time import sys import bencode ses = lt.session() ses.listen_on(6881, 6891) params = { 'save_path': '.', 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } info_hash = "2B3AF3B4977EB5485D39F96FE414729530F48386" link = "magnet:?xt=urn:btih:" + info_hash h = lt.add_magnet_uri(ses, link, params) ses.add_dht_router("router.utorrent.com", 6881) ses.add_dht_router("router.bittorrent.com", 6881) ses.add_dht_router("dht.transmissionbt.com", 6881) ses.start_dht() while (not h.has_metadata()): time.sleep(1) torinfo = h.get_torrent_info() fs = lt.file_storage() for f in torinfo.files(): fs.add_file(f) torfile = lt.create_torrent(fs) torfile.set_comment(torinfo.comment()) torfile.set_creator(torinfo.creator()) f = open("torrentfile.torrent", "wb") f.write(lt.bencode(torfile.generate())) f.close() This produces a torrent file, that cannot be loaded by transmission. It lacks trackers as well as the real pieces (creates \x00 instead of the actual pieces). The following line _would_ save the pieces, but still lacks the trackers and is not able to be opened by transmission: f = open("torrentfile.torrent", "wb") f.write(lt.bencode(torinfo.metadata())) f.close() How can I create a torrent, that looks like the actual torrent, by just using the magnet link (as stated in the code)? (I am using Ubuntu 15.04 x64 with libtorrent 0.16.18-1) I am not illegally downloading the file behind the torrent- however, I have the torrent to be compared to the torrent downloaded by my script. Answer: You're not setting piece hashes and the piece size (of the `file_storage` object). See the [documentation](http://libtorrent.org/reference- Create_Torrents.html#create_torrent). However, a simpler and more robust way of creating a .torrent file is to use the `create_torrent` constructor that directly takes a `torrent_info` object. i.e.: torfile = lt.create_torrent(h.get_torrent_info()) f = open("torrentfile.torrent", "wb") f.write(lt.bencode(torfile.generate())) f.close()
Having a colon in a networkx node Question: I need to create a graph using `networkx` (and `pydot2`) from data that I can't predict. I have a problem with the `:` character ; if I want to create a node called `I like Python because : it's fast and readable`, `networkx` will create two nodes, one called `I like python because : it's fast and readable` and another called `it's fast and readable`. It considers the colon as a node separation operator. How can I avoid that ? Is there a way to escape the colon, or to tell `networkx` not to parse then ? The nodes are represented as strings (with the colon in them). Thanks ! Answer: Use the networkx 1.10 and everything works fine: From a python interactive shell: >>> import networkx as nx >>> G=nx.Graph() >>> G.add_node("I like Python because : it's fast and readable") >>> G.nodes() ["I like Python because : it's fast and readable"] As you use a quote `'` inside the string use double quote `"` as string delimiter.
timeit is not working in the python manage.py shell Question: I have to find time taken to run query in django project i.e. `python manage.py shell` code: >>> import timeit >>> d = {"a":1, "b":2} >>> def a1(): ... for i in d: ... a = i, d[i] ... >>> a1() >>> print "Time 1:", timeit.timeit('a1()', 'from __main__ import a1 as a1') Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib64/python2.6/timeit.py", line 227, in timeit return Timer(stmt, setup, timer).timeit(number) File "/usr/lib64/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 3, in inner ImportError: cannot import name a1 Time 1: >>> **This is not working in python manage.py shell** **But this is working file I write code in py file and run my command line.** There is something wrong in `from __main__ import a1 as a1` Answer: I have encountered the same problem and have found no real solution. What works for a few lines of code like the one in your example, is putting them directly in the `setup` parameter of timeit(): >>> setup = 'd={"a":1, "b":2}\ndef a1():\n for i in d:\n a = i, d[i]\n' >>> print "Time 1:", timeit.timeit('a1()', setup) Time 1: 0.337239027023 Yet, while it does not help explain why the import in `timeit` doesn't work in the django shell, why not implement your own timing function? >>> import time >>> def time_function(fnc, number=10**6): >>> start = time.time() >>> for i in xrange(number): >>> fnc() >>> return time.time() - start >>> print "Time 1:", time_function(a1) Time 1: 0.3310558795928955
Randomising conditions with alternating order in PsychoPy Question: I have a simple experiment with 8 different trials that I wish to present only once without repeat; participants are asked to 'solve' a numeric sequence where 4 sequences have a solution (S) and 4 are unsolvable (U). Thus, I have 8 trials: S1, S2, S3, S4, U1, U2, U3, U4. I want to present the trials so that they alternate: S1, U1, S2, U2, S3, U3, S4, U4 However, I want to randomise the order of S and U, whilst maintaining the alternating pattern. For example, S3, U2, S2, U4, S4, U1, S1, U3 I am using the builder and am new to Python (although I am familiar with coding in Matlab). The only solutions I can come up with is to try and shuffle the order of the trials in the excel file and then combining them so they alternate - this doesn't seems very elegant though. Is there a simple way to implement this within the builder or by adding a code component? I have included the input file / excel table that defines the trials. The column 'difficulty' indicates whether they are Solvable or Unsolvable trials. cheers, Harry [input](http://i.stack.imgur.com/PULwp.png) Answer: Uses prior answer [on list conversions](http://stackoverflow.com/questions/12355442/converting-a-list-of- tuples-into-a-simple-flat-list) and concept of [list comprehensions](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) import random as r a = ["s1","s2","s3","s4"] b = ["u1","u2","u3","u4"] r.shuffle(a) r.shuffle(b) trialList = [tr for pr in zip(a,b) for tr in pr]
Python distutils exclude setup.py Question: My `setup.py` script is simple: from distutils.core import setup setup(name='my-awesome-app', version='1.0', scripts=['my-awesome-app.py'], ) And the file structure is: my-awesome-app/ my-awesome-app.py setup.py In theory I am only including `my-awesome-app.py` in the distribution. In practice `setup.py` ends up in the RPM too. I don't see a point of including `setup.py` there, is there a way to force distutils to leave this file out? I am using python 2.7, I build my RPM by running `python setup.py bdist_rpm`. Thanks for help :) Answer: `setup.py` is required because when the package is installed in your environment, the following command is run: $ python setup.py install Running `python setup.py bdist_rpm` only creates a _distribution_ package that you can give to others. `setup.py` is still required to do the installation.
Matplotlib didn’t show the plot Question: I don’t know why my matplotlib didn’t show plots, and no errors too. I thinks I missing something on its installation because when in IPython notebooks an QtIpython using `%mayplotlib inline` directive have no problems but when running from terminal or script didn’t show anything. Any ideas ?? for example, in QtIPython and Ipython notebook I run %matplotlib inline import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') ax.plot([1,2,3,4,5,6,7,8,9,0],[2,3,4,5,6,7,8,9,0,11], '-r') ax.grid() plt.show() and the plot shows Ok! but in a simple script with import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') ax.plot([1,2,3,4,5,6,7,8,9,0],[2,3,4,5,6,7,8,9,0,11], '-r') ax.grid() plt.show() didn’t show anything Answer: If you use matplotlib inline in IPython notebook, the plots are shown automatically. If you plot things in a script you have to put a `plt.show()` at the end to actually show the figure. In the terminal you can also use `plt.ion()` to switch on intreactive mode.
Incorrect shape for arguments to lasagne function Question: I'm trying to build a neural network regressor using the [scikit- neuralnetwork](https://github.com/aigamedev/scikit-neuralnetwork) library. As I understand it, ny NN seems to be being built fine, but I keep running into the following error at the `nn.predict()` call: rmichael@node:~/Sandbox$ sudo python NNScript.py Traceback (most recent call last): File "NNScript.py", line 15, in <module> print nn.predict(X_train[0]) File "/users/rmichael/scikit-neuralnetwork/sknn/mlp.py", line 309, in predict return super(Regressor, self)._predict(X) File "/users/rmichael/scikit-neuralnetwork/sknn/mlp.py", line 256, in _predict return self._backend._predict_impl(X) File "/users/rmichael/scikit-neuralnetwork/sknn/backend/lasagne/mlp.py", line 242, in _predict_impl return self.f(X) File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 786, in __call__ allow_downcast=s.allow_downcast) File "/usr/local/lib/python2.7/dist-packages/theano/tensor/type.py", line 177, in filter data.shape)) TypeError: ('Bad input argument to theano function with name "/users/rmichael/scikit-neuralnetwork/sknn/backend/lasagne/mlp.py:199" at index 0(0-based)', 'Wrong number of dimensions: expected 2, got 1 with shape (59,).') rmichael@node:~/Sandbox$ My code is as follows: import numpy as np from sknn.mlp import Regressor, Layer X_train = np.genfromtxt("OnlineNewsPopularity.csv", dtype=float, delimiter=',', skip_header=1, usecols=range(1,60)) y_train = np.genfromtxt("OnlineNewsPopularity.csv", dtype=float, delimiter=',', names=True, usecols=(60)) nn = Regressor( layers=[ Layer("Rectifier", units=1), Layer("Linear")], learning_rate=0.02, n_iter=1) nn.fit(X_train, y_train) print nn.predict(X_train[0]) Might someone here know what's going wrong here? Any help would be greatly appreciated. Answer: The problem is that the model expects its input to be a matrix but you're providing a vector. In the line print nn.predict(X_train[0]) why do you only pass the first row of `X_train`? I expect if you passed the whole matrix, i.e. print nn.predict(X_train) or stacked the first row so it's passed as a matrix with only one row: print nn.predict(np.expand_dims(X_train[0], 0)) then it may work as expected.
ioctl errorno: 25 in GPIB communication using python-gpib Question: I am trying to communicate with a Tektronix oscilloscope TDS 210 using a GPIB- USB-HS adapter of National Instruments. My system is Ubuntu 14.04.3 where I installed linux-gpib as described in this link: [Linux GPIB Driver package (source)](http://sourceforge.net/p/linux-gpib/mailman/linux-gpib- general/thread/[email protected]/) and also python-gpib. I reconfigured the /etc/gpib.conf like this: interface { minor = 0 /* board index, minor = 0 uses /dev/gpib0, minor = 1 uses /dev/gpib1, etc. */ board_type = "ni_usb_b" /* type of interface board being used */ name = "tds" /* optional name, allows you to get a board descriptor using ibfind() */ pad = 0 /* primary address of interface */ sad = 0 /* secondary address of interface */ master = yes /* interface board is system controller */ timeout = TNONE /* timeout for commands */ } device { minor = 0 name = "ATTN" pad = 0 sad = 0 } The lsmod give me this: $ lsmod | grep gpib ni_usb_gpib 36515 1 gpib_common 38274 3 ni_usb_gpib The dmesg: $ dmesg | grep gpib [ 2173.992039] ni_usb_gpib driver loadingni_usb_gpib: probe succeeded for path: usb-0000:00:1a.0-1.2 [ 2173.992098] usbcore: registered new interface driver ni_usb_gpib [ 2173.992102] gpib: registered ni_usb_b interface [ 2173.995077] ni_usb_gpib: attach But when a try to communicate with the oscilloscope using ibtest I receive this error: gpib status is: ibsta = 0x8100 < ERR CMPL > iberr= 0 EDVR 0: OS error ibcnt = 25 And with Python: import Gpib tds = Gpib.Gpib(0,0) tds.write("*IDN?") --------------------------------------------------------------------------- GpibError Traceback (most recent call last) <ipython-input-4-e61e6a76ac49> in <module>() 1 import Gpib 2 inst = Gpib.Gpib(0,0) ----> 3 inst.write("*IDN?") /usr/local/lib/python2.7/dist-packages/Gpib.pyc in write(self, str) 47 48 def write(self,str): ---> 49 gpib.write(self.id, str) 50 51 def write_async(self,str): GpibError: write() error: Inappropriate ioctl for device (errno: 25) Did someone already have a similar problem or knows how to fix this? Answer: I had the exact same errors as you from both ibtest, and python. I was trying to get gpib working on a pi. I followed the tutorial <https://xdevs.com/guide/ni_gpib_rpi/> I fixed it by changing my /etc/gpib.conf (note eos): interface { minor = 0 board_type = "ni_usb_b" name = "violet" pad = 0 sad = 0 timeout = T30s eos = 0xd /* EOS Byte, was 0xa and I got same errors as you */ set-reos = yes set-bin = no set-xeos = no set-eot = yes master = yes } Now everything works! $ sudo gpib_config $ sudo ibtest Do you wish to open a (d)evice or an interface (b)oard? (you probably want to open a device): d enter primary gpib address for device you wish to open [0-30]: 3 trying to open pad = 3 on /dev/gpib0 ... You can: w(a)it for an event ... (w)rite data string : w enter a string to send to your device: *idn? sending string: *idn? gpib status is: ibsta = 0x2100 < END CMPL > iberr= 0 ibcnt = 6 You can: w(a)it for an event ... (r)ead string : r enter maximum number of bytes to read [1024]: trying to read 1024 bytes from device... received string: 'AEROFLEX,3920,1000662592,3.7.0,2' Number of bytes read: 32 gpib status is: ibsta = 0x2100 < END CMPL > iberr= 0 ibcnt = 32 In Python, I get errors unless I call clear after instantition, after that it's good to go: ? sudo python Python 2.7.9 (default, Mar 8 2015, 00:52:26) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Gpib >>> inst = Gpib.Gpib(0,3) >>> inst.clear() >>> inst.write("*idn?") >>> inst.read(100) 'AEROFLEX,3920,1000662592,3.7.0,2' If you still can't talk to an instrument try the string ID? instead of *IDN?. Some hp equipment has an alternate command syntax which uses different command strings, check the manual (it might be in the back mentioned in passing), you can usually switch the syntax back and forth with a command. Good luck.
Python: Exporting text list to a text file Question: I am new to Python and I was wondering how to save this hashed password list (stored in variable _passwords_) ['73868cb1848a216984dca1b6b0ee37bc', '2de9210e9173ca4151bb220a2ded6cdb', '8c064f4067cf0c59c68ec281f5786cb2'] to a text file in the format: 73868cb1848a216984dca1b6b0ee37bc 2de9210e9173ca4151bb220a2ded6cdb 8c064f4067cf0c59c68ec281f5786cb2 currently I am able to save it to a text file however it saves as ['73868cb1848a216984dca1b6b0ee37bc', '2de9210e9173ca4151bb220a2ded6cdb', '8c064f4067cf0c59c68ec281f5786cb2'] current code to save file: f = open( 'hash.txt', 'w' ) f.write(repr(passwords) + '\n' ) f.close() Please help :) Thank you Reason for wanting to save in text is so I can call that list in a new script to decrypt them however because it saves as a list (and imports as a list) it creates a list in a list and messes up my decryption script. Edit: Thank you all for the great answers :) its a huge help! Answer: You can use the following code : f = open( 'hash.txt', 'w' ) for a in passowrds: f.write(a + '\n' ) #you have to pass them as separate variables f.close() Whenever you have to take out take out values from a list, you can use the _for loop_ Example list = ["cat","dog","lion"] for animal in list: print animal This will print each animal in the list. You can use any other variable name in place of animal.
Pyinstaller + Django = No module named 'django.core.context_processors' Question: I am trying to package my django app with pyinstaller and I created this pyinstaller spec file for this purpose: # -*- mode: python -*- block_cipher = None a = Analysis(['manage.py'], pathex=['/home/gero/PycharmProjects/gen-optimizer-precision'], binaries=None, datas=None, hiddenimports=[], hookspath=None, runtime_hooks=None, excludes=['matplotlib'], win_no_prefer_redirects=None, win_private_assemblies=None, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='optimizer', debug=True, strip=None, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=None, upx=True, name='optimizer') Here is the pyinstallers log: 39 INFO: PyInstaller: 3.0 : Python: 3.4.2 39 INFO: Platform: Linux-3.16.0-44-generic-x86_64-with-Ubuntu-14.10-utopic 41 INFO: UPX is not available. 41 INFO: Removing temporary files and cleaning cache in ~/.local/share/pyinstaller 47 INFO: Extending PYTHONPATH with ~/PycharmProjects/gen-optimizer-precision 47 INFO: checking Analysis 47 INFO: Building Analysis because out00-Analysis.toc is non existent 47 INFO: Initializing module dependency graph... 48 INFO: Initializing module graph hooks... 49 INFO: Analyzing base_library.zip ... 1336 INFO: Processing pre-find module path hook distutils 2482 INFO: running Analysis out00-Analysis.toc 2510 INFO: Analyzing manage.py 4420 INFO: Looking for import hooks ... 4422 INFO: Processing hook hook-django.template.loaders.py 5025 INFO: Processing hook hook-encodings.py 5033 INFO: Processing hook hook-django.db.backends.py 5408 WARNING: Hidden import 'django.db.backends.__pycache__.base' not found (probably old hook) 5503 INFO: Processing hook hook-distutils.py 5504 INFO: Processing hook hook-xml.py 5697 INFO: Processing hook hook-django.core.management.py 6317 INFO: Excluding import 'matplotlib' 6319 WARNING: Removing import 'matplotlib' 6319 INFO: Excluding import 'IPython' 6319 INFO: Excluded import 'tkinter' not found 6319 INFO: Processing hook hook-django.db.backends.mysql.base.py 6321 INFO: Processing hook hook-xml.dom.py 6322 INFO: Processing hook hook-django.py 6323 INFO: Django root directory ~/PycharmProjects/gen-optimizer-precision/genoptimizer ~/optimizer/lib/python3.4/site-packages/django/forms/models.py:1246: RemovedInDjango19Warning: cache_choices has been deprecated and will be removed in Django 1.9. *args, **kwargs) 6964 INFO: Collecting Django migration scripts. 7027 WARNING: Hidden import 'django.contrib.messages.context_processors.messages' not found (probably old hook) 8465 INFO: Processing pre-find module path hook site 8466 INFO: site: retargeting to fake-dir '~/optimizer/lib/python3.4/site-packages/PyInstaller/fake-modules' 9558 WARNING: Hidden import 'optimizer.templatetags' not found (probably old hook) 9957 WARNING: Hidden import 'django.template.loaders.app_directories.Loader' not found (probably old hook) 9964 WARNING: Hidden import 'django.contrib.sessions.context_processors' not found (probably old hook) 10063 WARNING: Hidden import 'django.contrib.contenttypes.context_processors' not found (probably old hook) 10063 WARNING: Hidden import 'django.contrib.sessions.templatetags' not found (probably old hook) 10063 WARNING: Hidden import 'optimizer.context_processors' not found (probably old hook) 10063 WARNING: Hidden import 'django.contrib.auth.context_processors.auth' not found (probably old hook) 10063 WARNING: Hidden import 'csvimport.app.CSVImportConf' not found (probably old hook) 10146 WARNING: Hidden import 'suitlocale.templatetags' not found (probably old hook) 10148 WARNING: Hidden import 'django.template.context_processors.media' not found (probably old hook) 10149 WARNING: Hidden import 'django.contrib.contenttypes.templatetags' not found (probably old hook) 10149 WARNING: Hidden import 'genoptimizer.optemplates.templatetags' not found (probably old hook) 10149 WARNING: Hidden import 'django.contrib.staticfiles.context_processors' not found (probably old hook) 10399 WARNING: Hidden import 'crispy_forms.context_processors' not found (probably old hook) 10417 WARNING: Hidden import 'suit.context_processors' not found (probably old hook) 10417 WARNING: Hidden import 'genoptimizer.optemplates.context_processors' not found (probably old hook) 10442 WARNING: Hidden import 'django.template.context_processors.static' not found (probably old hook) 10442 WARNING: Hidden import 'django.template.context_processors.debug' not found (probably old hook) 10455 WARNING: Hidden import 'csvimport.app.CSVImportConf.templatetags' not found (probably old hook) 10455 WARNING: Hidden import 'django.template.context_processors.tz' not found (probably old hook) 10455 WARNING: Hidden import 'django.contrib.auth.templatetags' not found (probably old hook) 10455 WARNING: Hidden import 'csvimport.app.CSVImportConf.context_processors' not found (probably old hook) 10460 WARNING: Hidden import 'django.contrib.admin.context_processors' not found (probably old hook) 10461 WARNING: Hidden import 'suitlocale.context_processors' not found (probably old hook) 10461 WARNING: Hidden import 'django.contrib.messages.templatetags' not found (probably old hook) 10462 WARNING: Hidden import 'django.template.context_processors.i18n' not found (probably old hook) 10462 WARNING: Hidden import 'django.template.loaders.filesystem.Loader' not found (probably old hook) 10687 INFO: Processing hook hook-django.db.backends.oracle.base.py 10689 INFO: Processing hook hook-pydoc.py 10690 INFO: Processing hook hook-django.core.mail.py 10743 INFO: Processing hook hook-xml.sax.py 10743 INFO: Processing hook hook-setuptools.py 10744 INFO: Processing hook hook-xml.dom.domreg.py 10744 INFO: Processing hook hook-sqlite3.py 10747 INFO: Processing hook hook-sysconfig.py 10748 INFO: Processing hook hook-psycopg2.py 10748 WARNING: Hidden import 'mx.DateTime' not found (probably old hook) 10748 INFO: Processing hook hook-django.core.cache.py 10773 INFO: Processing hook hook-django.contrib.sessions.py 10826 INFO: Looking for ctypes DLLs 10863 WARNING: library rpcrt4.dll required via ctypes not found 10943 INFO: Analyzing run-time hooks ... 10959 INFO: Including run-time hook 'pyi_rth_pkgres.py' 10960 INFO: Including run-time hook 'pyi_rth_django.py' 10992 INFO: Looking for dynamic libraries 11644 INFO: Looking for eggs 11644 INFO: Python library not in binary depedencies. Doing additional searching... 11674 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython3.4m.so.1.0 11707 INFO: Warnings written to ~/PycharmProjects/gen-optimizer-precision/build/optimizer/warnoptimizer.txt 11721 INFO: checking PYZ 11721 INFO: Building PYZ because out00-PYZ.toc is non existent 11721 INFO: Building PYZ (ZlibArchive) ~/PycharmProjects/gen-optimizer-precision/build/optimizer/out00-PYZ.pyz 12267 INFO: checking PKG 12267 INFO: Building PKG because out00-PKG.toc is non existent 12267 INFO: Building PKG (CArchive) out00-PKG.pkg 12308 INFO: Bootloader ~/optimizer/lib/python3.4/site-packages/PyInstaller/bootloader/Linux-64bit/run_d 12308 INFO: checking EXE 12308 INFO: Building EXE because out00-EXE.toc is non existent 12308 INFO: Building EXE from out00-EXE.toc 12308 INFO: Appending archive to EXE ~/PycharmProjects/gen-optimizer-precision/build/optimizer/optimizer 12322 INFO: checking COLLECT 12322 INFO: Building COLLECT because out00-COLLECT.toc is non existent 12322 INFO: Removing dir ~/PycharmProjects/gen-optimizer-precision/dist/optimizer 12473 INFO: Building COLLECT out00-COLLECT.toc I am getting this error at runtime when I try to request the home page: Starting development server at http://127.0.0.1:8002/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "~/optimizer/lib/python3.4/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "~/PycharmProjects/gen-optimizer-precision/optimizer/views.py", line 52, in optimized_setup return render(request, 'optimizer.html', {'form': form}) File "~/optimizer/lib/python3.4/site-packages/django/shortcuts.py", line 67, in render template_name, context, request=request, using=using) File "~/optimizer/lib/python3.4/site-packages/django/template/loader.py", line 99, in render_to_string return template.render(context, request) File "~/optimizer/lib/python3.4/site-packages/django/template/backends/django.py", line 74, in render return self.template.render(context) File "~/optimizer/lib/python3.4/site-packages/django/template/base.py", line 209, in render with context.bind_template(self): File "/usr/lib/python3.4/contextlib.py", line 59, in __enter__ return next(self.gen) File "~/optimizer/lib/python3.4/site-packages/django/template/context.py", line 237, in bind_template processors = (template.engine.template_context_processors + File "~/optimizer/lib/python3.4/site-packages/django/utils/functional.py", line 59, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "~/optimizer/lib/python3.4/site-packages/django/template/engine.py", line 90, in template_context_processors return tuple(import_string(path) for path in context_processors) File "~/optimizer/lib/python3.4/site-packages/django/template/engine.py", line 90, in <genexpr> return tuple(import_string(path) for path in context_processors) File "~/optimizer/lib/python3.4/site-packages/django/utils/module_loading.py", line 26, in import_string module = import_module(module_path) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked ImportError: No module named 'django.core.context_processors' Any clues fellows? Answer: From [docs](https://docs.djangoproject.com/en/1.8/ref/templates/api/): > Changed in **Django 1.8** : > > Built-in template context processors were moved from > **django.core.context_processors** to **django.template.context_processors** > in Django 1.8. Probably you are importing context_processors using the old path in `~/PycharmProjects/gen-optimizer-precision/optimizer/views.py`.
Retrieve image of url to jpg file Question: from urllib.request import urlopen from shutil import copyfileobj sh='''http://www.stockcharts.com/h-sc/ui?s=GLD''' floc= '''c:/files/python/texts/sh.jpg''' with urlopen (sh) as str ,open (floc,'wb')as outf: copyfileobj(str,outf) This code does not produce a valid jpg file. Is there another way of coding it? Answer: **Problem:** Your problem is the fact that your program is not working with an image URL. **Solution:** You want to parse the html from the site then using wildcards get the IMG Url link then use that for your program.(to note that site uses .Png) The below code is just an example of the downloading the image not the Html stuff (I'm new to coding myself) import random import urllib.request def download_web_image(url): name = random.randrange(1,1000) full_name = str(name) + ".png" urllib.request.urlretrieve(url,full_name) img_url = input('Please Insert Image Url you wish to download: ') download_web_image(img_url)
Writing processed data into excel using CSV Python Question: I'm trying to write some data into the excel spreadsheet using CSV. I'm writing a motif finder, reading the input from fasta and outputs to excel. But I'm having a hard time writing the data in a correct format. My desired result in the excel is like below.. SeqName M1 Hits M2 Hits Seq1 MN[A-Z] 3 V[A-Z]R[ML] 2 Seq2 MN[A-Z] 0 V[A-Z]R[ML] 5 Seq3 MN[A-Z] 1 V[A-Z]R[ML] 0 I have generated correct results but I just don't know how to put them in a correct format like above. This is the code that I have so far. import re from Bio import SeqIO import csv import collections def SearchMotif(f1, motif, f2="motifs.xls"): with open(f1, 'r') as fin, open(f2,'wb') as fout: # This makes SeqName static and everything else mutable thus, when more than 1 motifs are searched, # they can be correctly placed into excel. writer = csv.writer(fout, delimiter = '\t') motif_fieldnames = ['SeqName'] writer_dict = csv.DictWriter(fout,delimiter = '\t' ,fieldnames=motif_fieldnames) for i in range(0,len(motif),1): motif_fieldnames.append('M%d' %(i+1)) motif_fieldnames.append('Hits') writer_dict.writeheader() # Reading input fasta file for processing. fasta_name = [] for seq_record in SeqIO.parse(f1,'fasta'): sequence = repr(seq_record.seq) # re-module only takes string fasta_name.append(seq_record.name) print sequence ********** for j in motif: motif_name = j print motif_name ********** number_count = len(re.findall(j,sequence)) print number_count ********** writer.writerow([motif_name]) for i in fasta_name: writer.writerow([i]) # [] makes it fit into one column instead of characters taking each columns The print statement that have the asterisks ********** generates this...where number is the number of Hits and difference sequences are seq1, seq2 ...and so on. Seq('QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQ...LTS', SingleLetterAlphabet()) PA[A-Z] 0 Y[A-Z]L[A-Z] 0 Seq('SFNVATLPAESSSTDLDTTVLLPDEPAEVSDLERIETEWTNMKILELPFAPQMK...VSS', SingleLetterAlphabet()) PA[A-Z] 2 Y[A-Z]L[A-Z] 0 Seq('PAESIYFKIEKTYNLT', SingleLetterAlphabet()) PA[A-Z] 1 Y[A-Z]L[A-Z] 1 Answer: You can write your data to a Pandas DataFrame, and then use the DataFrame's to_csv method to export it to a CSV. There is also a to_excel method. Pandas won't let you have multiple columns with the same name, like your "Hits" column. However, you can work around that by putting the column names you want in the first row and using the header=False option when you export. "import pandas as pd", then replace your code starting at "fasta_name = []" with this: column_names = ['SeqName'] for i, m in enumerate(motif): column_names += ['M'+str(i), 'Hits'+str(i)] df = pd.DataFrame(columns=column_names) for row, seq_record in enumerate(SeqIO.parse(f1, 'fasta')): sequence = repr(seq_record.name) df.loc[row, 'SeqName'] = sequence for i, j in enumerate(motif): df.loc[row, 'M'+str(i)] = j df.loc[row, 'Hits'+str(i)] = len(re.findall(j, sequence)) df.to_csv(index=False)
Python code to redirect stdin and stdout to a shell script Question: I am trying to write a program that reads from a file and writes to a new file using the command line. I am using the CommandLine class and using ArgParse to accept different args as well as the file names for input and output. I am trying to redirect stdin and stdout to these files. However, I keep getting an error that I put at the bottom of the code below. Am I inputting the arguments to the command line incorrectly, or is something else going on? All of my files are in the same folder. class CommandLine() : ''' Handle the command line, usage and help requests. CommandLine uses argparse, now standard in 2.7 and beyond. it implements a standard command line argument parser with various argument options, a standard usage and help, and an error termination mechanism do-usage_and_die. attributes: all arguments received from the commandline using .add_argument will be avalable within the .args attribute of object instantiated from CommandLine. For example, if myCommandLine is an object of the class, and requiredbool was set as an option using add_argument, then myCommandLine.args.requiredbool will name that option. ''' def __init__(self, inOpts=None): ''' CommandLine constructor. Implements a parser to interpret the command line argv string using argparse. ''' import argparse self.parser = argparse.ArgumentParser(description = 'Program prolog - a brief description of what this thing does', epilog = 'Program epilog - some other stuff you feel compelled to say', add_help = True, #default is True prefix_chars = '-', usage = '%(prog)s [options] -option1[default] <input >output' ) self.parser.add_argument('inFile', action = 'store', help='input file name') self.parser.add_argument('outFile', action = 'store', help='output file name') self.parser.add_argument('-lG', '--longestGene', action = 'store', nargs='?', const=True, default=False, help='longest Gene in an ORF') self.parser.add_argument('-mG', '--minGene', type=int, choices= (0, 100, 200, 300, 500, 1000), action = 'store', help='minimum Gene length') self.parser.add_argument('-s', '--start', action = 'append', nargs='?', help='start Codons') #allows multiple list options self.parser.add_argument('-st', '--stop', action = 'append', nargs='?', help='stop Codons') #allows multiple list options self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1') if inOpts is None : self.args = self.parser.parse_args() else : self.args = self.parser.parse_args(inOpts) C:\Users\Zach\Documents\UCSC\BME 160\Lab 5>python findORFsCmdLine.py -- minGene=3 00 --longestGene --start=ATG --stop=TAG --stop=TGA --stop=TAA <tass2.fa >result. txt usage: findORFsCmdLine.py [options] -option1[default] <input >output findORFsCmdLine.py: error: the following arguments are required: inFile, outFile Answer: The error tells you that you did not provide `inFile` and `outFile`. This seems confusing because you did indeed provide `<tass2.fa` and `>result.txt` on the command line. On the command line `<` and `>` have special meaning. `<tass2.fa` is handled by `bash` (or whichever shell you use) and it opens the file `tass2.fa` and sends the contents to your program over `stdin`. It then removes that from the list of command line arguments because `bash` has already taken care of it. A similar thing happens with `>result.txt` where any output from your file that normally goes to `stdout` such as print calls will be written to that file. Again `bash` handles this so your program never gets the argument from the command line. To make sure the filenames go to your program you need to remove the `<` and `>` symbols. * * * In addition to that, the way you are call `add_argument` for `inFile` and `outFile` is not correct. Using `action='store'` simply stores the value of the argument under the given name. This is the default action so doing that is redundant. You need to tell `add_argument` that these are file types. Then you can use these as files and read and write as you desire. parser.add_argument('inFile', type=argparse.FileType('r')) parser.add_argument('outFile', type=argparse.FileType('w')) If you wish to allow these arguments to be optional and use `stdin` and `stdout` automatically if they do not supply a filename then you can do this: parser.add_argument('inFile', type=argparse.FileType('r'), nargs='?', default=sys.stdin) parser.add_argument('outFile', type=argparse.FileType('w'), nargs='?', default=sys.stdout) * * * You say you are writing a program that reads from a file and writes to a new file using the command line and go on to say that you are trying to redirect these files to stdin and stdout. If it is really your intention to redirect the input and output files using the shell with the `>` and `<` operators, then you do not need to call `add_argument` with `outFile` at all. Just let the shell handle it. Remove that line from your program and use `print` or similar to send your content to `stdout` and that file will be created. You will still need the call `add_argument('inFile', ...`.
how to print field in chinese in pymongo Question: I have an `extracted_text` field in each document and the value of `extracted_text` is some chinese text. when I want to print the `extracted_text` field the program encountered a run-time error. I know MongoDB store strings as `utf-8`, but my program failed to encode `extracted_text` in `gbk`. I tried some other decode encode combination and they all are wrong. I think I have grasped the knowledge of encode/decode of python, but this error made me confused. so could you please point out what's wrong with my program. Thanks! Below is my program and the output log. #encoding=gbk from pymongo import MongoClient import bson client = MongoClient('localhost', 27017) db=client.jd pages=db.pages for page in pages.find(): print page for key in page: print "1, key", key print "2, key type", type(page[key]) if page[key] is None: print key+"\t"+"None" elif type(page[key]) is unicode: print key +"\t"+ page[key].encode('gbk', 'ignore') the output {u'url': u'http://item.jd.com/1635670097.html', u'_id': ObjectId('5656815e4a487a1735aadbae'), u'extracted_text': u'\t\t\tPlover\u5544\u6728\u9e1f \u771f\u76ae\u76ae\u978b \u5546\u52a1\u4f11\u95f2\u978b\u900f\u6c14\u7537\u58eb\u5934\u5c42\u725b\u76ae\u590f\u5b63\u8212\u9002\u5957\u811a\u8f6f\u5e95\u82f1\u4f26\u5a5a\u978b\u6b63\u88c5\u978b\u5b50 \u9ed1\u8272 40\u3010\u56fe\u7247 \u4ef7\u683c \u54c1\u724c \u62a5\u4ef7\u3011-\u4eac\u4e1c\t\t\t\t\t\t\t\u6536\u85cf\u4eac\u4e1c\t\t\t\t\t\t\u60a8\u597d\uff01\u6b22\u8fce\u6765\u5230\u4eac\u4e1c\uff01\t\t\t\t\t\t\t[\u767b\u5f55]\t\t\t\t\t\t\t[\u514d\u8d39\u6ce8\u518c]\t\t\t\t\t\t\t\u6211\u7684\u8ba2\u5355\t\t\t\t\t\t\t\u4eac\u4e1c\u4f1a\u5458\t\t\t\t\t\t\t\u624b\u673a\u4eac\u4e1c\t\t\t\t\t\t\u5ba2\u6237\u670d\u52a1\t\t\t\t\t\t\t\t\t\u5e2e\u52a9\u4e2d\u5fc3\t\t\t\t\t\t\t\t\t\u552e\u540e\u670d\u52a1\t\t\t\t\t\t\t\t\t\u5728\u7ebf\u5ba2\u670d\t\t\t\t\t\t\t\t\t\u610f\u89c1\u5efa\u8bae\t\t\t\t\t\t\t\t\t\u5ba2\u670d\u90ae\u7bb1\t\t\t\t\t\t\u7f51\u7ad9\u5bfc\u822a\t\t\t\t\t\t\t\t\t\u7279\u8272\u680f\u76ee\t\t\t\t\t\t\t\t\t\t\t\u4eac\u4e1c\u901a\u4fe1\t\t\t\t\t\t\t\t\t\t\t\u6821\u56ed\u4e4b\u661f\t\t\t\t\t\t\t\t\t\t\t\u4e3a\u6211\u63a8\u8350\t\t\t\t\t\t\t\t\t\t\t\u89c6\u9891\u8d2d\u7269\t\t\t\t\t\t\t\t\t\t\t\u4eac\u4e1c\u793e\u533a\t\t\t\t\t\t\t\t\t\t\t\u5728\u7ebf\u8bfb\u4e66\t\t\t\t\t\t\t\t\t\t\t\u88c5\u673a\u5927\u5e08\t\t\t\t\t\t\t\t\t\t\t\u4eac\u4e1cE\u5361\t\t\t\t\t\t\t\t\t\t\t\u5bb6\u88c5\u57ce\t\t\t\t\t\t\t\t\t\t\t\u642d\u914d\u8d2d\t\t\t\t\t\t\t\t\t\t\t\u6211\u559c\u6b22\t\t\t\t\t\t\t\t\t\u4f01\u4e1a\u670d\u52a1\t\t\t\t\t\t\t\t\t\t\t\u4f01\u4e1a\u5ba2\u6237\t\t\t\t\t\t\t\t\t\t\t\u529e\u516c\u76f4\u901a\u8f66\t\t\t\t\t\t\t\t\t\u65d7\u4e0b\u7f51\u7ad9\t\t\t\t\t\t\t\t\t\t\tEnglish Site\t\t\t\t\t\t\t\u66f4\u591a\u5bfc\u822a\t\t\t\t\t\t\t\t\u670d\u88c5\u57ce\t\t\t\t\t\t\t\t\u98df\u54c1\t\t\t\t\t\t\t\t\u56e2\u8d2d\t\t\t\t\t\t\t\t\u593a\u5b9d\u5c9b\t\t\t\t\t\t\t\t\u95ea\u8d2d\t\t\t\t\t\t\t\t\u91d1\u878d\t\t\t\t\t\t\t\u70ed\u95e8\u641c\u7d22\uff1a\t\t\t\t\t\t\t\u51ac\u5b63\u8fde\u8863\u88d9\t\t\t\t\t\t\t\u8fd0\u52a8\u7fbd\u7ed2\u670d\t\t\t\t\t\t\t\u7bb1\u5305\t\t\t\t\t\t\t\u4fdd\u6696\u5185\u8863\t\t\t\t\t\t\t\u51b2\u950b\u8863\t\t\t\t\t\t\t\u7cbe\u54c1\u7537\u88c5\t\t\t\t\t\t\t\u7f51\u4e0a\u914d\u955c\t\t\t\t\t\t\t\u56f4\u5dfe\t\t\t\t\t\t\t\t\u6211\u7684\u4eac\u4e1c\t\t\t\t\t\t\t\t\t\u60a8\u597d\uff0c\u8bf7\t\t\t\t\t\t\t\t\t\t\u767b\u5f55\t\t\t\t\t\t\t\t\t\t\t\u5f85\u5904\u7406\u8ba2\u5355\t\t\t\t\t\t\t\t\t\t\t\u54a8\u8be2\u56de\u590d\t\t\t\t\t\t\t\t\t\t\t\u964d\u4ef7\u5546\u54c1\t\t\t\t\t\t\t\t\t\t\t\u8fd4\u4fee\u9000\u6362\u8d27\t\t\t\t\t\t\t\t\t\t\t\u4f18\u60e0\u5238\t\t\t\t\t\t\t\t\t\t\t\u6211\u7684\u5173\u6ce8\xa0>\t\t\t\t\t\t\t\t\t\t\t\u6211\u7684\u4eac\u8c46\xa0>\t\t\t\t\t\t\t\t\t\t\t\u6211\u7684\u7406\u8d22\xa0>\t\t\t\t\t\t\t\t\t\t\t\u6211\u7684\u767d\u6761\xa0>\t\t\t\t\t\t\t\t\t\t\t\u4eac\u4e1c\u91d1\u91c7\xa0>\t\t\t\t\t\t\t\t\t\t\u6700\u8fd1\u6d4f\u89c8\u7684\u5546\u54c1\uff1a\t\t\t\t\t\t\t\t\t\t\t\u67e5\u770b\u6d4f\u89c8\u5386\u53f2\xa0>\t\t\t\t\t\t\t\t\t14\t\t\t\t\t\t\t\t\u53bb\u8d2d\u7269\u8f66\u7ed3\u7b97\t\t\t\t\t\t\t\t\t\u8d2d\u7269\u8f66\u4e2d\u8fd8\u6ca1\u6709\u5546\u54c1\uff0c\u8d76\u7d27\u9009\u8d2d\u5427\uff01\t\t\t\t\t\t\t\u978b\u9774\t\t\t\t\t\t\xa0>\xa0\t\t\t\t\t\t\xa0>\xa0\t\t\t\t\t\t\tPlover\u5544\u6728\u9e1f \u771f\u76ae\u76ae\u978b \u5546\u52a1\u4f11\u95f2\u978b\u900f\u6c14\u7537\u58eb\u5934\u5c42\u725b\u76ae\u590f\u5b63..\t\t\t\t\t\t\t\t\t\u5546\u54c1\u7f16\u53f7\uff1a\t\t\t\t\t\t\t\t\t1635670097\t\t\t\t\t\t\t\t\t\u5173\u6ce8\u5546\u54c1\t\t\t\t\t\t\t\t\t\u5206\u4eab\t\t\t\t\t\t\t\t\tPlover\u5544\u6728\u9e1f \u771f\u76ae\u76ae\u978b \u5546\u52a1\u4f11\u95f2\u978b\u900f\u6c14\u7537\u58eb\u5934\u5c42\u725b\u76ae\u590f\u5b63\u8212\u9002\u5957\u811a\u8f6f\u5e95\u82f1\u4f26\u5a5a\u978b\u6b63\u88c5\u978b\u5b50 \u9ed1\u8272 40\t\t\t\t\t\t\t\t\t\t\u7d2f\u8ba1\u8bc4\u4ef7\t\t\t\t\t\t\t\t\t\t\u4eac \u4e1c \u4ef7\uff1a\t\t\t\t\t\t\t\t\t\t\t(\u964d\u4ef7\u901a\u77e5)\t\t\t\t\t\t\t\t\t\t\t\u4fc3\u9500\u4fe1\u606f\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u9879\u4fc3\u9500\t\t\t\t\t\t\t\t\t\t\u652f\u3000\u3000\u6301\uff1a\t\t\t\t\t\t\t\t\t\t\u914d \u9001 \u81f3\uff1a\t\t\t\t\t\t\t\t\t\t\u670d\u3000\u3000\u52a1\uff1a\t\t\t\t\t\t\t\t\t\t\u9009\u62e9\u989c\u8272\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\t\u9ed1\u8272\t\t\t\t\t\t\t\t\t\t\t\t\t\u68d5\u8272\t\t\t\t\t\t\t\t\t\t\u9009\u62e9\u5c3a\u7801\uff1a\t\t\t\t\t\t\t\t\t\t\t\t38\t\t\t\t\t\t\t\t\t\t\t\t39\t\t\t\t\t\t\t\t\t\t\t\t40\t\t\t\t\t\t\t\t\t\t\t\t41\t\t\t\t\t\t\t\t\t\t\t\t42\t\t\t\t\t\t\t\t\t\t\t\t43\t\t\t\t\t\t\t\t\t\t\t\t44\t\t\t\t\t\t\t\t\t\t\t\t\u76ae\u978b\u7801 \u6bd4\u8fd0\u52a8\u978b\u5927\u4e00\u7801\t\t\t\t\t\t\t\t\t\t\u5408\u7ea6\u5957\u9910\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\u9009\u62e9\u5957\u9910\u4e0e\u8d44\u8d39\t\t\t\t\t\t\t\t\t\t\t\t\u8bf7\u9009\u62e9\u5957\u9910\u5185\u5bb9\t\t\t\t\t\t\t\t\t\t\t\t\u91cd\u9009\t\t\t\t\t\t\t\t\t\u3000\u60a8\u9009\u62e9\u7684\u5730\u533a\u6682\u4e0d\u652f\u6301\u5408\u7ea6\u673a\u9500\u552e\uff01\t\t\t\t\t\t\t\t\t\t\u62a2\u8d2d\t\t\t\t\t\t\t\t\t\t\t\u9009\u4f5c\u793c\u7269\u8d2d\u4e70\t\t\t\t\t\t\t\t\t\t\u9009\u62e9\u53f7\u7801\u548c\u5957\u9910\t\t\t\t\t\t\t\t\t\t\t\u52a0\u5165\u8d2d\u7269\u8f66\t\t\t\t\t\t\t\t\t\t\u6253\u767d\u6761\t\t\t\t\t\t\t\t\t\t\t\u5230\u8d27\u901a\u77e5\t\t\t\t\t\t\t\t\t\t\u6e29\u99a8\u63d0\u793a\uff1a\t\t\t\t\t\t\t\t\u66f4\u591a\u5546\u54c1\u4fe1\u606f\t\t\t\t\t\t\t\t\t\u4e50\u54c1\u6c47\u978b\u9774\u4e13\u8425\u5e97\t\t\t\t\t\t\t\t\t\t\t\t\u7efc\u5408\u8bc4\u5206\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\t\u5206\t\t\t\t\t\t\t\t\t\t\t\t\u7ec6\u5219\u8bc4\u5206\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\t9.96\t\t\t\t\t\t\t\t\t\t\t\t\t9.68\t\t\t\t\t\t\t\t\t\t\t\t\t9.96\t\t\t\t\t\t\t\t\t\t\t\t\u7efc\u5408\u8bc4\u5206\t\t\t\t\t\t\t\t\t\t\t\t\u8bc4\u5206\u7ec6\u5219\t\t\t\t\t\t\t\t\t\t\t\t\u76f8\u6bd4\u884c\u4e1a\t\t\t\t\t\t\t\t\t\t\t\t\t9.8\t\t\t\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\t\t\t\t\t\t\t\t\t\t\t\t\t\t9.96\t\t\t\t\t\t\t\t\t\t\t\t\t\t70.7%\t\t\t\t\t\t\t\t\t\t\t\t\t\u670d\u52a1\t\t\t\t\t\t\t\t\t\t\t\t\t\t9.68\t\t\t\t\t\t\t\t\t\t\t\t\t\t9.80%\t\t\t\t\t\t\t\t\t\t\t\t\t\u65f6\u6548\t\t\t\t\t\t\t\t\t\t\t\t\t\t9.96\t\t\t\t\t\t\t\t\t\t\t\t\t\t55.6%\t\t\t\t\t\t\t\t\t\t\t\t\u516c\u53f8\u540d\u79f0\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\u8386\u7530\u5e02\u4e50\u54c1\u6c47\u8d38\u6613\u6709\u9650\u516c\u53f8\t\t\t\t\t\t\t\t\t\t\t\t\u6240 \u5728 \u5730\uff1a\t\t\t\t\t\t\t\t\t\t\t\t\u798f\u5efa \u8386\u7530\u5e02\t\t\t\t\t\t\t\t\t\u5728\u7ebf\u5ba2\u670d\uff1a\t\t\t\t\t\t\t\t\t\u8fdb\u5165\u5e97\u94fa\t\t\t\t\t\t\t\t\t\u5173\u6ce8\u5e97\u94fa\t\t\t\t\t\t\t\t\t\u670d\u52a1\u652f\u6301\uff1a\t\t\t\t\t\t\t\t\t\u63a8\u8350\u914d\u4ef6\t\t\t\t\t\t\t\t\t\u4f18\u60e0\u5957\u88c5\t\t\t\t\t\t\t\t\t\u6700\u4f73\u7ec4\u5408\t\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u4ecb\u7ecd\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u8bc4\u4ef7\t\t\t\t\t\t\t\t\t\t\t(0)\t\t\t\t\t\t\t\t\t\t\u552e\u540e\u4fdd\u969c\t\t\t\t\t\t\t\t\t\t\u4eac\u4e1c\u670d\u52a1\t\t\t\t\t\t\t\t\t\t\t\u52a0\u5165\u8d2d\u7269\u8f66\t\t\t\t\t\t\t\t\t\t\tPlover\u5544\u6728\u9e1f \u771f\u76ae\u76ae\u978b \u5546\u52a1\u4f11\u95f2\u978b\u900f\u6c14\u7537\u58eb\u5934\u5c42\u725b\u76ae\u590f\u5b63\u8212\u9002\u5957\u811a\u8f6f\u5e95\u82f1\u4f26\u5a5a\u978b\u6b63\u88c5\u978b\u5b50 \u9ed1\u8272 40\t\t\t\t\t\t\t\t\t\t\t\t\u4eac\u4e1c\u4ef7\uff1a\t\t\t\t\t\t\t\t\t\t\t\u5ba2\u6237\u7aef\u9996\u5355 \u6ee179\u900179\t\t\t\t\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u540d\u79f0\uff1aPlover\u5544\u6728\u9e1f \u771f\u76ae\u76ae\u978b \u5546\u52a1\u4f11\u95f2\u978b\u900f\u6c14\u7537\u58eb\u5934\u5c42\u725b\u76ae\u590f\u5b63\u8212\u9002\u5957\u811a\u8f6f\u5e95\u82f1\u4f26\u5a5a\u978b\u6b63\u88c5\u978b\u5b50 \u9ed1\u8272 40\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u7f16\u53f7\uff1a1635670097\t\t\t\t\t\t\t\t\t\t\u5e97\u94fa\uff1a\t\t\t\t\t\t\t\t\t\t\t\u4e50\u54c1\u6c47\u978b\u9774\u4e13\u8425\u5e97\t\t\t\t\t\t\t\t\t\t\u4e0a\u67b6\u65f6\u95f4\uff1a2015-07-14 17:59:42\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u6bdb\u91cd\uff1a1.25kg\t\t\t\t\t\t\t\t\t\t\u8d27\u53f7\uff1a8175\t\t\t\t\t\t\t\t\t\t\u5c3a\u7801\uff1a38\t\t\t\t\t\t\t\t\t\t\u9500\u552e\u6e20\u9053\u7c7b\u578b\uff1a\u7ebf\u4e0a\u9500\u552e\t\t\t\t\t\t\t\t\t\t\u98ce\u683c\uff1a\u82f1\u4f26\t\t\t\t\t\t\t\t\t\t\u978b\u9762\u6750\u6599\uff1a\u5934\u5c42\u725b\u76ae\t\t\t\t\t\t\t\t\t\t\u6d41\u884c\u5143\u7d20\uff1a\u8f66\u7f1d\u7ebf\t\t\t\t\t\t\t\t\t\t\u989c\u8272\uff1a\u9ed1\u8272\t\t\t\t\t\t\t\t\t\t\u76ae\u9769\u98ce\u683c\uff1a\u8f6f\u9762\u76ae\t\t\t\t\t\t\t\t\t\t\u4e0a\u5e02\u5e74\u4efd\u5b63\u8282\uff1a2015\u79cb\u5b63\t\t\t\t\t\t\t\t\t\t\u978b\u5e95\u6750\u8d28\uff1a\u6a61\u80f6\t\t\t\t\t\t\t\t\t\t\u95ed\u5408\u65b9\u5f0f\uff1a\u5957\u811a\t\t\t\t\t\t\t\t\t\t\u978b\u8ddf\uff1a\u6709\u8ddf\t\t\t\t\t\t\t\t\t\t\u529f\u80fd\uff1a\u8010\u78e8\t\t\t\t\t\t\t\t\t\t\u978b\u5934\u6b3e\u5f0f\uff1a\u5706\u5934\t\t\t\t\t\t\t\t\t\t\u91cc\u6599\u6750\u8d28\uff1a\u76ae\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t249\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u51ac\u5b63\u9ad8\u5e2e\u677f\u978b\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t268\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u6237\u5916\u4f11\u95f2\u76ae\u978b\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t268\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u65f6\u5c1a\u4fdd\u6696\u7537\u9774\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t199\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u65b0\u6b3e\u7cfb\u5e26\u7537\u978b\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t249\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u6b63\u88c5\u9632\u6ed1\u76ae\u978b\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t278\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\u8f6f\u5e95\u8212\u9002\u6b63\u88c5\u978b\t\t\t\t\t\t\t\t\t\t\u5982\u679c\u60a8\u53d1\u73b0\u5546\u54c1\u4fe1\u606f\u4e0d\u51c6\u786e\uff0c\t\t\t\t\t\t\t\t\t\t\t\u6b22\u8fce\u7ea0\u9519\t\t\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u4ecb\u7ecd\u52a0\u8f7d\u4e2d...\t\t\t\t\t\t\u6ce8\uff1a\u56e0\u5382\u5bb6\u4f1a\u5728\u6ca1\u6709\u4efb\u4f55\u63d0\u524d\u901a\u77e5\u7684\u60c5\u51b5\u4e0b\u66f4\u6539\u4ea7\u54c1\u5305\u88c5\u3001\u4ea7\u5730\u6216\u8005\u4e00\u4e9b\u9644\u4ef6\uff0c\u672c\u53f8\u4e0d\u80fd\u786e\u4fdd\u5ba2\u6237\u6536\u5230\u7684\u8d27\u7269\u4e0e\u5546\u57ce\u56fe\u7247\u3001\u4ea7\u5730\u3001\u9644\u4ef6\u8bf4\u660e\u5b8c\u5168\u4e00\u81f4\u3002\u53ea\u80fd\u786e\u4fdd\u4e3a\u539f\u5382\u6b63\u8d27\uff01\u5e76\u4e14\u4fdd\u8bc1\u4e0e\u5f53\u65f6\u5e02\u573a\u4e0a\u540c\u6837\u4e3b\u6d41\u65b0\u54c1\u4e00\u81f4\u3002\u82e5\u672c\u5546\u57ce\u6ca1\u6709\u53ca\u65f6\u66f4\u65b0\uff0c\u8bf7\u5927\u5bb6\u8c05\u89e3\uff01\t\t\t\t\t\t\u4eac\u4e1c\u4e0a\u7684\u6240\u6709\u5546\u54c1\u4fe1\u606f\u3001\u5ba2\u6237\u8bc4\u4ef7\u3001\u5546\u54c1\u54a8\u8be2\u3001\u7f51\u53cb\u8ba8\u8bba\u7b49\u5185\u5bb9\uff0c\u662f\u4eac\u4e1c\u91cd\u8981\u7684\u7ecf\u8425\u8d44\u6e90\uff0c\u672a\u7ecf\u8bb8\u53ef\uff0c\u7981\u6b62\u975e\u6cd5\u8f6c\u8f7d\u4f7f\u7528\u3002\t\t\t\t\t\t\t\u672c\u7ad9\u5546\u54c1\u4fe1\u606f\u5747\u6765\u81ea\u4e8e\u5408\u4f5c\u65b9\uff0c\u5176\u771f\u5b9e\u6027\u3001\u51c6\u786e\u6027\u548c\u5408\u6cd5\u6027\u7531\u4fe1\u606f\u62e5\u6709\u8005\uff08\u5408\u4f5c\u65b9\uff09\u8d1f\u8d23\u3002\u672c\u7ad9\u4e0d\u63d0\u4f9b\u4efb\u4f55\u4fdd\u8bc1\uff0c\u5e76\u4e0d\u627f\u62c5\u4efb\u4f55\u6cd5\u5f8b\u8d23\u4efb\u3002\t\t\t\t\t\t\t\u5370\u5237\u7248\u6b21\u4e0d\u540c\uff0c\u5370\u5237\u65f6\u95f4\u548c\u7248\u6b21\u4ee5\u5b9e\u7269\u4e3a\u51c6\u3002\t\t\t\t\t\t\t\u5546\u54c1\u8bc4\u4ef7\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\t\t\t\u5168\u90e8\u8bc4\u4ef7\t\t\t\t\t\t\t\t\t\t\t()\t\t\t\t\t\t\t\t\t\t\u597d\u8bc4\t\t\t\t\t\t\t\t\t\t\t()\t\t\t\t\t\t\t\t\t\t\u4e2d\u8bc4\t\t\t\t\t\t\t\t\t\t\t()\t\t\t\t\t\t\t\t\t\t\u5dee\u8bc4\t\t\t\t\t\t\t\t\t\t\t()\t\t\t\t\t\t\t\t\t\t\u6709\u56fe\u7247\u7684\u8bc4\u4ef7\t\t\t\t\t\t\t\t\t\t\t()\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\t\t\t\u5168\u90e8\u8d2d\u4e70\u54a8\u8be2\t\t\t\t\t\t\t\t\t\t\u5546\u54c1\u54a8\u8be2\t\t\t\t\t\t\t\t\t\t\u5e93\u5b58\u914d\u9001\t\t\t\t\t\t\t\t\t\t\u652f\u4ed8\t\t\t\t\t\t\t\t\t\t\u53d1\u7968\u4fdd\u4fee\t\t\t\t\t\t\t\t\t\t\u53d6\u6d88\t\t\t\t\t\t\t\u56e0\u5382\u5bb6\u66f4\u6539\u4ea7\u54c1\u5305\u88c5\u3001\u4ea7\u5730\u6216\u8005\u66f4\u6362\u968f\u673a\u9644\u4ef6\u7b49\u6ca1\u6709\u4efb\u4f55\u63d0\u524d\u901a\u77e5\uff0c\u4e14\u6bcf\u4f4d\u54a8\u8be2\u8005\u8d2d\u4e70\u60c5\u51b5\u3001\u63d0\u95ee\u65f6\u95f4\u7b49\u4e0d\u540c\uff0c\u4e3a\u6b64\u4ee5\u4e0b\u56de\u590d\u4ec5\u5bf9\u63d0\u95ee\u80053\u5929\u5185\u6709\u6548\uff0c\u5176\u4ed6\u7f51\u53cb\u4ec5\u4f9b\u53c2\u8003\uff01\u82e5\u7531\u6b64\u7ed9\u60a8\u5e26\u6765\u4e0d\u4fbf\u8bf7\u591a\u591a\u8c05\u89e3\uff0c\u8c22\u8c22\uff01\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\u9500\u552e\u8054\u76df\t\t\t\t\t\t\u4eac\u4e1c\u516c\u76ca\t\t\t\t\t\t\u53cb\u60c5\u94fe\u63a5\t\t\t\t\t\t\t\t\t\u6d3e\u5199\u9e4f\u4ef6\t\t\t\t\t\t\t\t\t(\u5317\u4eac)\t\t\t\t\t\t\t\t\t2015-11-23\t\t\t\t\t\t\t\t\t\t\t\u8d28\u91cf\u4e0d\u9519\uff0c\u505a\u5de5..\t\t\t\t\t\t\t\t\t\t2015-11-23 19:10:50\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u8d28\u91cf\u4e0d\u9519\uff0c\u505a\u5de5..\t\t\t\t\t\t\t\t\t\u83c1\u9999\u5bfb\u5ffb\t\t\t\t\t\t\t\t\t(\u6e56\u5317)\t\t\t\t\t\t\t\t\t2015-11-23\t\t\t\t\t\t\t\t\t\t\t\u5c3a\u7801\u521a\u5408\u811a\uff0c\u6837..\t\t\t\t\t\t\t\t\t\t2015-11-23 19:06:37\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u5c3a\u7801\u521a\u5408\u811a\uff0c\u6837..\t\t\t\t\t\t\t\t\t\u8a00\u9999\u99a8\t\t\t\t\t\t\t\t\t(\u6d59\u6c5f)\t\t\t\t\t\t\t\t\t2015-11-23\t\t\t\t\t\t\t\t\t\t\t\u978b\u5b50\u8d28\u91cf\u5f88\u597d\uff0c..\t\t\t\t\t\t\t\t\t\t2015-11-23 19:02:09\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u978b\u5b50\u8d28\u91cf\u5f88\u597d\uff0c..\t\t\t\t\t\t\t\t\t\u7434\u56e0\u5415\u9edb\t\t\t\t\t\t\t\t\t(\u5317\u4eac)\t\t\t\t\t\t\t\t\t2015-11-23\t\t\t\t\t\t\t\t\t\t\t\u7269\u6d41\u5f88\u5feb\u3002\u5305\u88c5..\t\t\t\t\t\t\t\t\t\t2015-11-23 18:59:47\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u7269\u6d41\u5f88\u5feb\u3002\u5305\u88c5..\t\t\t\t\t\t\t\t\t\u79f0\u658c\u7ef4\u67e5\t\t\t\t\t\t\t\t\t(\u5b89\u5fbd)\t\t\t\t\t\t\t\t\t2015-11-23\t\t\t\t\t\t\t\t\t\t\t\u978b\u5b50\u6536\u5230\u4e86\uff0c\u8bd5..\t\t\t\t\t\t\t\t\t\t2015-11-23 18:57:23\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u978b\u5b50\u6536\u5230\u4e86\uff0c\u8bd5..\t\t\t\t\t\t\t\t\tkefkke1082\t\t\t\t\t\t\t\t\t(\u5b89\u5fbd)\t\t\t\t\t\t\t\t\t2015-11-23\t\t\t\t\t\t\t\t\t\t\t\u978b\u5b50\u6536\u5230\u4e86\uff0c\u8bd5..\t\t\t\t\t\t\t\t\t\t2015-11-23 18:49:50\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u978b\u5b50\u6536\u5230\u4e86\uff0c\u8bd5..\t\t\t\t\t\t\t\t\tkuikui72863\t\t\t\t\t\t\t\t\t(\u5e7f\u4e1c)\t\t\t\t\t\t\t\t\t2015-11-22\t\t\t\t\t\t\t\t\t\t\t\u978b\u5b50\uff0c\u6536\u5230\u4e86\uff0c..\t\t\t\t\t\t\t\t\t\t2015-11-22 19:41:24\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u978b\u5b50\uff0c\u6536\u5230\u4e86\uff0c..\t\t\t\t\t\t\t\t\tlangnhr368791\t\t\t\t\t\t\t\t\t(\u5e7f\u4e1c)\t\t\t\t\t\t\t\t\t2015-11-22\t\t\t\t\t\t\t\t\t\t\t\u978b\u5b50\u8fd8\u662f\u5934\u4e00\u6b21..\t\t\t\t\t\t\t\t\t\t2015-11-22 19:37:13\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u978b\u5b50\u8fd8\u662f\u5934\u4e00\u6b21..\t\t\t\t\t\t\t\t\tntmcai3806\t\t\t\t\t\t\t\t\t(\u56db\u5ddd)\t\t\t\t\t\t\t\t\t2015-11-22\t\t\t\t\t\t\t\t\t\t\t\u978b\u5b50\u9001\u7ed9\u8001\u516c\u7684..\t\t\t\t\t\t\t\t\t\t2015-11-22 19:32:54\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u978b\u5b50\u9001\u7ed9\u8001\u516c\u7684..\t\t\t\t\t\t\t\t\tdanddan322333\t\t\t\t\t\t\t\t\t(\u6d59\u6c5f)\t\t\t\t\t\t\t\t\t2015-11-21\t\t\t\t\t\t\t\t\t\t\t\u4eca\u5929\u770b\u5230\u54e5\u54e5\u5f88..\t\t\t\t\t\t\t\t\t\t2015-11-21 19:42:17\t\t\t\t\t\t\t\t\t\u4f7f\u7528\u5fc3\u5f97\uff1a\u4eca\u5929\u770b\u5230\u54e5\u54e5\u5f88..\t\t\t\t\t\t\t\t\t\t\u70ed\u95e8\u8d34\u5b50\t\t\t\t\t\t\t\t\t\t\u7f51\u53cb\u8ba8\u8bba\u5708\t\t\t\t\t\t\t\t\t\t\u6652\u5355\u8d34\t\t\t\t\t\t\t\t\t\t\u8ba8\u8bba\u8d34\t\t\t\t\t\t\t\t\t\t\u95ee\u7b54\u8d34\t\t\t\t\t\t\t\t\t\t\u5708\u5b50\u8d34\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u6d4f\u89c8\u4e86\u8be5\u5546\u54c1\u7684\u7528\u6237\u8fd8\u6d4f\u89c8\u4e86\t\t\t\t\t\t\t\t\u52a0\u8f7d\u4e2d\uff0c\u8bf7\u7a0d\u5019...\t\t\t\t\t\t\t\u5e97\u5185\u641c\u7d22\t\t\t\t\t\t\t\t\u5173\u952e\u5b57\uff1a\t\t\t\t\t\t\t\t\u4ef7\u3000\u683c\uff1a\t\t\t\t\t\t\t\t\u5230\t\t\t\t\t\t\t\t\u3000\u3000\u3000\t\t\t\t\t\t\t\u5e97\u957f\u63a8\u8350\t\t\t\t\t\t\t\t\t\t\u5544\u6728\u9e1f(PLOVER)\u65b0\u6b3e\u65f6\u5c1a\u7537\u978b \u53cd\u7ed2\u76ae\u82f1\u4f26\u4f11\u95f2\u978b\u65f6\u5c1a\u677f\u978b\u7cfb\u5e26\u900f\u6c14\u6f6e\u6d41\u78e8\u7802\u5de5\u88c5\u978b\u6237\u5916\u978b\u5b50 \u84dd\u8272 38\t\t\t\t\t\t\t\t\t\t\u5544\u6728\u9e1f\u7537\u978b \u65b0\u6b3e\u7537\u58eb\u5546\u52a1\u4f11\u95f2\u978b\u97e9\u7248\u771f\u76ae\u7cfb\u5e26\u65f6\u5c1a\u677f\u978b \u82f1\u4f26\u6237\u5916\u7537\u58eb\u6f6e\u6d41\u4f4e\u5e2e\u61d2\u4eba\u978b\u5934\u5c42\u725b\u76ae\u978b \u767d\u8272 38\t\t\t\t\t\t\t\t\t\t\u5544\u6728\u9e1fPlover\u7537\u978b \u65b0\u6b3e\u590f\u5b63\u6237\u5916\u4f11\u95f2\u978b\u8fd0\u52a8\u978b\u900f\u6c14\u6f6e\u6d41\u7537\u58eb\u5355\u978b\u82f1\u4f26\u65f6\u5c1a\u767e\u642d\u97e9\u7248\u53cd\u7ed2\u76ae\u677f\u978b \u68d5\u8272 38\t\t\t\t\t\t\t\t\t\tPlover\u5544\u6728\u9e1f \u76ae\u978b \u5546\u52a1\u4f11\u95f2\u978b\u900f\u6c14\u7537\u58eb\u5934\u5c42\u725b\u76ae\u590f\u5b63\u8212\u9002\u5957\u811a\u8f6f\u5e95\u771f\u76ae\u82f1\u4f26\u5a5a\u978b\u6b63\u88c5\u978b\u5b50 \u9ed1\u8272 38\t\t\t\t\t\t\t\t\t\tPlover\u5544\u6728\u9e1f \u7537\u978b2015\u590f\u5b63\u65b0\u6b3e\u4f11\u95f2\u978b\u900f\u6c14\u6237\u5916\u9632\u6ed1\u677f\u978b \u7537\u58eb\u97e9\u7248\u65c5\u6e38\u978b\u9a7e\u8f66\u978b\u6f6e\u978b \u84dd\u8272 38\t\t\t\t\t\t\t\t\t\t\u5544\u6728\u9e1fPlover \u7537\u978b2015\u590f\u5b63\u65b0\u6b3e \u4f11\u95f2\u978b \u7537\u58eb\u82f1\u4f26\u65f6\u5c1a\u97e9\u7248\u677f\u978b \u6f6e\u6d41\u65e5\u5e38\u4f11\u95f2\u978b\u5b50 \u6df1\u84dd\u8272 38'} 1, key url 2, key type <type 'unicode'> url http://item.jd.com/1635670097.html 1, key _id 2, key type <class 'bson.objectid.ObjectId'> 1, key extracted_text 2, key type <type 'unicode'> Traceback (most recent call last): File "query.py", line 16, in <module> print key +"\t"+ page[key].encode('gbk', 'ignore') UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 9: ordinal not in range(128) Answer: It is because the 'key' is unicode, you may try: print key.encode('gbk', 'ignore') +"\t"+ page[key].encode('gbk', 'ignore')