Search Results

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

Page 59/548 | < Previous Page | 55 56 57 58 59 60 61 62 63 64 65 66  | Next Page >

  • Converting Python Script to Vb.NET - Involves Post and Input XML String

    - by Jason Shoulders
    I'm trying to convert a Python Script to Vb.Net. The Python Script appears to accept some XML input data and then takes it to a web URL and does a "POST". I tried some VB.NET code to do it, but I think my approach is off because I got an error back "BadXmlDataErr" plus I can't really format my input XML very well - I'm only doing string and value. The input XML is richer than that. Here is an example of what the XML input data looks like in the Python script: <obj is="MyOrg:realCommand_v1/" > <int name="priority" val="1" /> <real name="value" val="9.5" /> <str name="user" val="MyUserName" /> <reltime name="overrideTime" val="PT60S"/> </obj> Here's the Vb.net code I attempted to convert that: Dim reqparm As New Specialized.NameValueCollection reqparm.Add("priority", "1") reqparm.Add("value", "9.5") reqparm.Add("user", "MyUserName") reqparm.Add("overrideTime", "PT60S") Using client As New Net.WebClient Dim sTheUrl As String = "[My URL]" Dim responsebytes = client.UploadValues(sTheUrl, "POST", MyReqparm) Dim responsebody = (New System.Text.UTF8Encoding).GetString(responsebytes) End Using I feel like I should be doing something else. Can anyone point me to the right direction?

    Read the article

  • Prolog singleton variables in Python

    - by Rubens
    I'm working on a little set of scripts in python, and I came to this: line = "a b c d e f g" a, b, c, d, e, f, g = line.split() I'm quite aware of the fact that these are decisions taken during implementation, but shouldn't (or does) python offer something like: _, _, var_needed, _, _, another_var_needed, _ = line.split() as well as Prolog does offer, in order to exclude the famous singleton variables. I'm not sure, but wouldn't it avoid unnecessary allocation? Or creating references to the result of the split call does not count up as overhead? EDIT: Sorry, my point here is: in Prolog, as far as I'm concerned, in an expression like: test(L, N) :- test(L, 0, N). test([], N, N). test([_|T], M, N) :- V is M + 1, test(T, V, N). The variable represented by _ is not accessible, for what I suppose the reference to the value that does exist in the list [_|T] is not even created. But, in Python, if I use _, I can use the last value assigned to _, and also, I do suppose the assignment occurs for each of the variables _ -- which may be considered an overhead. My question here is if shouldn't there be (or if there is) a syntax to avoid such unnecessary attributions.

    Read the article

  • Square Brackets in Python Regular Expressions (re.sub)

    - by user1479984
    I'm migrating wiki pages from the FlexWiki engine to the FOSwiki engine using Python regular expressions to handle the differences between the two engines' markup languages. The FlexWiki markup and the FOSwiki markup, for reference. Most of the conversion works very well, except when I try to convert the renamed links. Both wikis support renamed links in their markup. For example, Flexwiki uses: "Link To Wikipedia":[http://www.wikipedia.org/] FOSwiki uses: [[http://www.wikipedia.org/][Link To Wikipedia]] both of which produce something that looks like I'm using the regular expression renameLink = re.compile ("\"(?P<linkName>[^\"]+)\":\[(?P<linkTarget>[^\[\]]+)\]") to parse out the link elements from the FlexWiki markup, which after running through something like "Link Name":[LinkTarget] is reliably producing groups <linkName> = Link Name <linkTarget = LinkTarget My issue occurs when I try to use re.sub to insert the parsed content into the FOSwiki markup. My experience with regular expressions isn't anything to write home about, but I'm under the impression that, given the groups <linkName> = Link Name <linkTarget = LinkTarget a line like line = renameLink.sub ( "[[\g<linkTarget>][\g<linkName>]]" , line ) should produce [[LinkTarget][Link Name]] However, in the output to the text files I'm getting [[LinkTarget [[Link Name]] which breaks the renamed links. After a little bit of fiddling I managed a workaround, where line = renameLink.sub ( "[[\g<linkTarget>][ [\g<linkName>]]" , line ) produces [[LinkTarget][ [[Link Name]] which, when displayed in FOSwiki looks like <[[Link Name> <--- Which WORKS, but isn't very pretty. I've also tried line = renameLink.sub ( "[[\g<linkTarget>]" + "[\g<linkName>]]" , line ) which is producing [[linkTarget [[linkName]] There are probably thousands of instances of these renamed links in the pages I'm trying to convert, so fixing it by hand isn't any good. For the record I've run the script under Python 2.5.4 and Python 2.7.3, and gotten the same results. Am I missing something really obvious with the syntax? Or is there an easy workaround?

    Read the article

  • Python vs all the major professional languages [closed]

    - by Matt
    I've been reading up a lot lately on comparisons between Python and a bunch of the more traditional professional languages - C, C++, Java, etc, mainly trying to find out if its as good as those would be for my own purposes. I can't get this thought out of my head that it isn't good for 'real' programming tasks beyond automation and macros. Anyway, the general idea I got from about two hundred forum threads and blog posts is that for general, non-professional-level progs, scripts, and apps, and as long as it's a single programmer (you) writing it, a given program can be written quicker and more efficiently with Python than it could be with pretty much any other language. But once its big enough to require multiple programmers or more complex than a regular person (read: non-professional) would have any business making, it pretty much becomes instantly inferior to a million other languages. Is this idea more or less accurate? (I'm learning Python for my first language and want to be able to make any small app that I want, but I plan on learning C eventually too, because I want to get into driver writing eventually. So I've been trying to research each ones strengths and weaknesses as much as I can.) Anyway, thanks for any input

    Read the article

  • Python to Java translation

    - by obelix1337
    Hello, i get quite short code of algorithm in python, but i need to translate it to Java. I didnt find any program to do that, so i will really appreciate to help translating it. I learned python a very little to know the idea how algorithm work. The biggest problem is because in python all is object and some things are made really very confuzing like sum(self.flow[(source, vertex)] for vertex, capacity in self.get_edges(source)) and "self.adj" is like hashmap with multiple values which i have no idea how to put all together. Is any better collection for this code in java? code is: [CODE] class FlowNetwork(object): def __init__(self): self.adj, self.flow, = {},{} def add_vertex(self, vertex): self.adj[vertex] = [] def get_edges(self, v): return self.adj[v] def add_edge(self, u,v,w=0): self.adj[u].append((v,w)) self.adj[v].append((u,0)) self.flow[(u,v)] = self.flow[(v,u)] = 0 def find_path(self, source, sink, path): if source == sink: return path for vertex, capacity in self.get_edges(source): residual = capacity - self.flow[(source,vertex)] edge = (source,vertex,residual) if residual > 0 and not edge in path: result = self.find_path(vertex, sink, path + [edge]) if result != None: return result def max_flow(self, source, sink): path = self.find_path(source, sink, []) while path != None: flow = min(r for u,v,r in path) for u,v,_ in path: self.flow[(u,v)] += flow self.flow[(v,u)] -= flow path = self.find_path(source, sink, []) return sum(self.flow[(source, vertex)] for vertex, capacity in self.get_edges(source)) g = FlowNetwork() map(g.add_vertex, ['s','o','p','q','r','t']) g.add_edge('s','o',3) g.add_edge('s','p',3) g.add_edge('o','p',2) g.add_edge('o','q',3) g.add_edge('p','r',2) g.add_edge('r','t',3) g.add_edge('q','r',4) g.add_edge('q','t',2) print g.max_flow('s','t') [/CODE] result of this example is "5". algorithm find max flow in graph(linked list or whatever) from source vertex "s" to destination "t". Many thanx for any idea

    Read the article

  • Generating a python file

    - by fema
    Hi! I'm havin issues with python (imo python itself is an issue). I have a txt file, it contains a custom language and I have to translate it to a working python code. The input: import sys n = int(sys.argv[1]) ;;print "Beginning of the program!" LOOP i in range(1,n) {print "The number:";;print i} BRANCH n < 5 {print n ;;print "less than 5"} The wanted output looks exactly like this: import sys n = int(sys.argv[1]) print "Beginning of the program!" for i in range(1,n) : print "The number:" print i if n < 5 : print n print "less than 5" The name of the input file is read from parameter. The out file is out.py. In case of a wrong parameter, it gives an error message. The ;; means a new line. When I tried to do it, I made an array, I read all the lines into it, split by " ". Then I wanted to strip it from the marks I don't need. I made 2 loops, one for the lines, one for the words. So then I started to replace the things. Everything went fine until it came to the } mark. It finds it, but it can not replace or strip it. I have no more idea what to do. Could someone help me, please? Thanks in advance!

    Read the article

  • Python 2.6 does not like appending to existing archives in zip files

    - by user313661
    Hello, In some Python unit tests of a program I'm working on we use in-memory zipfiles for end to end tests. In SetUp() we create a simple zip file, but in some tests we want to overwrite some archives. For this we do "zip.writestr(archive_name, zip.read(archive_name) + new_content)". Something like import zipfile from StringIO import StringIO def Foo(): zfile = StringIO() zip = zipfile.ZipFile(zfile, 'a') zip.writestr( "foo", "foo content") zip.writestr( "bar", "bar content") zip.writestr( "foo", zip.read("foo") + "some more foo content") print zip.read("bar") Foo() The problem is that this works fine in Python 2.4 and 2.5, but not 2.6. In Python 2.6 this fails on the print line with "BadZipfile: File name in directory "bar" and header "foo" differ." It seems that it is reading the correct file bar, but that it thinks it should be reading foo instead. I'm at a loss. What am I doing wrong? Is this not supported? I tried searching the web but could find no mention of similar problems. I read the zipfile documentation, but could not find anything (that I thought was) relevant, especially since I'm calling read() with the filename string. Any ideas? Thank you in advance!

    Read the article

  • Porting Python algorithm to C++ - different solution

    - by cb0
    Hello, I have written a little brute string generation script in python to generate all possible combinations of an alphabet within a given length. It works quite nice, but for the reason I wan't it to be faster I try to port it to C++. The problem is that my C++ Code is creating far too much combination for one word. Heres my example in python: ./test.py gives me aaa aab aac aad aa aba .... while ./test (the c++ programm gives me) aaa aaa aaa aaa aa Here I also get all possible combinations, but I get them twice ore more often. Here is the Code for both programms: #!/usr/bin/env python import sys #Brute String Generator #Start it with ./brutestringer.py 4 6 "abcdefghijklmnopqrstuvwxyz1234567890" "" #will produce all strings with length 4 to 6 and chars from a to z and numbers 0 to 9 def rec(w, p, baseString): for c in "abcd": if (p<w - 1): rec(w, p + 1, baseString + "%c" % c) print baseString for b in range(3,4): rec(b, 0, "") And here the C++ Code #include <iostream> using namespace std; string chars="abcd"; void rec(int w,int b,string p){ unsigned int i; for(i=0;i<chars.size();i++){ if(b < (w-1)){ rec(w, (b+1), p+chars[i]); } cout << p << "\n"; } } int main () { int a=3, b=0; rec (a+1,b, ""); return 0; } Does anybody see my fault ? I don't have much experience with C++. Thanks indeed

    Read the article

  • python interactive mode module import issue

    - by Jeff
    I believe I have what would be called a scope issue, perhaps name space. Not too sure I'm new to python. I'm trying to make a module that will search through a list using regular expressions. I'm sure there is a better way of doing it but this error that I'm getting is bugging me and I want to understand why. here's my code: class relist(list): def __init__(self, l): list.__init__(self, l) def __getitem__(self, rexp): r = re.compile(rexp) res = filter(r.match, self) return res if __name__ == '__main__': import re listl = [x+y for x in 'test string' for y in 'another string for testing'] print(listl) test = relist(listl) print('----------------------------------') print(test['[s.]']) When I run this code through the command line it works the way I expect it to; however when I run it through python interactive mode I get the error >>> test['[s.]'] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "relist.py", line 8, in __getitem__ r = re.compile(rexp) NameError: global name 're' is not defined While in the interactive mode I do import re and I am able to use the re functions, but for some reason when I'm trying to execute the module it doesn't work. Do I need to import re into the scope of the class? I wouldn't think so because doesn't python search through other scopes if it's not found in the current one? I appreciate your help, and if there is a better way of doing this search I would be interested in knowing. Thanks

    Read the article

  • Communicating with a running python daemon

    - by hanksims
    I wrote a small Python application that runs as a daemon. It utilizes threading and queues. I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health. In a nutshell, I'd like to be able to do something like this: python application.py start # launches the daemon Later, I'd like to be able to come along and do something like: python application.py check_queue_size # return info from the daemonized process To be clear, I don't have any problem implementing the Django-inspired syntax. What I don't have any idea how to do is to send signals to the daemonized process (start), or how to write the daemon to handle and respond to such signals. Like I said above, I'm looking for general approaches. The only one I can see right now is telling the daemon constantly log everything that might be needed to a file, but I hope there's a less messy way to go about it. UPDATE: Wow, a lot of great answers. Thanks so much. I think I'll look at both Pyro and the web.py/Werkzeug approaches, since Twisted is a little more than I want to bite off at this point. The next conceptual challenge, I suppose, is how to go about talking to my worker threads without hanging them up. Thanks again.

    Read the article

  • Python to C/C++ const char question

    - by tsukemonoki
    I am extending Python with some C++ code. One of the functions I'm using has the following signature: int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, char *format, char **kwlist, ...); (link: http://docs.python.org/release/1.5.2p2/ext/parseTupleAndKeywords.html) The parameter of interest is kwlist. In the link above, examples on how to use this function are given. In the examples, kwlist looks like: static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; When I compile this using g++, I get the warning: warning: deprecated conversion from string constant to ‘char*’ So, I can change the static char* to a static const char*. Unfortunately, I can't change the Python code. So with this change, I get a different compilation error (can't convert char** to const char**). Based on what I've read here, I can turn on compiler flags to ignore the warning or I can cast each of the constant strings in the definition of kwlist to char *. Currently, I'm doing the latter. What are other solutions? Sorry if this question has been asked before. I'm new.

    Read the article

  • Efficient way to get highly correlated pairs from large data set in Python or R

    - by Akavall
    I have a large data set (Let's say 10,000 variables with about 1000 elements each), we can think of it as 2D list, something like: [[variable_1], [variable_2], ............ [variable_n] ] I want to extract highly correlated variable pairs from that data. I want "highly correlated" to be a parameter that I can choose. I don't need all pairs to be extracted, and I don't necessarily want the most correlated pairs. As long as there is an efficient method that gets me highly correlated pairs I am happy. Also, it would be nice if a variable does not show up in more than one pair. Although this might not be crucial. Of course, there is a brute force way to finding such pairs, but it is too slow for me. I've googled around for a bit and found some theoretical work on this issue, but I wasn't able for find a package that could do what I am looking for. I mostly work in python, so a package in python would be most helpful, but if there exists a package in R that does what I am looking for it will be great. Does anyone know of a package that does the above in Python or R? Or any other ideas? Thank You in Advance

    Read the article

  • Ruby, Python, or PHP?

    - by Gabe
    And so we return to the age old question - but with a few twists. This morning, I searched and read up on which web development language to learn first. I'm thinking Ruby, Python, or perhaps PHP. But I have a few questions before deciding. Background: I'm a year into C++ (through school), but want to get into web development. I have all summer to commit to one language, learn it, do some projects, get up some websites, and so on. Now my questions (and these are assuming that I should choose between Ruby, Python, and PHP - if I should choose a different language, let me know.): I hope to use whichever language I learn for websites/web apps. Some of the threads on stackoverflow suggested Python was the best overall language, but others were unanimous that Ruby was best specifically for web development. For a first language suited towards web development, which language do you recommend, and why? This might tie into the first question, but which language looks most promising for future work, future personal projects, and basically the future in general? I'm just a freshman in college. Ideally, the language I choose would be on the rise, community-wise and opportunity-wise. (One reason I'm leaning towards Ruby is that it seems a lot of the newer tech startups/successes are using it.)

    Read the article

  • Obtain File size with os.path.getsize() in Python 2.7.5

    - by Ruxuan Ouyang
    I am new to python. I am trying to use os.path.getsize() to obtain the file size. However, if the file name is not in Englist, but in Chinese, Gemany, or French, etc, Python cannot recognize it and do not return the size of the file. Could you please help me with it? How can I let Python recognize the file's name and return the size of these kind of files? For example: The file's name is:?????????? ????????????? ? ????????????? ???????? ?? 2030?.doc path="C:\xxxx\xxx\xxxx\?????????? ????????????? ? ????????????? ???????? ?? 2030?.doc" I'd like to use" os.path.getsize(path) But it does not recognize the file name. Could you please kindly tell me what should I do? Thank you very much!

    Read the article

  • Python script web service timeout

    - by Robert
    We have had a Python script running for many months now that simply scans through a directory of files, and posts each file to our web site via a web service call. The web site is also written in Python. For no apparent reason, this morning this script started throwing the following error: urllib2.URLError: <urlopen error (10060, 'Operation timed out')> The site itself is up and running just fine. There are no indications of any errors. The developer that was working on this site is no longer with us, and we do not have a strong Python developer on staff as we are moving away from that. Before I do an all nighter and rewrite this thing in C#, I wanted to see if anyone had any experience dealing with this issue. I do know that the script is connecting to a secure site (HTTPS), so I am not sure if something has come up with that, and I honestly dont know where to look to determine that. As I said before, the site itself isn't showing any signs of error, including SSL. Any thoughts?

    Read the article

  • Heapsort not working in Python for list of strings using heapq module

    - by VSN
    I was reading the python 2.7 documentation when I came across the heapq module. I was interested in the heapify() and the heappop() methods. So, I decided to write a simple heapsort program for integers: from heapq import heapify, heappop user_input = raw_input("Enter numbers to be sorted: ") data = map (int, user_input.split(",")) new_data = [] for i in range(len(data)): heapify(data) new_data.append(heappop(data)) print new_data This worked like a charm. To make it more interesting, I thought I would take away the integer conversion and leave it as a string. Logically, it should make no difference and the code should work as it did for integers: from heapq import heapify, heappop user_input = raw_input("Enter numbers to be sorted: ") data = user_input.split(",") new_data = [] for i in range(len(data)): heapify(data) print data new_data.append(heappop(data)) print new_data Note: I added a print statement in the for loop to see the heapified list. Here's the output when I ran the script: `$ python heapsort.py Enter numbers to be sorted: 4, 3, 1, 9, 6, 2 [' 1', ' 3', ' 2', ' 9', ' 6', '4'] [' 2', ' 3', '4', ' 9', ' 6'] [' 3', ' 6', '4', ' 9'] [' 6', ' 9', '4'] [' 9', '4'] ['4'] [' 1', ' 2', ' 3', ' 6', ' 9', '4']` The reasoning I applied was that since the strings are being compared, the tree should be the same if they were numbers. As is evident, the heapify didn't work correctly after the third iteration. Could someone help me figure out if I am missing something here? I'm running Python 2.4.5 on RedHat 3.4.6-9. Thanks, VSN

    Read the article

  • Learning Python and trying to get first two letters and last two letters of a string.

    - by Sergio Tapia
    Here's my code: # B. both_ends # Given a string s, return a string made of the first 2 # and the last 2 chars of the original string, # so 'spring' yields 'spng'. However, if the string length # is less than 2, return instead the empty string. def both_ends(s): if len(s) <= 2: return "" else: return s[0] + s[1] + s[len(s)-2] + s[len(s-1)] # +++your code here+++ return Unfortunately my program doesn't run. :( I'm sure I'm overlooking something since I'm a newbie with Python. Here's the error: > Traceback (most recent call last): File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 120, in <module> main() File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 97, in main test(both_ends('spring'), 'spng') File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 44, in both_ends return s[0] + s[1] + s[len(s)-2] + s[len(s-1)] TypeError: unsupported operand type(s) for -: 'str' and 'int' Thanks for the help guys. :D

    Read the article

  • How to download the Enthought Tool Suite python script?

    - by user1539217
    I have Python downloaded already, but want to contribute code to the Enthought Tool Suite (ETS). According to this site (http://code.enthought.com/source/): it says to download the following python script: https://raw.github.com/enthought/ets/master/ets.py I put the ets.py into the python script, save as...and in the Python Shell, I typed in "import ets" However, nothing happens. Also, the site says to run the following commands: $ mkdir ets $ cd ets # and copy ets.py here $ python ets.py clone Typing those lines in Python Shell gives me the message: "SyntaxError: invalid syntax" As you can see, I'm new to Python, and I don't know what I'm doing. How do I download the ETS script and run the commands??

    Read the article

  • Python TEA implementation

    - by Gaks
    Anybody knows proper python implementation of TEA (Tiny Encryption Algorithm)? I tried the one I've found here: http://sysadminco.com/code/python-tea/ - but it does not seem to work properly. It returns different results than other implementations in C or Java. I guess it's caused by completely different data types in python (or no data types in fact). Here's the code and an example: def encipher(v, k): y=v[0];z=v[1];sum=0;delta=0x9E3779B9;n=32 w=[0,0] while(n>0): y += (z << 4 ^ z >> 5) + z ^ sum + k[sum & 3] y &= 4294967295L # maxsize of 32-bit integer sum += delta z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3] z &= 4294967295L n -= 1 w[0]=y; w[1]=z return w def decipher(v, k): y=v[0] z=v[1] sum=0xC6EF3720 delta=0x9E3779B9 n=32 w=[0,0] # sum = delta<<5, in general sum = delta * n while(n>0): z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3] z &= 4294967295L sum -= delta y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3] y &= 4294967295L n -= 1 w[0]=y; w[1]=z return w Python example: >>> import tea >>> key = [0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805] >>> v = [0xe15034c8, 0x260fd6d5] >>> res = tea.encipher(v, key) >>> "%X %X" % (res[0], res[1]) **'70D16811 F935148F'** C example: #include <unistd.h> #include <stdio.h> void encipher(unsigned long *const v,unsigned long *const w, const unsigned long *const k) { register unsigned long y=v[0],z=v[1],sum=0,delta=0x9E3779B9, a=k[0],b=k[1],c=k[2],d=k[3],n=32; while(n-->0) { sum += delta; y += (z << 4)+a ^ z+sum ^ (z >> 5)+b; z += (y << 4)+c ^ y+sum ^ (y >> 5)+d; } w[0]=y; w[1]=z; } int main() { unsigned long v[] = {0xe15034c8, 0x260fd6d5}; unsigned long key[] = {0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805}; unsigned long res[2]; encipher(v, res, key); printf("%X %X\n", res[0], res[1]); return 0; } $ ./tea **D6942D68 6F87870D** Please note, that both examples were run with the same input data (v and key), but results were different. I'm pretty sure C implementation is correct - it comes from a site referenced by wikipedia (I couldn't post a link to it because I don't have enough reputation points yet - some antispam thing)

    Read the article

  • Python RSS Feeder + Jquery RSS Reader

    - by Panther24
    I'm trying to implement an RSS Feeder in python using PyRSS2Gen and it created an XML file. Now in jQuery I'm using Google Ajax API's RSS reader and trying to read it. I get an error saying something is wrong. I'm unable to figure out the issue. I've checked some documentation but not able to get it. This is how my xml file looks: <rss version="2.0"> <channel> <title>Andrew's PyRSS2Gen feed</title> <link> http://www.dalkescientific.com/Python/PyRSS2Gen.html </link> <description> The latest news about PyRSS2Gen, a Python library for generating RSS2 feeds </description> <lastBuildDate>Fri, 26 Mar 2010 13:10:55 GMT</lastBuildDate> <generator>PyRSS2Gen-1.0.0</generator> <docs>http://blogs.law.harvard.edu/tech/rss</docs> <item> <title>PyRSS2Gen-0.0 released</title> <link> http://www.dalkescientific.com/news/030906-PyRSS2Gen.html </link> <description> Dalke Scientific today announced PyRSS2Gen-0.0, a library for generating RSS feeds for Python. </description> <guid isPermaLink="true"> http://www.dalkescientific.com/news/030906-PyRSS2Gen.html </guid> <pubDate>Sat, 06 Sep 2003 21:31:00 GMT</pubDate> </item> <item> <title>Thoughts on RSS feeds for bioinformatics</title> <link> http://www.dalkescientific.com/writings/diary/archive/2003/09/06/RSS.html </link> <description> One of the reasons I wrote PyRSS2Gen was to experiment with RSS for data collection in bioinformatics. Last year I came across... </description> <guid isPermaLink="true"> http://www.dalkescientific.com/writings/diary/archive/2003/09/06/RSS.html </guid> <pubDate>Sat, 06 Sep 2003 21:49:00 GMT</pubDate> </item> </channel> </rss> And my JS looks like this <!-- ++Begin Dynamic Feed Wizard Generated Code++ --> <!-- // Created with a Google AJAX Search and Feed Wizard // http://code.google.com/apis/ajaxsearch/wizards.html --> <!-- // The Following div element will end up holding the actual feed control. // You can place this anywhere on your page. --> <!-- Google Ajax Api --> <script src="../js/jsapi.js" type="text/javascript"></script> <!-- Dynamic Feed Control and Stylesheet --> <script src="../js/gfdynamicfeedcontrol.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="../css/gfdynamicfeedcontrol.css"> <script type="text/javascript"> function LoadDynamicFeedControl() { var feeds = [ {title: 'Demo', url: 'wcarss.xml' }]; var options = { stacked : false, horizontal : false, title : "" } new GFdynamicFeedControl(feeds, 'feed-control', options); } // Load the feeds API and set the onload callback. google.load('feeds', '1'); google.setOnLoadCallback(LoadDynamicFeedControl); </script> <!-- ++End Dynamic Feed Control Wizard Generated Code++ --> Can some help me and tell me what I'm doing wrong here? NOTE: Does the XML file have to be deployed? Cause currently its in my local machine and I'm trying to just call it.

    Read the article

  • Ubuntu: pip not working with python3.4

    - by val_
    Trying to get pip working on my Ubuntu pc. pip seems to be working for python2.7, but not for others. Here's the problem: $ pip Traceback (most recent call last): File "/usr/local/bin/pip", line 9, in <module> load_entry_point('pip==1.4.1', 'console_scripts', 'pip')() File "/usr/local/lib/python3.4/dist-packages/setuptools-1.1.5-py3.4.egg /pkg_resources.py", line 357, in load_entry_point def get_entry_info(dist, group, name): File "/usr/local/lib/python3.4/dist-packages/setuptools-1.1.5-py3.4.egg/pkg_resources.py", line 2394, in load_entry_point break File "/usr/local/lib/python3.4/dist-packages/setuptools-1.1.5-py3.4.egg/pkg_resources.py", line 2108, in load name = some.module:some.attr [extra1,extra2] ImportError: No module named 'pip' $ which pip /usr/local/bin/pip $ python2.7 -m pip //here can be just python, btw Usage: /usr/bin/python2.7 -m pip <command> [options] //and so on... $ python3.4 -m pip /usr/bin/python3.4: No module named pip From the home/user/.pip/pip.log : Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1431, in install requirement.uninstall(auto_confirm=True) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 598, in uninstall paths_to_remove.remove(auto_confirm) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1836, in remove renames(path, new_path) File "/usr/lib/python2.7/dist-packages/pip/util.py", line 295, in renames shutil.move(old, new) File "/usr/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/usr/bin/pip' There's no /usr/bin/pip btw. How can I fix this issue to work with pip and python 3.4 normally? I am trying to use pycharm, but it's package manager also stucks in this problem. Thanks for attention!

    Read the article

  • mysqldb interfaceError

    - by Johanna
    I have a very weird probleme with mysqldb (mysql module for python). I have a file with queries for inserting records in tables. If I call the functions from the file, it works just fine. But when I try to call one of the functions from another file it throws me a _mysql_exception.InterfaceError: (0, '') I really don't get what I'm doing wrong here.. I call the function from buildDB.py : import create create.newFormat("HD", 0,0,0) The function newFormat(..) is in create.py (imported) : from Database import Database db = Database() def newFormat(name, width=0, height=0, fps=0): format_query = "INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('"+name+"',"+str(width)+","+str(height)+","+str(fps)+");" db.execute(format_query) And the class Databse is the following : import MySQLdb from MySQLdb.constants import FIELD_TYPE class Database(): def __init__(self): server = "localhost" login = "seq" password = "seqmanager" database = "Sequence" my_conv = { FIELD_TYPE.LONG: int } self.conn = MySQLdb.connection(host=server, user=login, passwd=password, db=database, conv=my_conv) # self.cursor = self.conn.cursor() def close(self): self.conn.close() def execute(self, query): self.conn.query(query) (I put only relevant code) Traceback : Z:\sequenceManager\mysql>python buildDB.py D:\ProgramFiles\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWa rning: the sets module is deprecated from sets import ImmutableSet INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('HD',0 ,0,0); Traceback (most recent call last): File "buildDB.py", line 182, in <module> create.newFormat("HD") File "Z:\sequenceManager\mysql\create.py", line 52, in newFormat db.execute(format_query) File "Z:\sequenceManager\mysql\Database.py", line 19, in execute self.conn.query(query) _mysql_exceptions.InterfaceError: (0, '') The warning has never been a problem before so I don't think it's related.

    Read the article

  • Configure Django project in a subdirectory using mod_python. Admin not working.

    - by David
    HI guys. I was trying to configure my django project in a subdirectory of the root, but didn't get things working.(LOcally it works perfect). I followed the django official django documentarion to deploy a project with mod_python. The real problem is that I am getting "Page not found" errors, whenever I try to go to the admin or any view of my apps. Here is my python.conf file located in /etc/httpd/conf.d/ in Fedora 7 LoadModule python_module modules/mod_python.so SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On PythonPath "['/var/www/vhosts/mysite.com/httpdocs','/var/www/vhosts/mysite.com/httpdocs/mysite'] + sys.path" I know /var/www/ is not the best place to put my django project, but I just want to send a demo of my work in progress to my customer, later I will change the location. For example. If I go to www.domain.com/mysite/ I get the index view I configured in mysite.urls. But I cannot access to my app.urls (www.domain.com/mysite/app/) and any of the admin.urls.(www.domain.com/mysite/admin/) Here is mysite.urls: urlpatterns = patterns('', url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'), (r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done'), (r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), (r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'), (r'^$', 'app.views.index'), (r'^admin/', include(admin.site.urls)), (r'^app/', include('mysite.app.urls')), (r'^photologue/', include('photologue.urls')), ) I also tried changing admin.site.urls with ''django.contrib.admin.urls' , but it didn't worked. I googled a lot to solve this problem and read how other developers configure their django project, but didn't find too much information to deploy django in a subdirectory. I have the admin enabled in INSTALLED_APPS and the settings.py is ok. Please if you have any guide or telling me what I am doing wrong it will be much appreciated. THanks.

    Read the article

  • Solving embarassingly parallel problems using Python multiprocessing

    - by gotgenes
    How does one use multiprocessing to tackle embarrassingly parallel problems? Embarassingly parallel problems typically consist of three basic parts: Read input data (from a file, database, tcp connection, etc.). Run calculations on the input data, where each calculation is independent of any other calculation. Write results of calculations (to a file, database, tcp connection, etc.). We can parallelize the program in two dimensions: Part 2 can run on multiple cores, since each calculation is independent; order of processing doesn't matter. Each part can run independently. Part 1 can place data on an input queue, part 2 can pull data off the input queue and put results onto an output queue, and part 3 can pull results off the output queue and write them out. This seems a most basic pattern in concurrent programming, but I am still lost in trying to solve it, so let's write a canonical example to illustrate how this is done using multiprocessing. Here is the example problem: Given a CSV file with rows of integers as input, compute their sums. Separate the problem into three parts, which can all run in parallel: Process the input file into raw data (lists/iterables of integers) Calculate the sums of the data, in parallel Output the sums Below is traditional, single-process bound Python program which solves these three tasks: #!/usr/bin/env python # -*- coding: UTF-8 -*- # basicsums.py """A program that reads integer values from a CSV file and writes out their sums to another CSV file. """ import csv import optparse import sys def make_cli_parser(): """Make the command line interface parser.""" usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV", __doc__, """ ARGUMENTS: INPUT_CSV: an input CSV file with rows of numbers OUTPUT_CSV: an output file that will contain the sums\ """]) cli_parser = optparse.OptionParser(usage) return cli_parser def parse_input_csv(csvfile): """Parses the input CSV and yields tuples with the index of the row as the first element, and the integers of the row as the second element. The index is zero-index based. :Parameters: - `csvfile`: a `csv.reader` instance """ for i, row in enumerate(csvfile): row = [int(entry) for entry in row] yield i, row def sum_rows(rows): """Yields a tuple with the index of each input list of integers as the first element, and the sum of the list of integers as the second element. The index is zero-index based. :Parameters: - `rows`: an iterable of tuples, with the index of the original row as the first element, and a list of integers as the second element """ for i, row in rows: yield i, sum(row) def write_results(csvfile, results): """Writes a series of results to an outfile, where the first column is the index of the original row of data, and the second column is the result of the calculation. The index is zero-index based. :Parameters: - `csvfile`: a `csv.writer` instance to which to write results - `results`: an iterable of tuples, with the index (zero-based) of the original row as the first element, and the calculated result from that row as the second element """ for result_row in results: csvfile.writerow(result_row) def main(argv): cli_parser = make_cli_parser() opts, args = cli_parser.parse_args(argv) if len(args) != 2: cli_parser.error("Please provide an input file and output file.") infile = open(args[0]) in_csvfile = csv.reader(infile) outfile = open(args[1], 'w') out_csvfile = csv.writer(outfile) # gets an iterable of rows that's not yet evaluated input_rows = parse_input_csv(in_csvfile) # sends the rows iterable to sum_rows() for results iterable, but # still not evaluated result_rows = sum_rows(input_rows) # finally evaluation takes place as a chain in write_results() write_results(out_csvfile, result_rows) infile.close() outfile.close() if __name__ == '__main__': main(sys.argv[1:]) Let's take this program and rewrite it to use multiprocessing to parallelize the three parts outlined above. Below is a skeleton of this new, parallelized program, that needs to be fleshed out to address the parts in the comments: #!/usr/bin/env python # -*- coding: UTF-8 -*- # multiproc_sums.py """A program that reads integer values from a CSV file and writes out their sums to another CSV file, using multiple processes if desired. """ import csv import multiprocessing import optparse import sys NUM_PROCS = multiprocessing.cpu_count() def make_cli_parser(): """Make the command line interface parser.""" usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV", __doc__, """ ARGUMENTS: INPUT_CSV: an input CSV file with rows of numbers OUTPUT_CSV: an output file that will contain the sums\ """]) cli_parser = optparse.OptionParser(usage) cli_parser.add_option('-n', '--numprocs', type='int', default=NUM_PROCS, help="Number of processes to launch [DEFAULT: %default]") return cli_parser def main(argv): cli_parser = make_cli_parser() opts, args = cli_parser.parse_args(argv) if len(args) != 2: cli_parser.error("Please provide an input file and output file.") infile = open(args[0]) in_csvfile = csv.reader(infile) outfile = open(args[1], 'w') out_csvfile = csv.writer(outfile) # Parse the input file and add the parsed data to a queue for # processing, possibly chunking to decrease communication between # processes. # Process the parsed data as soon as any (chunks) appear on the # queue, using as many processes as allotted by the user # (opts.numprocs); place results on a queue for output. # # Terminate processes when the parser stops putting data in the # input queue. # Write the results to disk as soon as they appear on the output # queue. # Ensure all child processes have terminated. # Clean up files. infile.close() outfile.close() if __name__ == '__main__': main(sys.argv[1:]) These pieces of code, as well as another piece of code that can generate example CSV files for testing purposes, can be found on github. I would appreciate any insight here as to how you concurrency gurus would approach this problem. Here are some questions I had when thinking about this problem. Bonus points for addressing any/all: Should I have child processes for reading in the data and placing it into the queue, or can the main process do this without blocking until all input is read? Likewise, should I have a child process for writing the results out from the processed queue, or can the main process do this without having to wait for all the results? Should I use a processes pool for the sum operations? If yes, what method do I call on the pool to get it to start processing the results coming into the input queue, without blocking the input and output processes, too? apply_async()? map_async()? imap()? imap_unordered()? Suppose we didn't need to siphon off the input and output queues as data entered them, but could wait until all input was parsed and all results were calculated (e.g., because we know all the input and output will fit in system memory). Should we change the algorithm in any way (e.g., not run any processes concurrently with I/O)?

    Read the article

  • Any good tutorials all this web programming stuff for a GUI person? [closed]

    - by supercheetah
    For some reason, I am having a hard time understanding all this web programming stuff--from AJAX to JSON, etc. I've got plenty of experience programming GUIs. I'm currently working on a project in Python, and I thought that maybe I could just use PyJS (since it's GWT for Python, it uses an API that's very familiar to experienced GUI programmers like myself) to compile it with a Javascript interface on top, but alas, the compiler gave me a spectacular failure. It's obviously not meant to handle much of any Python beyond itself, and some of the core Python library. It would have been nice if it could, but I will admit, it would have been the lazy way to do it. I tried to learn Django, but for some reason, I'm just having a hard time understanding the tutorial on their website, and what it's all doing. Maybe it's not the best framework to learn, perhaps? Anyway, does anyone have a good primer/tutorial explaining all this stuff, especially for Python, and especially for someone coming from a GUI background?

    Read the article

< Previous Page | 55 56 57 58 59 60 61 62 63 64 65 66  | Next Page >