w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PYTHON » Page 5
Pylab plot shows no plot points
It appears you want to plot one point at the time. Don't do that: collect all the data into an array (from the logfile), then plot that all at once. So, do all the plotting outside your for loop: import matplotlib.pylab as pylab logfile = file('sensorlog.txt','r') pylab.figure(1) pylab.xlabel('Time Steps') pylab.ylabel('Fan Temperature') temperatures = [] for line in logfile: if line[0].isdi

Categories : Python

Python: Run windows CMD commands through python, using å,ä and ö
I could do some tests on a windows 7 system. The problem is not on the execution of a command but only on the display of UTF-8 characters. First, it works almost correctly using Python 3.4 : it can display ä without problems. So I assume you are using a 2.x version. On a 2.x version, it is almost impossible to have proper display of UTF8 strings. If you manage to do it correctly, the driver wil

Categories : Python

Selenium phantomjs does not work for twitter.com
PhantomJS 1.9.8 does the work for twitter. New version available here: http://phantomjs.org/download.html Previously I used the older version of the PhantomJS: 1.9.7.

Categories : Python

python etree with xpath and namespaces with prefix
Oh, I found it. After we do that: dom = ET.parse(u'C:\filepath\1.xml') rootxml = dom.getroot() Object rootxml contains dictionary nsmap, which contains all namespaces that I want. So, simplest solution I've found: dom = ET.parse(u'C:\filepath\1.xml') rootxml = dom.getroot() nss = rootxml.nsmap for subtag in rootxml.xpath(u'//par:actual', namespaces=nss): #do something print(subtag)

Categories : Python

MongoEngine: storing EmbeddedDocument in DictField
I finally found the answer to my problem. The correct way to achieve this pattern is by making use of a MapField. The corresponding model in MongoEngine looks like: class Inner(EmbeddedDocument): name = StringField() class Outer(Document): outer_data = StringField() embed = MapField(EmbeddedDocumentField(Inner)) In MongoDB, all keys needs to be strings so there is no need to specify a "

Categories : Python

Why does the value of a variable changes on appending to python list as a list?
The number stored is the same in both cases. The only difference is what is being printed. Consider this: >>> a=1.234567890123456789 >>> print a 1.23456789012 >>> print [a] [1.2345678901234567] In the first case, the equivalent of str(a) is invoked, which does not show the full precision. In the second case, repr(a) is used.

Categories : Python

Numpy sum every n columns of matrix
Here's one way; first reshape x to a 3D array and then sum over the last axis: >>> x.reshape(-1, 4, 3).sum(axis=2) array([[ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30]])

Categories : Python

How to increase paramiko performance
You can check the exit status of the command - no need to use time.sleep. One possible solution: first, define a function to connect to the ssh server: def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return c

Categories : Python

python doc to docx conversion, comtypes.Documents.Open throwing ValueError: NULL COM pointer access
If you are still having this issue, this is what helped me for exactly the same layout of AWS(Win2012)-Apache(64bit)-Django: Change the DCOM Config Settings: Start -> dcomcnfg.exe Computers -> My Computer DCOM Config Select the Microsoft Word 97-2003 Documents -> Properties Tab Identity, change from Launching User to Interactive User

Categories : Python

cursor.execute in python for SQL
Explicitly cast the LOGINPROPERTY return value to an integer to work around the data type mapping problem by changing the query from this: "select loginproperty('tibbr_db','DaysUntilExpiration')" to this: "select cast(loginproperty('tibbr_db','DaysUntilExpiration') as integer)" The DaysUntilExpiration property in SQL Server should always return an integer, so you won't see any type errors wi

Categories : Python

Instancing a Table from __tablename__ in SQLAlchemy
Create_a.py import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class A(Base): __tablename__ = 'X' A_id = Column(Integer, primary_key=True) A_name = Column(String(250), nullable=False) engine = cre

Categories : Python

What are the best ways to have a python program and c program share data
I would consider using nanomsg for this. http://nanomsg.org/ It's a simple-to use C-only IPC library, with good python bindings also available. Alternatively, use it's older, but also awesome ZeroMQ if you like. Last but not least, while multiprocess-approaches are a good thing (tm), you could consider using ctypes and build a python wrapper around it. The advantage of this approach is that yo

Categories : Python

Numpy: Extract particular rows in matrix
If you are willing to use a list comprehension to generate the indexes, then you can use: w[np.array([np.arange(i,j) for i,j in np.hstack((y1,y2))]).ravel()] If you really can't use loops, try: a = np.hstack((y1,y2)) func = lambda i: np.arange(a[i][0],a[i][1]) b = np.vectorize(func,otypes=[np.ndarray]) w[np.hstack(b(np.arange(4)))]

