Search Results

Search found 13693 results on 548 pages for 'python metaprogramming'.

Page 133/548 | < Previous Page | 129 130 131 132 133 134 135 136 137 138 139 140  | Next Page >

  • python union of 2 nested lists with index

    - by sbas
    I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want is to find all sublists in B where the first 3 elements are equal to a sublist in A. In this example I want to get B[0] returned ([1,2,3,4]) because its first three elements are equal to A[0]. In addition, I also want the index to A[0] in this example, that is I[0]. I tried different things, but nothing worked so far :( First I tried this: Common = [] for i in range(len(B)): if B[i][:3] in A: id = [I[x] for x,y in enumerate(A) if y == B[i][:3]][0] ctdCommon.append([int(id)] + B[i]) But that takes ages, or never finishes Then I transformed A and B into sets and took the union from both, which was very quick, but then I don't know how to get the corresponding indices Does anyone have an idea?

    Read the article

  • Clever way of building a tag cloud? - Python

    - by RadiantHex
    Hi folks, I've built a content aggregator and would like to add a tag cloud representing the current trends. Unfortunately this is quite complex, as I have to look for keywords that represent the context of each article. For example words such as I, was, the, amazing, nice have no relation to context. Help would be much appreciated! :)

    Read the article

  • Python beautifulsoup trying to remove html tags 'span'

    - by Michelle Jun Lee
    I am trying to remove [<span class="street-address"> 510 E Airline Way </span>] and I have used this clean function to remove the one that is in between < > def clean(val): if type(val) is not StringType: val = str(val) val = re.sub(r'<.*?>', '',val) val = re.sub("\s+" , " ", val) return val.strip() and it produces [ 510 E Airline Way ]` i am trying to add within "clean" function to remove the char '[' and ']' and basically i just want to get the "510 E Airline Way". anyone has any clue what can i add to clean function? thank you

    Read the article

  • IECore - installation in maya python

    - by knishua
    I have downloaded IECore from this link http://code.google.com/p/cortex-vfx/ Following page suggests how to run it. http://code.google.com/p/cortex-vfx/wiki/DomeBuilderExample At this point error occurs saying No module named _IECore No module named _IECoreMaya import IECore < --------------- import IECoreMaya import maya.cmds How is it possible to get a positive output when running it. Brgds, kNish , Ashok

    Read the article

  • Advanced Python list comprehension

    - by Yuval A
    Given two lists: chars = ['ab', 'bc', 'ca'] words = ['abc', 'bca', 'dac', 'dbc', 'cba'] how can you use list comprehensions to generate a filtered list of words by the following condition: given that each word is of length n and chars is of length n as well, the filtered list should include only words that each i-th character is in the i string in words. In this case, we should get ['abc', 'bca'] as a result. (If this looks familiar to anyone, this was one of the questions in the previous Google code jam)

    Read the article

  • Python: Inheritance of a class attribute (list)

    - by Sano98
    Hi everyone, inheriting a class attribute from a super class and later changing the value for the subclass works fine: class Unit(object): value = 10 class Archer(Unit): pass print Unit.value print Archer.value Archer.value = 5 print Unit.value print Archer.value leads to the output: 10 10 10 5 which is just fine: Archer inherits the value from Unit, but when I change Archer's value, Unit's value remains untouched. Now, if the inherited value is a list, the shallow copy effect strikes and the value of the superclass is also affected: class Unit(object): listvalue = [10] class Archer(Unit): pass print Unit.listvalue print Archer.listvalue Archer.listvalue[0] = 5 print Unit.listvalue print Archer.listvalue Output: 10 10 5 5 Is there a way to "deep copy" a list when inheriting it from the super class? Many thanks Sano

    Read the article

  • Python Fabric error

    - by jwesonga
    I'm running fabric (Django deployment to apache) and everything seems to work fine until I get to the task for installing the site: def install_site(): "Add the virtualhost file to apache" require('release', provided_by=[deploy, setup]) sudo('cd %(path)/releases/%(release)/%(release); cp %(project_name)/%(virtualhost_path)/%(project_domain) /etc/apache2/sites-available/%(project_domain)s') sudo('cd /etc/apache2/sites-available; a2ensite %(project_domain)') I keep getting this error: [173.203.124.16] sudo: cd %(path)/releases/%(release)/%(release); [173.203.124.16] err: /bin/bash: -c: line 0: syntax error near unexpected token `(' [173.203.124.16] err: /bin/bash: -c: line 0: `cd %(path)/releases/%(release)/%(r elease);' Warning: sudo() encountered an error (return code 2) while executing 'cd %(path) /releases/%(release)/%(release);' I've gone through the fabfile.py over and over and I can't see why the error is coming...any ideas?

    Read the article

  • Specifying formatting for csv.writer in Python

    - by user248237
    I am using csv.DictWriter to output csv files from a set of dictionaries. I use the following function: def dictlist2file(dictrows, filename, fieldnames, delimiter='\t', lineterminator='\n'): out_f = open(filename, 'w') # Write out header header = delimiter.join(fieldnames) + lineterminator out_f.write(header) # Write out dictionary data = csv.DictWriter(out_f, fieldnames, delimiter=delimiter, lineterminator=lineterminator) data.writerows(dictrows) out_f.close() where dictrows is a list of dictionaries, and fieldnames provides the headers that should be serialized to file. Some of the values in my dictionary list (dictrows) are numeric -- e.g. floats, and I'd like to specify the formatting of these. For example, I might want floats to be serialized with "%.2f" rather than full precision. Ideally, I'd like to specify some kind of mapping that says how to format each type, e.g. {float: "%.2f"} that says that if you see a float, format it with %.2f. Is there an easy way to do this? I don't want to subclass DictWriter or anything complicated like that -- this seems like very generic functionality. How can this be done? The only other solution I can think of is: instead of messing with the formatting of DictWriter, just use the decimal package to specify the decimal precision of floats to be %.2 which will cause to be serialized as such. Don't know if this is a better solution? thanks very much for your help.

    Read the article

  • Google Appengine and Python exceptions

    - by Jim
    In my Google Appengine application I have defined a custom exception InvalidUrlException(Exception) in the module 'gvu'. Somewhere in my code I do: try: results = gvu.article_parser.parse(source_url) except gvu.InvalidUrlException as e: self.redirect('/home?message='+str(e)) ... which works fine in the local GAE development server, but raises <type 'exceptions.SyntaxError'>: invalid syntax (translator.py, line 18) when I upload it. (line 18 is the line starting with 'except') The problem seems to come from the 'as e' part: if I remove it I don't get this exception anymore. However I would like to be able to access the raised exception. Have you ever encountered this issue? Is there an alternative syntax?

    Read the article

  • STFT and ISTFT in Python

    - by endolith
    Is there any form of short-time Fourier transform with corresponding inverse transform built into SciPy or NumPy or whatever? There's the pyplot specgram function in matplotlib, which calls ax.specgram(), which calls mlab.specgram(), which calls _spectral_helper(): #The checks for if y is x are so that we can use the same function to #implement the core of psd(), csd(), and spectrogram() without doing #extra calculations. We return the unaveraged Pxy, freqs, and t. I'm not sure if this can be used to do an STFT and ISTFT, though. Is there anything else, or should I translate something like this?

    Read the article

  • Changing font size of legend title in Python pylab rose/polar plot

    - by LaurieW
    I'm trying to change the font size of the title of an existing legend on a rose, or 'polar', plot. Most of the code was written by somebody else, who is away. I've added:- ax.legend(title=legend_title) setp(l.get_title(), fontsize=8) to add the title 'legend_title', which is a variable that the user enters a string for in a a different function that uses this code. The second line of this doesn't return an error but doesn't appear to do anything either. The complete code is below. 'Rose' and 'RoseAxes' are modules/functions written by somebody. Does anyone know of a way to change the legend title font size? I've found some examples for normal plots but can't find any for rose/polar plots. from Rose.RoseAxes import RoseAxes from pylab import figure, title, setp, close, clf from PlotGeneration import color_map_xml fig = figure(1) rect = [0.02, 0.1, 0.8, 0.8] ax = RoseAxes(fig, rect, axisbg='w') fig.add_axes(ax) if cmap == None: (XMLcmap,colors) = color_map_xml.get_cmap('D:/HRW/VET/HrwPyLibs/ColorMapLibrary/paired.xml',255) else: XMLcmap = cmap bqs = kwargs.pop('CTfigname', None) ax.box(Dir, U, bins = rose_binX, units = unit, nsector = nsector, cmap = XMLcmap, lw = 0, **kwargs ) l = ax.legend() ax.legend(title=legend_title) setp(l.get_texts(), fontsize=8) setp(l.get_title(), fontsize=8) Thanks for any help

    Read the article

  • Python Access Parallel Port

    - by PPTim
    Hi, I've been trying to access the parallel port with pyParallel, which is in the same sourceforge as PySerial: http://sourceforge.net/projects/pyserial/files/ I'm getting a WidowsError: exception: priviledged instruciton. Has anyone used this module before? import parallel p = parallel.Parallel() Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Python26\lib\site-packages\parallel\parallelwin32.py", line 74, in __init__ self.ctrlReg = _pyparallel.inp(self.ctrlRegAdr) WindowsError: exception: priviledged instruction

    Read the article

  • Python class design - Splitting up big classes into multiple ones to group functionality

    - by Ivo Wetzel
    OK I've got 2 really big classes 1k lines each that I currently have split up into multiple ones. They then get recombined using multiple inheritance. Now I'm wondering, if there is any cleaner/better more pythonic way of doing this. Completely factoring them out would result in endless amounts of self.otherself.do_something calls, which I don't think is the way it should be done. To make things clear here's what it currently looks like: from gui_events import GUIEvents # event handlers from gui_helpers import GUIHelpers # helper methods that don't directly modify the GUI # GUI.py class GUI(gtk.Window, GUIEvents, GUIHelpers): # general stuff here stuff here One problem that is result of this is Pylint complaining giving me trillions of "init not called" / "undefined attribute" / "attribute accessed before definition" warnings.

    Read the article

  • python win32com EXCEL data input error

    - by Rafal
    Welcome, I'm exporting results of my script into Excel spreadsheet. Everything works fine, I put big sets of data into SpreadSheet, but sometimes an error occurs: File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 550, in __setattr__ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) pywintypes.com_error: (-2147352567, 'Exception.', (0, None, None, None, 0, -2146777998), None)*** I suppose It's not a problem of input data format. I put several different types of data strings, ints, floats, lists and it works fine. When I run the sript for the second time it works fine - no error. What's going on? PS. This is code that generates error, what's strange is that the error doesn't occur always. Say 30% of runs results in an error. : import win32com.client def Generate_Excel_Report(): Excel=win32com.client.Dispatch("Excel.Application") Excel.Workbooks.Add(1) Cells=Excel.ActiveWorkBook.ActiveSheet.Cells for i in range(100): Row=int(35+i) for j in range(10): Cells(int(Row),int(5+j)).Value="string" for i in range(100): Row=int(135+i) for j in range(10): Cells(int(Row),int(5+j)).Value=32.32 #float Generate_Excel_Report() The strangest for me is that when I run the script with the same code, the same input many times, then sometimes an error occurs, sometimes not. Thanks in advance for any help

    Read the article

  • Properly using subprocess.PIPE in python?

    - by Gordon Fontenot
    I'm trying to use subprocess.Popen to construct a sequence to grab the duration of a video file. I've been searching for 3 days, and can't find any reason online as to why this code isn't working, but it keeps giving me a blank result: import sys import os import subprocess def main(): the_file = "/Volumes/Footage/Acura/MDX/2001/Crash Test/01 Acura MDX Front Crash.mov" ffmpeg = subprocess.Popen(['/opt/local/bin/ffmpeg', '-i', the_file], stdout = subprocess.PIPE, ) grep = subprocess.Popen(['grep', 'Duration'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) cut = subprocess.Popen(['cut', '-d', ' ', '-f', '4'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) sed = subprocess.Popen(['sed', 's/,//'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) duration = sed.communicate() print duration if __name__ == '__main__': main()

    Read the article

  • Use python decorators on class methods and subclass methods

    - by AlexH
    Goal: Make it possible to decorate class methods. When a class method gets decorated, it gets stored in a dictionary so that other class methods can reference it by a string name. Motivation: I want to implement the equivalent of ASP.Net's WebMethods. I am building this on top of google app engine, but that does not affect the point of difficulty that I am having. How it Would look if it worked: class UsefulClass(WebmethodBaseClass): def someMethod(self, blah): print(blah) @webmethod def webby(self, blah): print(blah) # the implementation of this class could be completely different, it does not matter # the only important thing is having access to the web methods defined in sub classes class WebmethodBaseClass(): def post(self, methodName): webmethods[methodName]("kapow") ... a = UsefulClass() a.post("someMethod") # should error a.post("webby") # prints "kapow" There could be other ways to go about this. I am very open to suggestions

    Read the article

  • Python decoding issue with hashlib.digest() method

    - by Sorw
    Hello StackOverflow community, Using Google App Engine, I wrote a keyToSha256() method within a model class (extending db.Model) : class Car(db.Model): def keyToSha256(self): keyhash = hashlib.sha256(str(self.key())).digest() return keyhash When displaying the output (ultimately within a Django template), I get garbled text, for example : ?????_??!`?I?!?;?QeqN??Al?'2 I was expecting something more in line with this : 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 Am I missing something important ? Despite reading several guides on ASCII, Unicode, utf-8 and the like, I think I'm still far from mastering the secrets of string encoding/decoding. After browsing StackOverflow and searching for insights via Google, I figured out I should ask the question here. Any idea ? Thanks !

    Read the article

  • Google App Engine (python): TemplateSyntaxError: 'for' statements with five words should end in 'rev

    - by Phil
    This is using the web app framework, not Django. The following template code is giving me an TemplateSyntaxError: 'for' statements with five words should end in 'reversed' error when I try to render a dictionary. I don't understand what's causing this error. Could somebody shed some light on it for me? {% for code, name in charts.items %} <option value="{{code}}">{{name}}</option> {% endfor %} I'm rendering it using the following: class GenerateChart(basewebview): def get(self): values = {"datepicker":True} values["charts"] = {"p3": "3D Pie Chart", "p": "Segmented Pied Chart"} self.render_page("generatechart.html", values) class basewebview(webapp.RequestHandler): ''' Base class for all webapp.RequestHandler type classes ''' def render_page(self, filename, template_values=dict()): filename = "%s/%s" % (_template_dir, filename) path = os.path.join(os.path.dirname(__file__), filename) self.response.out.write(template.render(path, template_values))

    Read the article

  • python mysqldb string formatting

    - by Daniel
    How do I do this correctly: I want to do a query like this: query = """SELECT * FROM sometable order by %s %s limit %s, %s;""" conn = app_globals.pool.connection() cur = conn.cursor() cur.execute(query, (sortname, sortorder, limit1, limit2) ) results = cur.fetchall() All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them. So it ends up like: ORDER BY 'somecol' 'DESC' Which is wrong should be: ORDER BY somecol DESC Any help greatly appreciated!

    Read the article

  • Python MySQLdb placeholders syntax

    - by ensnare
    I'd like to use placeholders as seen in this example: cursor.execute (""" UPDATE animal SET name = %s WHERE name = %s """, ("snake", "turtle")) Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in: query = """UPDATE animal SET name = %s WHERE name = %s """, ("snake", "turtle")) cursor.execute(query) cursor2.execute(query) cursor3.execute(query) What would be the proper syntax for doing something like this?

    Read the article

  • image segmentation using pil/any package of python

    - by sag
    hi all., i need to segment an image into regions .i'm using pil.i found no module to segment image in pil. I need this segmented regions as a list or dictionary. Actually i'm trying to compare the images for similarity in content aware fashion.for that i need to segment the image. i tried segwin tool but it is drawing another image(which is not required and also time consuming) thans in advance

    Read the article

  • Dont understand Python Method

    - by user836087
    I dont understand what is going on in the move method. I am taking the AI course from Udacity.com. The video location is: http://www.udacity.com/view#Course/cs373/CourseRev/apr2012/Unit/512001/Nugget/480015 Below is the code I dont get, its not working as shown in the video .. The answer I should be getting according to Udacity is [0, 0, 1, 0, 0] Here is what I get [] p=[0, 1, 0, 0, 0] def move(p, U): q = [] for i in range(len(p)): q.append(p[(i-U) % len(p)]) return q print move(p, 1)

    Read the article

< Previous Page | 129 130 131 132 133 134 135 136 137 138 139 140  | Next Page >