Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 71/782 | < Previous Page | 67 68 69 70 71 72 73 74 75 76 77 78  | Next Page >

  • Why can't I handle a KeyboardInterrupt in python?

    - by Josh
    I'm writing python 2.6.6 code on windows that looks like this: try: dostuff() except KeyboardInterrupt: print "Interrupted!" except: print "Some other exception?" finally: print "cleaning up...." print "done." dostuff() is a function that loops forever, reading a line at a time from an input stream and acting on it. I want to be able to stop it and clean up when I hit ctrl-c. What's happening instead is that the code under except KeyboardInterrupt: isn't running at all. The only thing that gets printed is "cleaning up...", and then a traceback is printed that looks like this: Traceback (most recent call last): File "filename.py", line 119, in <module> print 'cleaning up...' KeyboardInterrupt So, exception handling code is NOT running, and the traceback claims that a KeyboardInterrupt occurred during the finally clause, which doesn't make sense because hitting ctrl-c is what caused that part to run in the first place! Even the generic except: clause isn't running. EDIT: Based on the comments, I replaced the contents of the try: block with sys.stdin.read(). The problem still occurs exactly as described, with the first line of the finally: block running and then printing the same traceback.

    Read the article

  • Sending email in asp .net

    - by program-java
    hii every one, I m creating an project in which Admin is one user I want code or any idea how can Admin send a quotation of any type of products to his customer though email on their email ID and this quotation has to be a print option button bec. after clicking on print button quotation should be print How can i do it?

    Read the article

  • how to insert page view of a node in another page in drupal

    - by sprugman
    I have a list of node ids and I want to display the 'page' view of each one. For various reasons, I don't want to do this with views, and don't think I should need a module. Just an API call to theme('node'). Something like: $nids = array(3,4,5); foreach ($nids as $nid) { $node = node_load($nid); $result .= theme('node', $node); } but I'm not getting back the full page view of the node. I added this to my node-[type].tpl.php file: if ($page) print "PAGE MODE "; else print "NOT PAGE "; if ($teaser) print "TEASER MODE "; else print "NOT TEASER "; and got: NOT PAGE NOT TEASER I seem to be in some kind of limbo. I suspect there's an argument that I add to the theme function, but the terms are all so general (theme, teaser, page, node), I'm having trouble with my google-fu.

    Read the article

  • create a class attribute without going through __setattr__

    - by eric.frederich
    Hello, What I have below is a class I made to easily store a bunch of data as attributes. They wind up getting stored in a dictionary. I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units. When I started overriding __setattr__ I was having trouble creating that initial dicionary in the 2nd line of __init__ like so... super(MyDataFile, self).__setattr__('_data', {}) My question... Is there an easier way to create a class level attribute with going through __setattr__? Also, should I be concerned about keeping a separate dictionary or should I just store everything in self.__dict__? #!/usr/bin/env python from unitconverter import convert import re special_attribute_re = re.compile(r'(.+)__(.+)') class MyDataFile(object): def __init__(self, *args, **kwargs): super(MyDataFile, self).__init__(*args, **kwargs) super(MyDataFile, self).__setattr__('_data', {}) # # For attribute type access # def __setattr__(self, name, value): self._data[name] = value def __getattr__(self, name): if name in self._data: return self._data[name] match = special_attribute_re.match(name) if match: varname, units = match.groups() if varname in self._data: return self.getvaras(varname, units) raise AttributeError # # other methods # def getvaras(self, name, units): from_val, from_units = self._data[name] if from_units == units: return from_val return convert(from_val, from_units, units), units def __str__(self): return str(self._data) d = MyDataFile() print d # set like a dictionary or an attribute d.XYZ = 12.34, 'in' d.ABC = 76.54, 'ft' # get it back like a dictionary or an attribute print d.XYZ print d.ABC # get conversions using getvaras or using a specially formed attribute print d.getvaras('ABC', 'cm') print d.XYZ__mm

    Read the article

  • How can I find out the original username a process was started with?

    - by szabgab
    There is a perl script that needs to run as root but the we must make sure the user who runs the script did not log-in originally as user foo as it will be removed during the script. So how can I find out if the user, who might have su-ed several times since she logged in has not impersonated 'foo' at any time in that chain? I found an interesting perl script that was calling the following two shell scripts, but I think that would only work on Solaris. my $shell_paren = `ps -ef | grep -v grep | awk \'{print \$2\" \"\$3}\' | egrep \"^@_\" | awk \'{print \$2}'`; my $parent_owner = `ps -ef | grep -v grep | awk \'{print \$1\" \"\$2}\' | grep @_ | awk \'{print \$1}\'`; This needs to work on both Linux and Solaris and I'd rather eliminate the repeated calls to he the shell and keep the whole thing in Perl.

    Read the article

  • R matrix handling expressions aren't evaluated in a function or a "for" loop - Column extract doesn't seem to work

    - by Sal Leggio
    I have an R matrix named ddd. When I enter this, everything works fine: i <- 1 shapiro.test(ddd[,y]) ad.test(ddd[,y]) stem(ddd[,y]) print(y) The calls to Shapiro Wilk, Anderson Darling, and stem all work, and extract the same column. If I put this code in a "for" loop, the calls to Shapiro Wilk, and Anderson Darling stop working, while the the stem & leaf call and the print call continue to work. for (y in 7:10) { shapiro.test(ddd[,y]) ad.test(ddd[,y]) stem(ddd[,y]) print(y) } The decimal point is 1 digit(s) to the right of the | 0 | 0 0 | 899999 1 | 0 [1] 7 The same thing happens if I try and write a function. SW & AD do not work. The other calls do. D <- function (y) { + shapiro.test(ddd[,y]) + ad.test(ddd[,y]) + stem(ddd[,y]) + print(y) } D(9) The decimal point is at the | 9 | 000 9 | 10 | 00000 [1] 9 Why don't all the calls behave the same way?

    Read the article

  • Explanation of output

    - by Anon
    My program class Building { Building() { System.out.print("b "); } Building(String name) { this(); System.out.print("bn " + name); } }; public class House extends Building { House() { System.out.print("h "); // this is line# 1 } House(String name) { this(); // This is line#2 System.out.print("hn " + name); } public static void main(String[] args) { new House("x "); } } We know that compiler will write a call to super() as the first line in the child class's constructor. Therefore should not the output be: b (call from compiler written call to super(), before line#2 b (again from compiler written call to super(),before line#1 ) h hn x But the output is b h hn x Why is that?

    Read the article

  • Unable to plot graph using matplotlib

    - by Aman Deep Gautam
    I have the following code which searches all the directory in the current directory and then takes data from those files to plot the graph. The data is read correctly as verified by printing but there are no points plotted on graph. import argparse import os import matplotlib.pyplot as plt #find the present working directory pwd=os.path.dirname(os.path.abspath(__file__)) #find all the folders in the present working directory. dirs = [f for f in os.listdir('.') if os.path.isdir(f)] plt.figure() plt.xlim(0, 20000) plt.ylim(0, 1) for directory in dirs: os.chdir(os.path.join(pwd, directory)); chd_dir = os.path.dirname(os.path.abspath(__file__)) files = [ fl for fl in os.listdir('.') if os.path.isfile(fl) ] print files for f in files: f_obj = open(os.path.join(chd_dir, f), 'r') list_x = [] list_y = [] for i in xrange(0,4): f_obj.next() for line in f_obj: temp_list = line.split() print temp_list list_y.append(temp_list[0]) list_x.append(temp_list[1]) print 'final_lsit' print list_x print list_y plt.plot(list_x, list_y, 'r.') f_obj.close() os.chdir(pwd) plt.savefig("test.jpg") The input files look like the following: 5 865 14709 15573 14709 1.32667e-06 664 0.815601 14719 1.55333e-06 674 0.813277 14729 1.82667e-06 684 0.810185 14739 1.4e-06 694 0.808459 Can anybody help me with why this is happening? Being new I would like to know some tutorial where I can get help with kind of plotting as the tutorial I was following made me end up here. Any help appreciated.

    Read the article

  • issue running a batch script to kill a process

    - by user657064
    I am using the following script on a command line to kill a hypothetical notepad process (using a Korn shell in Windows XP, if that matters): kill $(tasklist | grep -i notepad.exe | awk '{print 2}') Now I take this line, and put it into a batch file c:\temp\testkill.bat, thinking that I should just as well be able to kill the process by running the batch file. However, when I run the batch file, I get the following awk error about unbalanced parentheses: C:/Temp ./testkill.bat C:\Tempkill $(tasklist | grep -i notepad.exe | awk '{print $2}') awk: unbalanced () Context is: {print $2}) <<< C:/Temp So I'm baffled as to why I am getting this error about unbalanced parentheses when I run this script via a batch file, but have no issues when I run the command directly from the command line? (Btw, I'm not necessarily tied to this way of killing a process - as a total noob to shell scripting, I am additionally wondering why if I write the following on the command line: tasklist | grep -i notepad.exe | awk '{print $2}' | kill the process ID that comes out of the tasklist/grep/awk calls doesn't seem to properly get piped to kill...)

    Read the article

  • Why will this for loop not return one field from list rather than the list?

    - by Dick Eshelman
    import csv """sample row = 10/6/2010,73.42,74.43,72.9,74.15,2993500""" filename_in = 'c:/python27/scripts/fiverows.csv' reader = csv.reader(open(filename_in, "rb"), dialect="excel", delimiter="\t", quoting =csv.QUOTE_MINIMAL) for row in reader: for item in row: print 'row = ',row print 'item = ', item When you run this script and print the row you get the sample row returned in [] as a list. When you print the item you get the sample row as an unquoted string. Why do I not get each field ie, (10/6/2010), (73.42), etc. returned as an item? How do I return a single item?

    Read the article

  • python - returns incorrect positive #

    - by tekknolagi
    what i'm trying to do is write a quadratic equation solver but when the solution should be -1, as in quadratic(2, 4, 2) it returns 1 what am i doing wrong? #!/usr/bin/python import math def quadratic(a, b, c): #a = raw_input("What\'s your `a` value?\t") #b = raw_input("What\'s your `b` value?\t") #c = raw_input("What\'s your `c` value?\t") a, b, c = float(a), float(b), float(c) disc = (b*b)-(4*a*c) print "Discriminant is:\n" + str(disc) if disc = 0: root = math.sqrt(disc) top1 = b + root top2 = b - root sol1 = top1/(2*a) sol2 = top2/(2*a) if sol1 != sol2: print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2) if sol1 == sol2: print "One solution:\n" + str(sol1) else: print "No solution!" EDIT: it returns the following... import mathmodules mathmodules.quadratic(2, 4, 2) Discriminant is: 0.0 One solution: 1.0

    Read the article

  • It says i have an indented block when i dont?

    - by user3728373
    def cave(): global key global response print(''' You find yourself standing infront of a cave. You venture into the cave to find a large door blocking your path. (insert key, turn around''') response = input("Enter a command: ") while response != 'insert key' or response != 'turn around': if response =='insert key' or response == 'turn around': break print('Choose one of the options: ") response = input() if response == 'insert key': if key == 1: win() else: print('''You don't have a key. Get One!!''') elif response == 'turn around' : home()

    Read the article

  • How to convert Beautiful Soup Unicode into a decimal value?

    - by MikeTheCoder
    I'm trying to Use python's Beautiful Soup Library to grab a bunch of divs from an html file, and from there get the string - which is a money value - that's inside the div. Then remove the dollar sign and convert it to a decimal so that I can use a greater than and less than conditional statement to compare values. I have googled the heck out of it and can't seem to come up with a way to convert this unicode string into a decimal value. I really could use some help here. How do I convert unicode into a decimal value? This was my last attempt: import unicodedata from bs4 import BeautifulSoup soup = BeautifulSoup(open("/Users/sm/Documents/python/htmldemo.html")) for tag in soup.findAll("div",attrs={"itemprop":"price"}) : val = tag.string new_val = val[8:] workable = int(new_val) if workable > 250: print(type(workable)) else: print(type(workable)) Edit: When I print the type of new_val I get : print(type(new_val))

    Read the article

  • For improving the join of two wave files

    - by kaki
    i want to get the values of the last 30 frames of the first wav file and first thirty frames of the second wave file in integer format and stored in a list or array. i have written the code for joining but during this manupalation i am getting in byte format and tried to convert it to integer but couldn't. as told before i want to get the frame detail of 1st 30 and last 30 in integer format,and by performing other operations join can be more successful looking for your help in this,please... thanking you, import wave m=['C:/begpython/S0001_0002.wav', 'C:/begpython/S0001_0001.wav'] i=1 a=m[i] infiles = [a] outfile = "C:/begpython/S0001_00367.wav" data= [] data1=[] for infile in infiles: w = wave.open(infile, 'rb') data1=[w.getnframes] #print w.readframes(100) data.append( [w.getparams(), w.readframes(w.getnframes())] ) #print w.readframes(1) #data1 = [ord(character) for character in data1] #print data1 #data1 = ''.join(chr(character) for character in data1) w.close() print data output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.writeframes(data[2][1]) output.close()

    Read the article

  • Python Etiquette: Importing Modules

    - by F3AR3DLEGEND
    Say I have two Python modules: module1.py: import module2 def myFunct(): print "called from module1" module2.py: def myFunct(): print "called from module2" def someFunct(): print "also called from module2" If I import module1, is it better etiquette to re-import module2, or just refer to it as module1.module2? For example (someotherfile.py): import module1 module1.myFunct() # prints "called from module1" module1.module2.myFunct() # prints "called from module2" I can also do this: module2 = module1.module2. Now, I can directly call module2.myFunct(). However, I can change module1.py to: from module2 import * def myFunct(): print "called from module1" Now, in someotherfile.py, I can do this: import module1 module1.myFunct() # prints "called from module1"; overrides module2 module1.someFunct() # prints "also called from module2" Also, by importing *, help('module1') shows all of the functions from module2. On the other hand, (assuming module1.py uses import module2), I can do: someotherfile.py: import module1, module2 module1.myFunct() # prints "called from module1" module2.myFunct() # prints "called from module2" Again, which is better etiquette and practice? To import module2 again, or to just refer to module1's importation?

    Read the article

  • How to lazy load a data structure (python)

    - by Anton Geraschenko
    I have some way of building a data structure (out of some file contents, say): def loadfile(FILE): return # some data structure created from the contents of FILE So I can do things like puppies = loadfile("puppies.csv") # wait for loadfile to work kitties = loadfile("kitties.csv") # wait some more print len(puppies) print puppies[32] In the above example, I wasted a bunch of time actually reading kitties.csv and creating a data structure that I never used. I'd like to avoid that waste without constantly checking if not kitties whenever I want to do something. I'd like to be able to do puppies = lazyload("puppies.csv") # instant kitties = lazyload("kitties.csv") # instant print len(puppies) # wait for loadfile print puppies[32] So if I don't ever try to do anything with kitties, loadfile("kitties.csv") never gets called. Is there some standard way to do this? After playing around with it for a bit, I produced the following solution, which appears to work correctly and is quite brief. Are there some alternatives? Are there drawbacks to using this approach that I should keep in mind? class lazyload: def __init__(self,FILE): self.FILE = FILE self.F = None def __getattr__(self,name): if not self.F: print "loading %s" % self.FILE self.F = loadfile(self.FILE) return object.__getattribute__(self.F, name) What might be even better is if something like this worked: class lazyload: def __init__(self,FILE): self.FILE = FILE def __getattr__(self,name): self = loadfile(self.FILE) # this never gets called again # since self is no longer a # lazyload instance return object.__getattribute__(self, name) But this doesn't work because self is local. It actually ends up calling loadfile every time you do anything.

    Read the article

  • Performance Problems with Django's F() Object

    - by JayhawksFan93
    Has anyone else noticed performance issues using Django's F() object? I am running Windows XP SP3 and developing against the Django trunk. A snippet of the models I'm using and the query I'm building are below. When I have the F() object in place, each call to a QuerySet method (e.g. filter, exclude, order_by, distinct, etc.) takes approximately 2 seconds, but when I comment out the F() clause the calls are sub-second. I had a co-worker test it on his Ubuntu machine, and he is not experiencing the same performance issues I am with the F() clause. Anyone else seeing this behavior? class Move (models.Model): state_meaning = models.CharField( max_length=16, db_index=True, blank=True, default='' ) drop = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_move_drop' ) class Split(models.Model): state_meaning = models.CharField( max_length=16, db_index=True, blank=True, default='' ) move = models.ForeignKey( Move, related_name='splits' ) pickup = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_split_pickup' ) pickup_date = models.DateField( null=True, default=None ) drop = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_split_drop' ) drop_date = models.DateField( null=True, default=None, db_index=True ) def get_splits(begin_date, end_date): qs = Split.objects \ .filter(state_meaning__in=['INPROGRESS','FULFILLED'], drop=F('move__drop'), # <<< the line in question pickup_date__lte=end_date) elapsed = timer.clock() - start print 'qs1 took %.3f' % elapsed start = timer.clock() qs = qs.filter(Q(drop_date__gte=begin_date) | Q(drop_date__isnull=True)) elapsed = timer.clock() - start print 'qs2 took %.3f' % elapsed start = timer.clock() qs = qs.exclude(move__state_meaning='UNFULFILLED') elapsed = timer.clock() - start print 'qs3 took %.3f' % elapsed start = timer.clock() qs = qs.order_by('pickup_date', 'drop_date') elapsed = timer.clock() - start print 'qs7 took %.3f' % elapsed start = timer.clock() qs = qs.distinct() elapsed = timer.clock() - start print 'qs8 took %.3f' % elapsed

    Read the article

  • How to write curiously recurring templates with more than 2 layers of inheritance?

    - by Kyle
    All the material I've read on Curiously Recurring Template Pattern seems to one layer of inheritance, ie Base and Derived : Base<Derived>. What if I want to take it one step further? #include <iostream> using std::cout; template<typename LowestDerivedClass> class A { public: LowestDerivedClass& get() { return *static_cast<LowestDerivedClass*>(this); } void print() { cout << "A\n"; } }; template<typename LowestDerivedClass> class B : public A<LowestDerivedClass> { public: void print() { cout << "B\n"; } }; class C : public B<C> { public: void print() { cout << "C\n"; } }; int main() { C c; c.get().print(); // B b; // Intentionally bad syntax, // b.get().print(); // to demonstrate what I'm trying to accomplish return 0; } How can I rewrite this code to compile without errors (and output "C\nB\n")?

    Read the article

  • Good practice of using list of function in Python

    - by riskio
    I am pretty new to python and I discovered by myself that I can create a list of function and call with a for loop. example: def a(args): print "A" def b(args): print "B" def c(args): print "C " + str(args) functions = [a,b,c] for i in functions: i(1) So, my question is: is there any good practice or elegant way to use list of functions and what is a good use of all this? (do have a particular name the "list of functions"?) thank you

    Read the article

  • Parsing XHTML results from Bing

    - by Nir
    Hello, i am trying to parse received search queries from bing search engines which are received in xhtml in java. I am using sax XmlReader to read the results but i keep on getting errors. here is my code-this one is for the hadler of the reader: import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XHTMLHandler extends DefaultHandler{ public XHTMLHandler() { super(); } public void startDocument () { System.out.println("Start document"); } public void endDocument () { System.out.println("End document"); } public void startElement (String uri, String name,String qName, Attributes atts) { if ("".equals (uri)) System.out.println("Start element: " + qName); else System.out.println("Start element: {" + uri + "}" + name); } public void endElement (String uri, String name, String qName) { if ("".equals (uri)) System.out.println("End element: " + qName); else System.out.println("End element: {" + uri + "}" + name); } public void startPrefixMapping (String prefix, String uri) throws SAXException { } public void endPrefixMapping (String prefix) throws SAXException { } public void characters (char ch[], int start, int length) { System.out.print("Characters: \""); for (int i = start; i < start + length; i++) { switch (ch[i]) { case '\\': System.out.print("\\\\"); break; case '"': System.out.print("\\\""); break; case '\n': System.out.print("\\n"); break; case '\r': System.out.print("\\r"); break; case '\t': System.out.print("\\t"); break; default: System.out.print(ch[i]); break; } } System.out.print("\"\n"); } } and this is the program itself: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpRetryException; import java.net.HttpURLConnection; import java.net.URL; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class Searching { private String m_urlBingSearch = "http://www.bing.com/search?q="; private HttpURLConnection m_httpCon; private OutputStreamWriter m_streamWriter; //private BufferedReader m_bufferReader; private URL m_serverAdress; private StringBuilder sb; private String m_line; private InputSource m_inputSrc; public Searching() { m_httpCon = null; m_streamWriter = null; //m_bufferReader = null; m_serverAdress = null; sb = null; m_line = new String(); } public void SearchBing(String searchPrms) throws SAXException,IOException { //set up connection sb = new StringBuilder(); sb.append(m_urlBingSearch); sb.append(searchPrms); m_serverAdress = new URL(sb.toString()); m_httpCon = (HttpURLConnection)m_serverAdress.openConnection(); m_httpCon.setRequestMethod("GET"); m_httpCon.setDoOutput(true); m_httpCon.setConnectTimeout(10000); m_httpCon.connect(); //m_streamWriter = new OutputStreamWriter(m_httpCon.getOutputStream()); //m_bufferReader = new BufferedReader(new InputStreamReader(m_httpCon.getInputStream())); XMLReader reader = XMLReaderFactory.createXMLReader(); XHTMLHandler handle = new XHTMLHandler(); reader.setContentHandler(handle); reader.setErrorHandler(handle); //reader.startPrefixMapping("html", "http://www.w3.org/1999/xhtml"); handle.startPrefixMapping("html", "http://www.w3.org/1999/xhtml"); m_inputSrc = new InputSource(m_httpCon.getInputStream()); reader.parse(m_inputSrc); m_httpCon.disconnect(); } public static void main(String [] args) throws SAXException,IOException { Searching s = new Searching(); s.SearchBing("beatles"); } } this is my error message: Exception in thread "main" java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source) at Searching.SearchBing(Searching.java:57) at Searching.main(Searching.java:65) can someone please help? i think it has something to do with dtd but i don't know hot to fix it

    Read the article

  • Is there a difference between `==` and `is` in python?

    - by Bernard
    My Google-fu has failed me. In Python, are these: n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' two tests for equality equivalent (ha!)? Does this hold true for objects where you would be comparing instances (a list say)? Okay, so this kind of answers my question: l = list() l.append(1) if l == [1]: print 'Yay!' # Holds true, but... if l is [1]: print 'Yay!' # Doesn't. So == tests value where is tests to see if they are the same object?

    Read the article

  • python multiprocessing.Process.Manager not producing consistent results?

    - by COpython
    I've written the following code to illustrate the problem I'm seeing. I'm trying to use a Process.Manager.list() to keep track of a list and increment random indices of that list. Each time there are 100 processes spawned, and each process increments a random index of the list by 1. Therefore, one would expect the SUM of the resulting list to be the same each time, correct? I get something between 203 and 205. from multiprocessing import Process, Manager import random class MyProc(Process): def __init__(self, A): Process.__init__(self) self.A = A def run(self): i = random.randint(0, len(self.A)-1) self.A[i] = self.A[i] + 1 if __name__ == '__main__': procs = [] M = Manager() a = M.list(range(15)) print('A: {0}'.format(a)) print('sum(A) = {0}'.format(sum(a))) for i in range(100): procs.append(MyProc(a)) map(lambda x: x.start(), procs) map(lambda x: x.join(), procs) print('A: {0}'.format(a)) print('sum(A) = {0}'.format(sum(a)))

    Read the article

  • Archive tar files to a different location inperl

    - by user314261
    Hi, I am a newbee in Perl. I am reading a directory having some archive files and uncompressing the archive files one by one. Everything seems well however the files are getting uncompressed in the folder which has the main perl code module which is running the sub modules. I want the archive to be generated in the folder I specify. This is my code: sub ExtractFile { #Read the folder which was copied in the output path recursively and extract if any file is compressed my $dirpath = $_[0]; opendir(D, "$dirpath") || die "Can't open dir $dirpath: $!\n"; my @list = readdir(D); closedir(D); foreach my $f (@list) { print " \$f = $f"; if(-f $dirpath."/$f") { #print " File in directory $dirpath \n ";#is \$f = $f\n"; my($file_name, $file_dirname,$filetype)= fileparse($f,qr{\..*}); #print " \nThe file extension is $filetype"; #print " \nThe file name is is $file_name"; # If compressed file then extract the file if($filetype eq ".tar" or $filetype eq ".tzr.gz") { my $arch_file = $dirpath."/$f"; print "\n file to be extracted is $arch_file"; my $tar = Archive::Tar->new($arch_file); #$tar->extract() or die ("Cannot extract file $arch_file"); #mkdir($dirpath."/$file_name"); $tar->extract_file($arch_file,$dirpath."/$file_name" ) or die ("Cannot extract file $arch_file"); } } if(-d $dirpath."/$f") { if($f eq "." or $f eq "..") { next; } print " Directory\n";# is $f"; ExtractFile($dirpath."/$f"); } } } The method ExtractFile is called recursively to loop all the archives. When using $tar-extract() it uncompresses in the folder which calls this metohd. when I use $tar-extract_file($arch_file,$dirpath."/$file_name" ) I get an error : No such file in archive: '/home/fsang/dante/workspace/output/s.tar' at /home/fsang/dante/lib/Extraction.pm line 80 Please help I have checked that path and input output there is no issue with it. Seems some usage problem I am not aware of for $tar-extract_file(). Many thanks for anyone resolving this issue. Regards, Sakshi

    Read the article

  • finding a solution to a giving maze txt.file

    - by alberto
    how can i fix this program, the problem is when it print out the coordinate it give me a 7 for the start and finish, i would appreciated you help, thanks start = (len(data)) finish = (len(data)) pos= [] for i in range(len(pos)): for j in range(len(pos[i])): if pos[i][j] == "S": start=(i,j) elif pos[i][j] == "F": finish=(i,j) print "S found in",start, print "\nF found in",finish,"\n"

    Read the article

< Previous Page | 67 68 69 70 71 72 73 74 75 76 77 78  | Next Page >