Search Results

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

Page 65/782 | < Previous Page | 61 62 63 64 65 66 67 68 69 70 71 72  | Next Page >

  • How to read Unicode characters from command-line arguments in Python on Windows

    - by Craig McQueen
    I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode? Example code: argv.py import sys first_arg = sys.argv[1] print first_arg print type(first_arg) print first_arg.encode("hex") print open(first_arg) On my PC set up for Japanese code page, I get: C:\temp>argv.py "PC·??????08.09.24.doc" PC·??????08.09.24.doc <type 'str'> 50438145835c83748367905c90bf8f9130382e30392e32342e646f63 <open file 'PC·??????08.09.24.doc', mode 'r' at 0x00917D90> That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character set—the final "open" call fails: C:\temp>argv.py Jörgen.txt Jorgen.txt <type 'str'> 4a6f7267656e2e747874 Traceback (most recent call last): File "C:\temp\argv.py", line 7, in <module> print open(first_arg) IOError: [Errno 2] No such file or directory: 'Jorgen.txt' Note—I'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives sys.argv as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support). Update: A few answers have said I should decode according to whatever the sys.argv is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable. Here's the use case that gives me grief: I have enabled drag-and-drop of files onto .py files in Windows Explorer. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding. There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.

    Read the article

  • Perl unpack in list context

    - by drewk
    A common 'Perlism' is generating a list as something to loop over in this form: for($str=~/./g) { print "the next character from \"$str\"=$_\n"; } In this case the global match regex returns a list that is one character in turn from the string $str, and assigns that value to $_ Instead of a regex, split can be used in the same way or 'a'..'z', map, etc. I am investigating unpack to generate a field by field interpretation of a string. I have always found unpack to be less straightforward to the way my brain works, and I have never really dug that deeply into it. As a simple case, I want to generate a list that is one character in each element from a string using unpack (yes -- I know I can do it with split(//,$str) and /./g but I really want to see if unpack can be used this way...) Obviously, I can use a field list for unpack that is unpack("A1" x length($str), $str) but is there some other way that kinda looks like globbing? ie, can I call unpack(some_format,$str) either in list context or in a loop such that unpack will return the next group of character in the format group until $str is exausted? I have read The Perl 5.12 Pack pod and the Perl 5.12 pack tutorial and the Perkmonks tutorial Here is the sample code: #!/usr/bin/perl use warnings; use strict; my $str=join('',('a'..'z', 'A'..'Z')); #the alphabet... $str=~s/(.{1,3})/$1 /g; #...in groups of three print "str=$str\n\n"; for ($str=~/./g) { print "regex: = $_\n"; } for(split(//,$str)) { print "split: \$_=$_\n"; } for(unpack("A1" x length($str), $str)) { print "unpack: \$_=$_\n"; }

    Read the article

  • how to get Celsius as output from LM335Z with arduino?

    - by wizztjh
    the firstsensor is my lm335z output. int firstSensor = 0; int secondSensor = 0; int thirdSensor = 0; int inByte = 0; void setup() { Serial.begin(9600); establishContact(); // send a byte to establish contact until receiver responds } void loop() { if (Serial.available() > 0) { inByte = Serial.read(); firstSensor = analogRead(0); delay(10); secondSensor = analogRead(1); thirdSensor = analogRead(2); Serial.print(firstSensor, DEC); Serial.print(","); Serial.print(secondSensor, DEC); Serial.print(","); Serial.println(thirdSensor, DEC); } } void establishContact() { }

    Read the article

  • Spikes in Socket Performance

    - by Harun Prasad
    We are facing random spikes in high throughput transaction processing system using sockets for IPC. Below is the setup used for the run: The client opens and closes new connection for every transaction, and there are 4 exchanges between the server and the client. We have disabled the TIME_WAIT, by setting the socket linger (SO_LINGER) option via getsockopt as we thought that the spikes were caused due to the sockets waiting in TIME_WAIT. There is no processing done for the transaction. Only messages are passed. OS used Centos 5.4 The average round trip time is around 3 milli seconds, but some times the round trip time ranges from 100 milli seconds to couple of seconds. Steps used for Execution and Measurement and output Starting the server $ python sockServerLinger.py /dev/null & Starting the client to post 1 million transactions to the server. And logs the time for a transaction in the client.log file. $ python sockClient.py 1000000 client.log Once the execution finishes the following command will show the execution time greater than 100 milliseconds in the format <line_number>:<execution_time>. $ grep -n "0.[1-9]" client.log | less Below is the example code for Server and Client. Server # File: sockServerLinger.py import socket, traceback,time import struct host = '' port = 9999 l_onoff = 1 l_linger = 0 lingeropt = struct.pack('ii', l_onoff, l_linger) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, lingeropt) s.bind((host, port)) s.listen(1) while 1: try: clientsock, clientaddr = s.accept() print "Got connection from", clientsock.getpeername() data = clientsock.recv(1024*1024*10) #print "asdasd",data numsent=clientsock.send(data) data1 = clientsock.recv(1024*1024*10) numsent=clientsock.send(data) ret = 1 while(ret>0): data1 = clientsock.recv(1024*1024*10) ret = len(data) clientsock.close() except KeyboardInterrupt: raise except: print traceback.print_exc() continue Client # File: sockClient.py import socket, traceback,sys import time i = 0 while 1: try: st = time.time() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) while (s.connect_ex(('127.0.0.1',9999)) != 0): continue numsent=s.send("asd"*1000) response = s.recv(6000) numsent=s.send("asd"*1000) response = s.recv(6000) i+=1 if i == int(sys.argv[1]): break except KeyboardInterrupt: raise except: print "in exec:::::::::::::",traceback.print_exc() continue print time.time() -st

    Read the article

  • Suppressing NSLog statements for release?

    - by fuzzygoat
    I wonder if someone could help me setup a number of NSLog statements so they print to console when executing in "Debug Mode" but don't print in "Release Mode". I understand I need to add something like DEBUG = 1 to the debug config in Xcode but I can't find where. Also how do I utilise this in my code? NSLog(@"Print Always"); if(DEBUG) NSLog(@"Print only in debug"); Is there a simple way of doing this? EDIT: I tried following this but when I entered either: OTHER_CFLAGS or GCC_PREPROCESSOR_DEFINITIONS Xcode informed me that "theres already another key named .... " gary

    Read the article

  • 301 versus inline rewrites

    - by Kristoffer S Hansen
    I'm in the process of adding 'pretty' URLs to an existing CMS, the menu is auto generated and the new 'pretty' URLs are to be handled independently as a seperate module. The auto-generated menu allways has URLs that look like this index.php?menu_id=n which ofcourse we would like to see as eg. /news or /products I'm currently at the point where I have to decide if I'm going to rewrite all output of the current system or simply put in a hook where I redirect to the 'pretty' URL. To put it differently, should i connect to the database, fetch all 'pretty' URLs, run through the existing output from WYSIWYG's, news modules, forums etc. and do some str_replace or other string manipulation (which I think would be a rather tedious and boring process), or should I simply hook in and throw a 301 redirecting index.php?menu_id=3 to /news will Google (or other search engines) penalize me for having 301's in the menus?

    Read the article

  • Use the Django ORM in a standalone script (again)

    - by Rishabh Manocha
    I'm trying to use the Django ORM in some standalone screen scraping scripts. I know this question has been asked before, but I'm unable to figure out a good solution for my particular problem. I have a Django project with defined models. What I would like to do is use these models and the ORM in my scraping script. My directory structure is something like this: project scrape #scraping scripts ... test.py web django_project settings.py ... #Django files I tried doing the following in project/scrape/test.py: print os.path.join(os.path.abspath('..'), 'web', 'django_project') sys.path.append(os.path.join(os.path.abspath('..'), 'web', 'django_project')) print sys.path print "-------" os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings' #print os.environ from django_project.myapp.models import MyModel print MyModel.objects.count() However, I get an ImportError when I try to run test.py: Traceback (most recent call last): File "test.py", line 12, in <module> from django_project.myapp.models import MyModel ImportError: No module named django_project.myapp.models One solution I found around this problem is to create a symbolic link to ../web/govcheck in the scrape folder: :scrape rmanocha$ ln -s ../web/govcheck ./govcheck With this, I can then run test.py just fine. However, this seems like a hack, and more importantly, is not very portable (I will have to create this symbolic link everywhere I run this code). So, I was wondering if anyone has any better solutions for my problem?

    Read the article

  • printarea function not working

    - by daljeet
    I am trying to print a particular area on my webpage by using jQuery printarea() function. It doesn't work and returns an error. Error return (media.toLowerCase() == "" || media.toLowerCase() == "print") jQuery function printDiv() { $('#dvTokenArea').printArea(); }? <div id="dvTokenArea" runat="server"> <asp:Label ID="lblTokenNumber" runat="server" Text="Print ME !!!!!!!!!!!!"> </asp:Label> </div> <asp:Button ID="btnPrintToken" runat="server" Text="Print" OnClientClick="javascript:printDiv();" />

    Read the article

  • Getting XQuery [modify()]: Top-level attribute nodes are not supported error while modifying xml

    - by sam
    DECLARE @mycur CURSOR DECLARE @id int DECLARE @ParentNodeName varchar(max) DECLARE @NodeName varchar(max) DECLARE @NodeText varchar(max) SET @mycur = CURSOR FOR SELECT * FROM @temp OPEN @mycur FETCH NEXT FROM @mycur INTO @id,@ParentNodeName,@NodeName,@NodeText WHILE @@FETCH_STATUS = 0 BEGIN PRINT @id -- sample statements PRINT @ParentNodeName PRINT @NodeName SET @x.modify (' insert attribute status {sql:variable("@status")} as first into (/@ParentNodeName/@NodeName/child::*[position()=sql:variable("@status")])[1] ') FETCH NEXT FROM @mycur INTO @id,@ParentNodeName,@NodeName,@NodeText END DEALLOCATE @mycur Any idea why I am getting this error as query works fine if I manually insert path

    Read the article

  • what is the problem in ATM machine program

    - by Have alook
    in this prigramm when the account number is uncorrect it should display a message to write a gain but when i wrote a gain by corrrect account number always it diplay the result of first account also there is aproblem in PIN number ,the use have only three time to try if he enter wrong numbe and if enter three times wrong it should stop the program but it complete to the last part I dont know why pleas help me this is my proram import java.util.*; class assignment2_70307{ public static void main(String args[]){ Scanner m=new Scanner(System.in); int i; i=0; int [] accountNo =new int[7] ;//declear the Accont number array accountNo [0] =1111; accountNo [1] =2222; accountNo [2] =3333; accountNo [3] =4444; accountNo [4] =5555; accountNo [5] =6666; accountNo [6] =7777; int [] PINno =new int[7]; //declear the PIN number array PINno [0] =1234; PINno [1] =5678; PINno [2] =9874; PINno [3] =6523; PINno [4] =1236; PINno [5] =4569; PINno [6] =8521; String [] CusomerNm =new String[7]; //dclear the customer name CusomerNm [0] ="Ali"; CusomerNm [1] ="Ahmed"; CusomerNm [2] ="Amal"; CusomerNm [3] ="Said"; CusomerNm [4] ="Rashid"; CusomerNm [5] ="Fatema"; CusomerNm [6] ="Mariam"; double [] Balance =new double[7]; //declear the Balane array Balance [0] =100.50; Balance [1] =5123.00; Balance [2] =12.00; Balance [3] =4569.00; Balance [4] =1020.25; Balance [5] =0.00; Balance [6] =44.10; System.out.println("Wellcome to mini ATM Machine"); int accountno,pino; accountno=0; pino=0; System.out.println("Please Enter your account number: or -1 to stop" ); accountno=m.nextInt(); if (accountno==accountNo[0]) System.out.print("Customer Name: "+CusomerNm [0]+ "\n" ); else if (accountno==accountNo[1]) System.out.print("Customer Name: "+CusomerNm [1]+ "\n" ); else if (accountno==accountNo[2]) System.out.print("Customer Name: "+CusomerNm [2]+ "\n" ); else if (accountno==accountNo[3]) System.out.print("Customer Name: "+CusomerNm [3]+ "\n" ); else if (accountno==accountNo[4]) System.out.print("Customer Name: "+CusomerNm [4]+ "\n" ); else if (accountno==accountNo[5]) System.out.print("Customer Name: "+CusomerNm [5]+ "\n" ); else if (accountno==accountNo[6]) System.out.print("Customer Name: "+CusomerNm [6]+ "\n" ); // else if (accountNo[0]==-1) //break; else { System.out.println("The account dose not exist,please try again"); //accountNo[i]=m.nextInt(); accountno=m.nextInt(); if(accountNo[i]==accountno) System.out.println("Customer Name: "+CusomerNm[i] ); else System.out.println("The account dose not exist,please try again"); accountno=m.nextInt(); System.out.println("Customer Name: "+CusomerNm[i] ); } System.out.print("Enter your PIN number:"); PINno[i]=m.nextInt(); if(PINno[i]==1234) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [0]+ "Rial"); //return 0; } else if(PINno[i]==5678) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [1]+ "Rial"); // return 1; } else if(PINno[i]==9874) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [2]+ "Rial"); // return 2; } else if(PINno[i]==6523) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [3]+ "Rial"); // return 3; } else if(PINno[i]==1236) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [4]+ "Rial"); // return 4; } else if(PINno[i]==4569) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [5]+ "Rial"); // return 5; } else if(PINno[i]==8521) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [6]+ "Rial"); // return 6; } else {System.out.println("try again"); //return 7; //if its wrong u can enter PIN number three times only for( i=0;i<2;i++) { System.out.println("enter pin again"); PINno[i]=m.nextInt(); String ss; //ss = "MAnal"; // goto ss ; } } //ss = "m"; int x; x=0; System.out.println("Enter the option from the list /n 1.Deposit /n 2.Withdraw /n 3.Balance"); x=m.nextInt(); double balance,amount; balance=0; amount=0; double deposit ,Withdraw; deposit=0; Withdraw=0; if (x==1){ System.out.println("Enter the amont you want to deposit:"+amount); amount=m.nextDouble(); Balance [i]=Balance [i]+amount; System.out.println("your balance ="+Balance [i]); } else if (x==2) { System.out.println("Enter the amont to withdraw:"); amount=m.nextDouble(); System.out.print(amount); if(Withdraw<=Balance [i]) { Balance [i]=Balance [i]-amount; System.out.println("your balance ="+Balance [i]); } else { System.out.println("sorry,please enter the amont less or equal your balance"); System.out.println(Balance [i]); } } else { if(x==1) { Balance [i]=Balance [i]+deposit; System.out.println("your current balance is :" +Balance [i]); } else { Balance [i]=Balance [i]-Withdraw; System.out.println("your current balance is :"+Balance [i]); } System.out.println("Thank you"); // err() } } }

    Read the article

  • How to include multiple tables programmaticaly into a Sweave document using R

    - by PaulHurleyuk
    Hello, I want to have a sweave document that will include a variable number of tables in. I thought the example below would work, but it doesn't. I want to loop over the list foo and print each element as it's own table. % \documentclass[a4paper]{article} \usepackage[OT1]{fontenc} \usepackage{longtable} \usepackage{geometry} \usepackage{Sweave} \geometry{left=1.25in, right=1.25in, top=1in, bottom=1in} \listfiles \begin{document} <<label=start, echo=FALSE, include=FALSE>>= startt<-proc.time()[3] library(RODBC) library(psych) library(xtable) library(plyr) library(ggplot2) options(width=80) #Produce some example data, here I'm creating some dummy dataframes and putting them in a list foo<-list() foo[[1]]<-data.frame(GRP=c(rep("AA",10), rep("Aa",10), rep("aa",10)), X1=rnorm(30), X2=rnorm(30,5,2)) foo[[2]]<-data.frame(GRP=c(rep("BB",10), rep("bB",10), rep("BB",10)), X1=rnorm(30), X2=rnorm(30,5,2)) foo[[3]]<-data.frame(GRP=c(rep("CC",12), rep("cc",18)), X1=rnorm(30), X2=rnorm(30,5,2)) foo[[4]]<-data.frame(GRP=c(rep("DD",10), rep("Dd",10), rep("dd",10)), X1=rnorm(30), X2=rnorm(30,5,2)) @ \title{Docuemnt to test putting a variable number of tables into a sweave Document} \author{"Paul Hurley"} \maketitle \section{Text} This document was created on \today, with \Sexpr{print(version$version.string)} running on a \Sexpr{print(version$platform)} platform. It took approx \input{time} sec to process. <<label=test, echo=FALSE, results=tex>>= cat("Foo") @ that was a test, so is this <<label=table1test, echo=FALSE, results=tex>>= print(xtable(foo[[1]])) @ \newpage \subsection{Tables} <<label=Tables, echo=FALSE, results=tex>>= for(i in seq(foo)){ cat("\n") cat(paste("Table_",i,sep="")) cat("\n") print(xtable(foo[[i]])) cat("\n") } #cat("<<label=endofTables>>= ") @ <<label=bye, include=FALSE, echo=FALSE>>= endt<-proc.time()[3] elapsedtime<-as.numeric(endt-startt) @ <<label=elapsed, include=FALSE, echo=FALSE>>= fileConn<-file("time.tex", "wt") writeLines(as.character(elapsedtime), fileConn) close(fileConn) @ \end{document} Here, the table1test chunk works as expected, and produced a table based on the dataframe in foo[[1]], however the loop only produces Table(underscore)1.... Any ideas what I'm doing wrong ?

    Read the article

  • Jasper report-> page footer question

    - by raj
    If page footer data 4000 character then I want to print on first pager footer from 0 to 1750 character and next pager footer I want to print from 1751 to 3500 and next page I want to print from 3501 to 4000 characters.Can anybody help me to solve this problem. Thanks, Raj

    Read the article

  • Why isn't my operator overloading working properly?

    - by Mithrax
    I have the following Polynomial class I'm working on: #include <iostream> using namespace std; class Polynomial { //define private member functions private: int coef[100]; // array of coefficients // coef[0] would hold all coefficients of x^0 // coef[1] would hold all x^1 // coef[n] = x^n ... int deg; // degree of polynomial (0 for the zero polynomial) //define public member functions public: Polynomial::Polynomial() //default constructor { for ( int i = 0; i < 100; i++ ) { coef[i] = 0; } } void set ( int a , int b ) //setter function { //coef = new Polynomial[b+1]; coef[b] = a; deg = degree(); } int degree() { int d = 0; for ( int i = 0; i < 100; i++ ) if ( coef[i] != 0 ) d = i; return d; } void print() { for ( int i = 99; i >= 0; i-- ) { if ( coef[i] != 0 ) { cout << coef[i] << "x^" << i << " "; } } } // use Horner's method to compute and return the polynomial evaluated at x int evaluate ( int x ) { int p = 0; for ( int i = deg; i >= 0; i-- ) p = coef[i] + ( x * p ); return p; } // differentiate this polynomial and return it Polynomial differentiate() { if ( deg == 0 ) { Polynomial t; t.set ( 0, 0 ); return t; } Polynomial deriv;// = new Polynomial ( 0, deg - 1 ); deriv.deg = deg - 1; for ( int i = 0; i < deg; i++ ) deriv.coef[i] = ( i + 1 ) * coef[i + 1]; return deriv; } Polynomial Polynomial::operator + ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) c.coef[i] += a.coef[i]; for ( int i = 0; i <= b.deg; i++ ) c.coef[i] += b.coef[i]; c.deg = c.degree(); return c; } Polynomial Polynomial::operator += ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) c.coef[i] += a.coef[i]; for ( int i = 0; i <= b.deg; i++ ) c.coef[i] += b.coef[i]; c.deg = c.degree(); for ( int i = 0; i < 100; i++) a.coef[i] = c.coef[i]; a.deg = a.degree(); return a; } Polynomial Polynomial::operator -= ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) c.coef[i] += a.coef[i]; for ( int i = 0; i <= b.deg; i++ ) c.coef[i] -= b.coef[i]; c.deg = c.degree(); for ( int i = 0; i < 100; i++) a.coef[i] = c.coef[i]; a.deg = a.degree(); return a; } Polynomial Polynomial::operator *= ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) for ( int j = 0; j <= b.deg; j++ ) c.coef[i+j] += ( a.coef[i] * b.coef[j] ); c.deg = c.degree(); for ( int i = 0; i < 100; i++) a.coef[i] = c.coef[i]; a.deg = a.degree(); return a; } Polynomial Polynomial::operator - ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) c.coef[i] += a.coef[i]; for ( int i = 0; i <= b.deg; i++ ) c.coef[i] -= b.coef[i]; c.deg = c.degree(); return c; } Polynomial Polynomial::operator * ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) for ( int j = 0; j <= b.deg; j++ ) c.coef[i+j] += ( a.coef[i] * b.coef[j] ); c.deg = c.degree(); return c; } }; int main() { Polynomial a, b, c, d; a.set ( 7, 4 ); //7x^4 a.set ( 1, 2 ); //x^2 b.set ( 6, 3 ); //6x^3 b.set ( -3, 2 ); //-3x^2 c = a - b; // (7x^4 + x^2) - (6x^3 - 3x^2) a -= b; c.print(); cout << "\n"; a.print(); cout << "\n"; c = a * b; // (7x^4 + x^2) * (6x^3 - 3x^2) c.print(); cout << "\n"; d = c.differentiate().differentiate(); d.print(); cout << "\n"; cout << c.evaluate ( 2 ); //substitue x with 2 cin.get(); } Now, I have the "-" operator overloaded and it works fine: Polynomial Polynomial::operator - ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) c.coef[i] += a.coef[i]; for ( int i = 0; i <= b.deg; i++ ) c.coef[i] -= b.coef[i]; c.deg = c.degree(); return c; } However, I'm having difficulty with my "-=" operator: Polynomial Polynomial::operator -= ( Polynomial b ) { Polynomial a = *this; //a is the poly on the L.H.S Polynomial c; for ( int i = 0; i <= a.deg; i++ ) c.coef[i] += a.coef[i]; for ( int i = 0; i <= b.deg; i++ ) c.coef[i] -= b.coef[i]; c.deg = c.degree(); // overwrite value of 'a' with the newly computed 'c' before returning 'a' for ( int i = 0; i < 100; i++) a.coef[i] = c.coef[i]; a.deg = a.degree(); return a; } I just slightly modified my "-" operator method to overwrite the value in 'a' and return 'a', and just use the 'c' polynomial as a temp. I've put in some debug print statement and I confirm that at the time of computation, both: c = a - b; and a -= b; are computed to the same value. However, when I go to print them, their results are different: Polynomial a, b; a.set ( 7, 4 ); //7x^4 a.set ( 1, 2 ); //x^2 b.set ( 6, 3 ); //6x^3 b.set ( -3, 2 ); //-3x^2 c = a - b; // (7x^4 + x^2) - (6x^3 - 3x^2) a -= b; c.print(); cout << "\n"; a.print(); cout << "\n"; Result: 7x^4 -6x^3 4x^2 7x^4 1x^2 Why is my c = a - b and a -= b giving me different results when I go to print them?

    Read the article

  • How can you do Co-routines using C#?

    - by WeNeedAnswers
    In python the yield keyword can be used in both push and pull contexts, I know how to do the pull context in c# but how would I achieve the push. I post the code I am trying to replicate in c# from python: def coroutine(func): def start(*args,**kwargs): cr = func(*args,**kwargs) cr.next() return cr return start @coroutine def grep(pattern): print "Looking for %s" % pattern try: while True: line = (yield) if pattern in line: print line, except GeneratorExit: print "Going away. Goodbye"

    Read the article

  • how python http request and response works

    - by Apache
    hi expert, i'm newbie for python, i use to learn using sample, i use python to scan wifi to get ssid, and now i want to send the data to the server, then i did as follow import httplib,urllib params = urllib.urlencode({"ssid":"guest"}) headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"} conn=httplib.HTTPConnection("http://223.56.124.58:8080/wireless") conn.request("POST","data",params,headers) response = conn.getresponse() print "Response" print response.status print "-----" print response.reason data = response.read() print data conn.close() but when execute the code i'm getting as follow root@dave-laptop:~# python http.py Traceback (most recent call last): File "http.py", line 9, in conn.request("POST","http://202.45.139.58:8080/ppod-web",params,headers) File "/usr/lib/python2.6/httplib.py", line 898, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.6/httplib.py", line 935, in _send_request self.endheaders() File "/usr/lib/python2.6/httplib.py", line 892, in endheaders self._send_output() File "/usr/lib/python2.6/httplib.py", line 764, in _send_output self.send(msg) File "/usr/lib/python2.6/httplib.py", line 723, in send self.connect() File "/usr/lib/python2.6/httplib.py", line 704, in connect self.timeout) File "/usr/lib/python2.6/socket.py", line 500, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno -2] Name or service not known can anyone help me the code should be like this when rum in the url http://223.56.124.58:8080/wireless?data={"wifi":{"ssid":"guest","rssi","80"}} how to set like this or other way to do this to send to the server thanks

    Read the article

  • Address of function is not actual code address

    - by mrjoltcola
    Debugging some code in Visual Studio 2008 (C++), I noticed that the address in my function pointer variable is not the actual address of the function itself. This is an extern "C" function. int main() { void (*printaddr)(const char *) = &print; // debug shows printaddr == 0x013C1429 } Address: 0x013C4F10 void print() { ... } The disassembly of taking the function address is: void (*printaddr)(const char *) = &print; 013C7465 C7 45 BC 29 14 3C 01 mov dword ptr [printaddr],offset print (13C1429h) What am I missing?

    Read the article

  • Convert sqlalchemy row object to python dict

    - by Anurag Uniyal
    or a simple way to iterate over columnName, value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker print "sqlalchemy version:",sqlalchemy.__version__ engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() users_table = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String), ) metadata.create_all(engine) class User(declarative_base()): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) def __init__(self, name): self.name = name Session = sessionmaker(bind=engine) session = Session() user1 = User("anurag") session.add(user1) session.commit() # uncommenting next line throws exception 'TypeError: 'User' object is not iterable' #print dict(user1) # this one also throws 'TypeError: 'User' object is not iterable' for u in session.query(User).all(): print dict(u) Running this code on my system outputs: sqlalchemy version: 0.5.6 Traceback (most recent call last): File "untitled-1.py", line 37, in <module> print dict(u) TypeError: 'User' object is not iterable

    Read the article

  • Python sudoku programming

    - by trevor
    I need your help on this. I have this program and I must finish it. It's missing 3 parts. Here is the program I'm working with: import copy def display(A): if A: for i in range(9): for j in range(9): if type(A[i][j]) == type([]): print A[i][j][0], else: print A[i][j], print print else: print A def has_conflict(A): for i in range(9): for j in range(9): for (x,y) in get_neighbors(i,j): if len(A[i][j])==1 and A[i][j]==A[x][y]: return True return False # HERE ARE THE PARTS THAT REQUIRE HELP!!!! def get_neighbors(x,y): return [] def update(A, i, j, value): return [] def solve(A): return [] # ENDS PARTS THAT REQUIRE HELP!!!! A = [] infile = open('puzzle1.txt', 'r') for i in range(9): A += [[]] for j in range(9): num = int(infile.read(2)) if num: A[i] += [[num]] else: A[i] += [[1,2,3,4,5,6,7,8,9]] for i in range(9): for j in range(9): if len(A[i][j])==1: A = update(A, i,j, A[i][j][0]) if A==[]: break if A==[]: break if A<>[]: A = solve(A) display(A) I need to solve the stuff formerly in bold letters, now explicitly marked in the code, specifically - get_neighbors(): - update(): - solve(): Thank you for your time and help.

    Read the article

  • slicing behaviour question of a list of lists

    - by Lex
    I got a function like def f(): ... ... return [list1, list2] this returns a list of lists [[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]] now when I do the following: for i in range(0,2):print f()[i][0:10] it works and print the lists sliced but if i do print f()[0:2][0:10] then it prints the lists ignoring the [0:10] slicing. Is there any way to make the second form work or do I have to loop every time to get the desired result?

    Read the article

  • Optimizing code using PIL

    - by freakazo
    Firstly sorry for the long piece of code pasted below. This is my first time actually having to worry about performance of an application so I haven't really ever worried about performance. This piece of code pretty much searches for an image inside another image, it takes 30 seconds to run on my computer, converting the images to greyscale and other changes shaved of 15 seconds, I need another 15 shaved off. I did read a bunch of pages and looked at examples but I couldn't find the same problems in my code. So any help would be greatly appreciated. From the looks of it (cProfile) 25 seconds is spent within the Image module, and only 5 seconds in my code. from PIL import Image import os, ImageGrab, pdb, time, win32api, win32con import cProfile def GetImage(name): name = name + '.bmp' try: print(os.path.join(os.getcwd(),"Images",name)) image = Image.open(os.path.join(os.getcwd(),"Images",name)) except: print('error opening image;', name) return image def Find(name): image = GetImage(name) imagebbox = image.getbbox() screen = ImageGrab.grab() #screen = Image.open(os.path.join(os.getcwd(),"Images","Untitled.bmp")) YLimit = screen.getbbox()[3] - imagebbox[3] XLimit = screen.getbbox()[2] - imagebbox[2] image = image.convert("L") Screen = screen.convert("L") Screen.load() image.load() #print(XLimit, YLimit) Found = False image = image.getdata() for y in range(0,YLimit): for x in range(0,XLimit): BoxCoordinates = x, y, x+imagebbox[2], y+imagebbox[3] ScreenGrab = screen.crop(BoxCoordinates) ScreenGrab = ScreenGrab.getdata() if image == ScreenGrab: Found = True #print("woop") return x,y if Found == False: return "Not Found" cProfile.run('print(Find("Login"))')

    Read the article

  • An annoying printing issue with Crystal Reports 2008

    - by Xience
    A little background: I have an extremely annoying printing issue with crystal reports. My environment is crystal reports 2008 SP2 on Windows 7 (64bit), Visual studio 2008 and .net framework 3.5 with all the latest updates for everything. The report is designed basically to render a small shelf label of the size (40mm width and 20mm height). In crystal when I set the page size to the above mentioned values and set orientation to portrait and take a preview, everything is displayed as i expect it to be and issuing a print command, it prints absolutely correct. The problem: The problem comes when i print this report from my program (in vb.net), dynamically setting data to some text fields, the result is that crystal somehow changes the print orientation, NOT the paper orientation as in portrait or landscape. Instead of printing from top left towards the bottom right, it rotates the whole output at 90 degrees to the left and reduces everything so small that it is barely visible, although it prints everything out. I have tested it on Intermec PF8t and Zebra GK420d label printers and a whole bunch of laser printers, but with the above stated page settings the output is always the same. Another strange thing that i noticed while experimenting with page sizes if i switch to landscape mode, the print out is correct in its font sizes and positions but then the text gets truncated due to overflowing the page size. Can anyone help me with this. Does crystal has anything like its own print drivers or something. I have tried to ensure to the best of my abilities that it is not a printer driver problem.

    Read the article

  • Casting To The Correct Subclass

    - by kap
    Hi Guys I hava a supeclass called Car with 3 subclasses. class Ford extends Car{ } class Chevrolet extends Car{ } class Audi extends Car{ } Now i have a function called printMessge(Car car) which will print a message of a particular car type. In the implementation i use if statements to test the instance of the classes like this. public int printMessge(Car car){ if((Ford)car instanceof Ford){ // print ford }else if((Chevrolet)car instanceof Chevrolet){ // print chevrolet }else if((Audi)car instanceof Audi){ // print Audi } } for instance if i call it for the first time with Ford printMessge(new Ford()), it prints the ford message but when i call it with printMessge(new Chevrolet()), i get EXCEPTION from the first if statement that Chevrolet cannot be cast to Ford. What am i doing wrong and what is the best way. thanks

    Read the article

  • need help passing multiple variables from foreach loop to test in switch case statement

    - by Brad
    $list_of_groups = array("FACULTY","STAFF"); foreach ($list_of_groups as $i => $group) { $user_in_group = $adldap->user_ingroup($username,$group); print "<h2>Group: ".$group." user in group? ".$user_in_group."</h2>"; // if 1, means yes } Need to print run the appropriate function based on what returns true. There are user's that are members of both FACULTY and STAFF groups, so I want to check for those users and display the appropriate content for them. So if the user is both faculty and staff, then display this, if they are only of staff, display that, same for faculty, might not make sense, but I will write out some code "in theory" that will help you understand what I am trying to do switch(Get group membership of user) { case "FACULTY": print "Faculty group member"; break; case "STAFF": print "Staff group member"; break; case "FACULTY and STAFF": print "Member of both faculty and staff"; break; } I am unsure on how it will check if they are members of both groups and run that thru the case statement to display the appropriate message. The foreach look currently runs thru every group the user belongs to, prints out the ones from the $list_of_groups and the number 1 to the right of it, signifying they belong to it. The problem I have is trying to use that information to run thru the case statement, I am unsure of how to go about that. This is what it prints out for the user currently passed thru the foreach loop: Group: FACULTY user in group? 1 Group: STAFF user in group? 1 Any help is appreciated.

    Read the article

< Previous Page | 61 62 63 64 65 66 67 68 69 70 71 72  | Next Page >