Categories : Python

Django-taggit adding new tags to an object?
django-taggit does exactly what you want, but in your case sampletag != Sample_tag so another Tag instnace is created. >>> i.tags.all() [] >>> i.tags.add("test") >>> i.tags.all() [<Tag: test>] >>> i.tags.add("test") >>> i.tags.all() [<Tag: test>] >>>

Categories : Python

Trying to use the Pillow library to create a gif‏
I guess this is the problem: s = list(s) You may think that s is global variable, but for python s is local variable, due to assignment. To make s global do: def main(im): global s ... Also you are catching all exceptions, so probably you are not getting any errors. If you really insist on the catching just do the following for now: except Exception as inst: raise(inst) This s

Categories : Python

Rails app to work with a remote heroku database
I don't see any problem in doing this, as far as rails manages the database structure and python script populates it with data. My advice, but just to make it simpler, is to define the database schema through migrations in your rails app and build it like the python script doesn't exist. Once you have completed it, simply start the python script so it can start populating the Database (could be ne

Categories : Python

Python: No Traceback when Scraping Data into Excel Spreadsheet
If there is no traceback then there is no error. Most likely something has gone wrong with your scraping/parsing code and your raw_list or other arrays aren't populated. Try print out the data that should be written to the worksheet in the last loop to see if there is any data to be written. If you aren't writing data to the worksheet then it will be empty.

Categories : Python

if not line.startswith - give to much single quotes and line bracks
Simply change your code like below. You don't need to go for a replace function. for r in log: host_line = "'",r['host'],"'" for line in host_line: if not line.startswith("178.255.20.20"): if not line == "'": print line.strip()

Categories : Python

element tree parse xml text string to be called by eval
You probably shouldn't use eval... But to answer your question on how to store an object to be later executed but eval, you do repr(my_object), this will often return a string, suitable for eval, but this is not always true.

Categories : Python

Django Unit Test Assert Database Transaction is Active
We managed to achieve this by adding the following function to the test class. def assert_inside_atomic_block(self, using=None): """ Returns a function that will assert we are inside an atomic transaction block. The purpose of this is to allow us to inject this assertion inside methods where we want to verify that a transaction is active. Does not work with django.db.TransactionT

Categories : Python

Retrieve data from mongodb based on date condition in pymongo
Haven't run your codes. Seems: self.stDate = datetime.datetime.now() self.endDate = datetime.datetime.now() - datetime.timedelta(days=1000) Should be: self.stDate = datetime.datetime.now() - datetime.timedelta(days=1000) self.endDate = datetime.datetime.now()

Categories : Python

How to parse json in my view from a requests post
In your code, the incoming request has already been converted to a QueryDict, it is not a json string which is why json.loads cannot do anything with it. The reason its a QueryDict is because you passed the dictionary to requests.post and it correctly posted it as part of the request body as form-encoded data. As its a QueryDict object, you can access it just like a Python dictionary: request.P

Categories : Python

Finding row wise average and average of all rows of space delimited file
Below code does the task mentioned: def rowAverageSum(filename): import numpy as np FullMean = 0 li = [map(int, x) for x in [i.strip().split() for i in open(filename).readlines()]] i=0 while i<len(li): for k in li: print "Mean of row ",i+1,":",np.mean(k) FullMean+=np.mean(k) i+=1 print "***************************" print "

Categories : Python

Add cylinder to plot
One possible method is to use the plot_surface. Adapting the solution given in this blog post then have import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Scatter graph N = 100 X = np.random.uniform(-1, 1, N) Y = np.random.uniform(-1, 1, N) Z = np.random.uniform(-2, 2, N) ax.scatter(X, Y, Z)

Categories : Python

IndexError: list index out of range when selecte values in openerp
Odedra is right, but I would like to point out two things: be aware that using field name as many2one might cause a lot of trouble - name in odoo is considered as a main field to filter with. when you do onchange for many2one field, you will not get a value, which can be searched with - use _logger.warn(name) to see, what value did you get - you will get an id instead of a name (just checked tha

Categories : Python

How to get full url from django request
You can use: request.build_absolute_uri() https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.build_absolute_uri

Categories : Python

Handling post data with requests in python
The requests lib already encodes your dictionaries. But if you wanna do it yourself, you should use a string. For a dict try this: postdata={ 'token':token, 'arg1':'', 'arg2':'', 'name[user]': user, # I think this should be : instead of , 'name[password]':password, 'arg3': 'Sign in'} headers={ 'Content-Type': 'application/x-www-form-urlencoded' # With this header

Categories : Python

From Arduino C to Raspberry pi python - volatile variable access inside thread
No, there's no such thing as volatile in Python, it's a much too low-level concept. You should just make sure there is some shared context (like an object instance) in which the variable can reside, so that it can be shared between the two contexts. Python will do the rest. class MyApp(object): def __init__(self): self._counter = 0 registerInterrupt(self.interruptHandler) def interr

Categories : Python

Pyinstaller error Can't perform this operation for unregistered loader type (MacOS)
I had similar problems and this is how I made it work. You need not use Foundation as its making the problem with Pyinstaller (Not sure why this is causing an issue) and is not used elsewhere in your code. import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init

Categories : Python

Django 1.7.1 requires a Default value for field - but no entry is in database. Why?
The migrations system is designed so that a single migration can be applied to more than one database. For example, you could have a development version, a staging version, and one or more production versions. That's why making the migration is a distinct step from applying the migration, and why makemgirations can't just look at the currently active database to see that it doesn't have any rows.

Categories : Python

How can I use my .conll file from nlp parser for feature selection
The output of a parser in the CoNLL-X format provides a separate column for the part-of-speech tags. For example, if you parse the sentence "I want to select adjectives only, and disregard other tags." the output might be as follows: 1 I _ PRP PRP _ 2 nsubj _ _ 2 want _ VB VBP _ 0 null _ _ 3 to _ TO TO _ 4 aux _ _ 4 select

Categories : Python

Adding newly created variables into existing dataframe in Python Pandas
To create new columns in a data frame you can just assign a series in the same way you would assign some data a variable name: with an equals sign. The following assumes that the CSV file has a header called 'Name' and that Name never can be split more than once i.e there are no middle names. The function simply created a data frame by reading the csv file, then creates two series objects of low

Categories : Python

Using 2d array to create clickable TKinter canvas
Try looping through the list, and with each entry bind the Button-1 event to the canvas object, so: self.board = list([list(range(5)), list(range(5)), list(range(5)), list(range(5)), list(range(5))]) for x in range(0, 5, 1): for y in range(0, 5, 1): self.board[x][y] = Canvas(<your settings>) self.board[x][y].grid(row = x, column = y) self.board[x][y].bind('<

Categories : Python

Write to the end of a binary file
As documented, opening in 'w' mode truncates the file (i.e., erases its existing contents). Try opening it in 'r+b' mode. Also, as described here (although admittedly not with total clarity), seeks relative to the end of the file still use positive numbers meaning "forward" and negative meaning "backward" (i.e., towards the beginning of the file). You are seeking past the end of the file. Use

Categories : Python

Pandas DataFrame row wise comparison
(df.label_x == df.label_y).value_counts() Many ways to to that, including the above... In [43]: (df.label_x == df.label_y).value_counts() Out[43]: True 4 False 1 dtype: int64

Categories : Python

Python Scrapy - Scrapping data from multiple website URLs
This is called a Broad Crawling and, generally speaking, this is not an easy thing to implement because of the different nature, representation, loading mechanisms web-sites use. The general idea would be to have a generic spider and some sort of a site-specific configuration where you would have a mapping between item fields and xpath expressions or CSS selectors used to retrieve the field value

Categories : Python

How to get 'My Document' folder path by python?
Now I found I should use the argument shellcon.CSIDL_PERSONAL instead of shellcon.CSIDL_MYDOCUMENTS . But I don't know why. On MSDN the function is said to be deprecated, but it still in pywin32 and I could not found the alternative function SHGetKnownFolderPath. Further more,CSIDL is also been replaced by KNOWNFOLDERID values, and in CSIDL document CSIDL_PERSONAL is equal to CSIDL_MYDOCUMENTS.

Categories : Python

How to download attachment from OERP using oerplib
After digging through Open ERP docs, I found out that attachments are saved as base64 encoded strings in DB unless the document addon is set up. So for anyone else who may find themselves stuck just read the data from datas property of the attachment resource object attachment_obj = oerp.browse('ir.attachment', 17) attachment_data = attachment_obj.datas

Categories : Python

Twisted server information
There are no pre-existing tools for doing this kind of analysis. There is ongoing work to make analysis of Twisted logfiles easier, but it is not done yet.

Categories : Python




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.