import datetime
start = datetime.datetime(2009, 1, 31)
end = datetime.datetime(2009, 2, 1)
print end-start
>>1 day, 0:00:00//output
How to get the output in minutes
Thanks,
Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code)
Conventional:
person = new Person("Joey")
person.getName().toLower().print()
Alternative:
person = new Person("Joey")
person.name().toLower().print()
Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal).
Thanks.
I'm working on a new presenation component for one of our applications. I am building a Custom WPF Control that just has a DocumentViewer in it and hosting that CC in a Windows Forms application with an ElementHost. I'm using Visual Studio 2008 with C#.
I have customized everything through the XAML to give it the look and feel that integrates it perfecting into our application, but one thing remains...
If you press CTRL+P the print dialog still comes up. I'm at a complete loss as to how to disable that fuction. The use of this CC is to allow the users to pull up and view the Manuals for the systems installed at that site, but we don't want them to accidently print them (100s of pages).
Please help,
-G
I have a simple 2D array:
int[,] m = {{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0}
};
How can I print this out onto a text file or something? I want to print the entire array onto a file, not just the contents. For example, I don't want a bunch of zeroes all in a row: I want to see the {{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0}
}; in it.
I'm using this program to record a sound in python:
import pyaudio
import wave
import sys
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
print "* recording"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk)
all.append(data)
print "* done recording"
stream.close()
p.terminate()
write data to WAVE file
data = ''.join(all)
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
I want to change the program to start recording when sound is detected by the sound card input. Probably should compare the input sound level in Chunk, but how do this?
I'm trying to debug some STL based C++ code in gdb.
The code has something like
int myfunc()
{
std::map<int,int> m;
...
}
Now in gdb, inside myfunc using "print m" gives something very ugly.
What I've seen recommended is compiling something like
void printmap( std::map<int,int> m )
{
for( std::map<int,int>::iterator it = ... )
{
printf("%d : %d", it->first, it->second );
}
}
Then in gdb doing
(gdb) call printmap( m )
This seems like a good way to handle the issue... but can I put printmap into a seperate object file (or even dynamic library) that I then load into gdb at runtime rather than compiling it into my binary - as recompiling the binary every time I want to look at another STL variable is not fun .. while compiling and loading a single .o file for the print routine may be acceptable.
From MSDN (link):
The type PrintDocumentImageableArea
has no public constructor. Hence, the
variable documentImageableArea must be
declared and assigned to Nothing and
only then passed to the method. This
method displays a PrintDialog
requiring input from the user. After
the user has selected a printer, paper
size, and orientation and closed the
dialog, documentImageableArea points
to an actual object and its properties
are initialized.
I have my custom print dialog and need to get the PrintDocumentImageableArea of a given PrintQueue and PrintTicket! (I need the margin's I need to apply)
From what I can gather it is quite common for anything but the most basic applications to use their own custom print dialog. There must be a way to get to this information!?
Any input appreciated!
In most scripting languages, a "Hello world!" application is very short:
print "Hello world"
In C++, it is a little more complicated, requiring at least 46 non-whitespace characters:
#include <cstdio>
int main()
{
puts("Hello world");
}
Java, at 75 non-whitespace characters, is even more verbose:
class A {
public static void main(String[] args) {
System.out.print("Hello world");
}
}
Are there any languages that require even more non-whitespace characters than Java? Which language requires the most?
Notes:
I'm asking about the length of the shortest possible "hello world" application in a given language.
A newline after "Hello world" is not required.
I'm not counting whitespace, but I know there is some language that uses only whitespace characters. If you use that one you can count the whitespace characters.
This is what I currently have:
wordlist = [fox, aced, definite, ace]
for word in wordlist:
a = len(word)
if (ord(word[a-(a-1)] - ord(word[(a-a)])) == ord(word[a-(a-2)])-ord(word[a-(a-1)]:
print "success", word
else:
print "fail", word
What I'm trying to do is calculate the ASCII values between each of the letters in the word. And check to see if the ord of the letters are increasing by the same value.
so for fox, it would check if the difference between the ord of 2nd and 1st letters are equal to the ord difference of the 3rd and 2nd letters.
However, with my current 'if' statement, only the first 3 letters of a word are compared. How can I rewrite this statement to cover every letter in a word of length greater than 3?
Sorry if I can't present this clearly, thanks for your time.
Hello.
Well, this smells like a tumbleweed, but I will ask it anyway.
Suppose you have a noweb file with some c# code. You also have the c++ pretty-print filter dpp. If you run the command noweave -filter ./dpp -x test.nw > csharp.tex on the file below, it will print everything except for the curly braces. Instead of them, I get an em-dash and a closing quotations marks (i.e. ?) in the dvi. The tex source looks fine... Any ideas?
@ C\# test file
<<test.c>>=
while( (a[right] >= pivot) && (left < right) )
{
right--;
}
Hello, I am trying to understand this simple hashlib code in Python that has been given to me the other day on "Stackoverflow":
import hashlib
m = hashlib.md5()
m.update("Nobody inspects")
m.update(" the spammish repetition here")
m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
m.digest_size
16
m.block_size
64
print m
I thought that "print m" would show me the MD5 digest of the phrase: "Nobody inspects the spammish repetition here", but as a result I got this line on my local host:
<md5 HASH object @ 01806220>
Strange, when I refreshed the page, I got another line:
<md5 HASH object @ 018062E0>
and every time when I refresh it, I get another value:
md5 HASH object @ 017F8AE0
md5 HASH object @ 01806220
md5 HASH object @ 01806360
md5 HASH object @ 01806400
md5 HASH object @ 01806220
Why is it so? I guess, what I have in each line flowing "@" is not really a digest. Then, what is it? And how can I display MD5 digest here in this code?
My python version is Python 2.5 and the framework I am currently using is webapp (I have downloaded it together with SDK from "Google App Engine")
Hi, I am using swig wrapper of openbabel(written in C++, and supply a python wrapper through swig)
Below i just use it to read a molecule structure file and get the unitcell property of it.
import pybel
for molecule in pybel.readfile('pdb','./test.pdb'):
unitcell = molecule.unitcell
print unitcell
|..
|..
The unitcell has function CellMatrix(),
unitcell.GetCellMatrix()
<22
the OpenBabel::matrix3x3 is something like :
1 2 3
4 5 6
7 8 9
i am wondering how to print out the contents of the matrix3*3 . I have tried str and repr with it.
Any general way to stringfy the contents of a matrix wrapped by swing in python ?
thanks
The problem is that my application only prints the first document fine. The second document is empty, only the page number is printed, the rest of the page is empty.
In Qt4, I'm initializing the printer in the main.cpp in the following way:
mw->printer = new QPrinter(QPrinter::HighResolution);
mw->printer->setPaperSize(QPrinter::A5);
mw->printer->setNumCopies(2);
mw->printer->setColorMode(QPrinter::GrayScale);
QPrintDialog *dialog = new QPrintDialog(mw->printer, mw);
dialog->setWindowTitle(QObject::tr("Printer Setup"));
if (dialog->exec() == QDialog::Accepted)
{
mw->printer->setFullPage(TRUE);
return a.exec ();
}
This works fine for printing the first document from the application:
qDebug("Printing");
QPainter p;
if (!p.begin(printer))
{
qDebug("Printing aborted");
return;
}
Q3PaintDeviceMetrics metrics(p.device());
int dpiy = metrics.logicalDpiY();
int dpix = metrics.logicalDpiX();
int tmargin = (int) ((marginTop / 2.54) * dpiy);
int bmargin = (int) ((marginBottom / 2.54) * dpiy);
int lmargin = (int) ((marginLeft / 2.54) * dpix);
int rmargin = (int) ((marginRight / 2.54) * dpix);
QRect body(lmargin, tmargin,
metrics.width() - (lmargin + rmargin),
metrics.height() - (tmargin + bmargin));
QString document;
/* ... app logic to write a richtext document */
Q3SimpleRichText richText(QString("<qt>%1</qt>").arg(document),
QFont("Arial", fontSize));
richText.setWidth(&p, body.width());
QRect view(body);
int page = 1;
do {
// draw text
richText.draw(&p, body.left(), body.top(), view, colorGroup());
view.moveBy(0, body.height());
p.translate(0, -body.height());
// insert page number
p.drawText(view.right() - p.fontMetrics().width(QString::number(page)),
view.bottom() + p.fontMetrics().ascent() + 5,
QString::number(page));
// exit loop on last page
if (view.top () >= richText.height ()) break;
printer->newPage();
page++;
} while (TRUE);
if (!p.end()) qDebug("Print painter yielded failure");
But when this routine runs the second time, it does not print the document. It will just print an empty page but still with the page number on it. This worked fine before with Qt3.
I just realized that i may not be following best practices in regards to the MVC pattern.
My issue is that my views "know" information about my database
Here's my situation in psuedo code...
My controller invokes a method from my model and passes it directly to the view
view.records = tableGateway.getRecords()
view.display()
in my view
each records as record
print record.name
print record.address
...
In my view i have record.name and record.address, info that's hard-coded to my database. Is this bad?
What other ways around it are there other than iterating over everything in the controller and basically rewriting the records collection. And that just seems silly.
Thanks
It's a known bug/issue that a label in GTK will not dynamically resize when the parent changes. It's one of those really annoying small details, and I want to hack around it if possible.
I followed the approach at 16 software, but as per the disclaimer you cannot then resize it smaller. So I attempted a trick mentioned in one of the comments (the set_size_request call in the signal callback), but this results in some sort of infinite loop (try it and see).
Does anyone have any other ideas?
(You can't block the signal just for the duration of the call, since as the print statements seem to indicate, the problem starts after the function is left.)
The code is below. You can see what I mean if you run it and try to resize the window larger and then smaller. (If you want to see the original problem, comment out the line after "Connect to the size-allocate signal", run it, and resize the window bigger.)
The Glade file ("example.glade"):
<?xml version="1.0"?>
<glade-interface>
<!-- interface-requires gtk+ 2.16 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="window1">
<property name="visible">True</property>
<signal name="destroy" handler="on_destroy"/>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="label" translatable="yes">In publishing and graphic design, lorem ipsum[p][1][2] is the name given to commonly used placeholder text (filler text) to demonstrate the graphic elements of a document or visual presentation, such as font, typography, and layout. The lorem ipsum text, which is typically a nonsensical list of semi-Latin words, is a hacked version of a Latin text by Cicero, with words/letters omitted and others inserted, but not proper Latin[1][2] (see below: History and discovery). The closest English translation would be "pain itself" (dolorem = pain, grief, misery, suffering; ipsum = itself).</property>
<property name="wrap">True</property>
</widget>
</child>
</widget>
</glade-interface>
The Python code:
#!/usr/bin/python
import pygtk
import gobject
import gtk.glade
def wrapped_label_hack(gtklabel, allocation):
print "In wrapped_label_hack"
gtklabel.set_size_request(allocation.width, -1)
# If you uncomment this, we get INFINITE LOOPING!
# gtklabel.set_size_request(-1, -1)
print "Leaving wrapped_label_hack"
class ExampleGTK:
def __init__(self, filename):
self.tree = gtk.glade.XML(filename, "window1", "Example")
self.id = "window1"
self.tree.signal_autoconnect(self)
# Connect to the size-allocate signal
self.get_widget("label1").connect("size-allocate", wrapped_label_hack)
def on_destroy(self, widget):
self.close()
def get_widget(self, id):
return self.tree.get_widget(id)
def close(self):
window = self.get_widget(self.id)
if window is not None:
window.destroy()
gtk.main_quit()
if __name__ == "__main__":
window = ExampleGTK("example.glade")
gtk.main()
I am new to programming and Python.
I have a very basic python script that connects to server and send a text message:
#!/usr/bin/python
import socket
s = socket.socket()
host = '127.0.0.1'
port = 4106
s.connect((host, port))
message = 'test1'
s.send(message)
print s.recv(1024)
s.close
Everything is fine, except that this message is an HL7 message and needs to wrapped in MLLP
I found this API that I think can do this for me (http://python-hl7.readthedocs.org/en/latest/api.html#mllp-network-client)
So I modified my program to the following, but I keep getting the error message: NameError: name 'MLLPClient' is not defined
#!/usr/bin/python
import socket
import hl7
host = '127.0.0.1'
port = 4106
with MLLPClient(host, port) as client:
client.send_message('test1')
print s.recv(1024)
s.close
Thanks in advanced for all the help
Hello all,
I am testing some logic to handle a user uploading a TAR file. When I feed a blank file to tarfile.is_tarfile() it returns True, which is not what I am expecting:
$ touch tartest
$ cat tartest
$ python -c "import tarfile; print tarfile.is_tarfile('tartest')"
True
If I add some text to the file, it returns False, which I am expecting:
$ echo "not a tar" > tartest
$ python -c "import tarfile; print tarfile.is_tarfile('tartest')"
False
I could add a check at the beginning to check for a zero-length file, but based on the documentation for tarfile.is_tarfile(name) I think this is unecessary:
Return True if name is a tar archive
file, that the tarfile module can
read.
I went so far as to check the source, tarfile.py, and I can see that it is checking header blocks but I do not fully understand how it is evaluating those blocks.
Am I misreading the documentation and therefore setting unfair expectations?
Thank you,
Zachary
I made this bash one-liner which I use to list Weblogic instances running along with their full paths.This works well when I run it from the shell.
/usr/ucb/ps auwwx | grep weblogic | tr ' ' '\n' | grep security.policy | grep domain | awk -F'=' '{print $2}' | sed 's/weblogic.policy//' | sed 's/security\///' | sort
I tried to incorporate this in an expect script
send "echo Weblogic Processes: ; /usr/ucb/ps auwwx | grep weblogic | tr ' ' '\n' | grep security.policy | grep domain | awk -F'=' '{print \$2}' | sed 's/weblogic.policy//' | sed 's/security\///' | sort ; echo ; echo\r"
but I got this error sed: -e expression #1, char 13: unknown option to `s'
Please help
I very new to Python, and fairly new to regex. (I have no Perl experience.)
I am able to use regular expressions in a way that works, but I'm not sure that my code is particularly Pythonic or consise.
For example, If I wanted to read in a text file and print out text that appears directly between the words 'foo' and 'bar' in each line (presuming this occurred one or zero times a line) I would write the following:
fileList = open(inFile, 'r')
pattern = re.compile(r'(foo)(.*)(bar)')
for line in fileList:
result = pattern.search(line)
if (result != None):
print result.groups()[1]
Is there a better way? The if is necessary to avoid calling groups() on None. But I suspect there is a more concise way to obtain the matching String when there is one, without throwing errors when there isn't.
I'm not hoping for Perl-like unreadability. I just want to accomplish this common task in the commonest and simplest way.
Hi,
My understanding of basic BFS traversal for a graph is:
BFS
{
Start from any node . Add it to que. Add it to visited array
While(que is not empty)
{
remove head from queue. Print node;
add all unvisited direct subchilds to que; mark them as visited
}
}
However, if we have to traverse a DIRECTED graph from a given node and not all nodes are accessible from the given node [directly or indirectly] how do we use BFS for the same.
Can you please explain in this graph as well:
a= b = d = e = d
a= c = d
Here if the starting node is b , we never print a and c.
Am I missing something in the algorithm.
P.S: I used "HashMap adj = new HashMap();" to create the adjacencey list to store graph
Any pointers are greatly appreciated.
Thanks.
in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?
the following code should illustrate what im after...
def checkEqual(x, y):
print True if x==y else False
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%line1
print "%s \n\n%s \n\n%s \n" % (line1, line2, line3)
checkEqual(line2, line3) #outputs False
checkEqual(line2, line3[1:-1]) #outputs True
The closest I have found so far is the %r formatting flag which seems to return a raw string albeit within single quote marks. Is there any easier way to do this like a line3 = raw(line1) kind of thing?
Hey, i am new to objective C, but i tried to use HOM in order to iterate over an NSArray and append a string to each element.
here is my code:
void print( NSArray *array ) {
NSEnumerator *enumerator = [array objectEnumerator];
id obj;
while ( nil!=(obj = [enumerator nextObject]) ) {
printf( "%s\n", [[obj description] cString] );
}
}
int main( int argc, const char *argv[] ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *names = [[NSArray alloc] init];
NSArray *names_concat = [[NSArray alloc] init];
names = [NSArray arrayWithObjects:@"John",@"Mary",@"Bob",nil];
names_concat = [[names collect] stringByAppendingString: @" Doe"];
print(names_concat);
[pool release];
}
What is wrong with this code?
My compiler (gcc) says NSArray may not respond to "-collect"
I'm stil pretty new to regular expression and just started learning to use awk. What I am trying to accomplish is writing a ksh script to read-in lines from text, and and for every lines that match the following:
*RECORD 0000001 [some_serial_#]
to replace $2 (i.e. 000001) with a different number. So essentially the script read in batch record dump, and replace the record number with date+record#, and write to separate file.
So this is what I'm thinking the format should be:
awk 'match($0,"/*FTR")!=0{$2="$DATE-n++"; print $0} match($0,"/*FTR")==0{print $0}' $BATCH > $OUTPUT
but obviously "/*FTR" is not going to work, and I'm not sure if changing $2 and then write the whole line is the correct way to do this. So I am in need of some serious enlightenment.
I have a structure for a tree and I want to print the tree by levels.
data Tree a = Nd a [Tree a] deriving Show
type Nd = String
tree = Nd "a" [Nd "b" [Nd "c" [], Nd "g" [Nd "h" [], Nd "i" [], Nd "j" [], Nd "k" []]], Nd "d" [Nd "f" []], Nd "e" [Nd "l" [Nd "n" [Nd "o" []]], Nd "m" []]]
preorder (Nd x ts) = x : concatMap preorder ts
postorder (Nd x ts) = (concatMap postorder ts) ++ [x]
But how to do it by levels? "levels tree" should print ["a", "bde", "cgflm", "hijkn", "o"].
I think that "iterate" would be suitable function for the purpose, but I cannot come up with a solution how to use it. Would you help me, please?