Given this :
import os
import subprocess
def check_server():
cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE)
result = cl.communicate()
print result
check_server()
check_server() returns this tuple:
('\nStarting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:26 EDT\nInteresting ports on 10.7.1.71:\nNot shown: 1711 closed ports\nPORT STATE SERVICE\n21/tcp open ftp\n22/tcp open ssh\n80/tcp open http\n\nNmap done: 1 IP address (1 host up) scanned in 0.293 seconds\n', None)
Changing the second line in the method to
result, err = cl.communicate()
results in check_server() returning :
Starting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:27 EDT
Interesting ports on 10.7.1.71:
Not shown: 1711 closed ports
PORT STATE SERVICE
21/tcp open ftp
22/tcp open ssh
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 0.319 seconds
Looks to be the case that the tuple is converted to a string, and the \n's are being stripped.... but how? What is 'err' and what exactly is it doing?
I have a hashmap like so:
results[tweet_id] = {"score" : float(dot(query,doc) / (norm(query) * norm(doc))), "tweet" : tweet}
What I'd like to do is to sort results by the innser "score" key. I don't know how possible this is, I saw many sorting tutorials but they were for simple (not nested) data structures.
Hi,
someone can tell me why this is incorrect as a singleton pattern:
class preSingleton(object):
def __call__(self):
return self
singleton = preSingleton()
a = singleton()
b = singleton()
print a==b
a.var_in_a = 100
b.var_in_b = 'hello'
print a.var_in_b
print b.var_in_a
Edit: The above code prints:
True
hello
100
thank you very much
I want to verify that the HTML tags present in a source string are also present in a target string.
For example:
>> source = '<em>Hello</em><label>What's your name</label>'
>> verify_target(’<em>Hi</em><label>My name is Jim</label>')
True
>> verify_target('<label>My name is Jim</label><em>Hi</em>')
True
>> verify_target('<em>Hi<label>My name is Jim</label></em>')
False
Hi,
I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function , something like so -
currmax = 0
def mymax(s) :
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
Is there a clean pythonic way of doing this?
Thanks!
Is it possible to get the full path of the file on the user's computer being uploaded to my site?
Using os.path.abspath(fileitem.filename) simply gets me the address of where my script is executing from on my shared hosting server.
FYI: fileitem = form['file'] and form = cgi.FieldStorage()
I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.
for row in rows:
for i in `row[4]`:
if i ==`1`:
print 'blue '
else:
print 'green '
Any help would be grateful
thanks
Yas
Is there a performance or code maintenance issue with using assert as part of the standard code instead of using it just for debugging purposes?
Is
assert x >= 0, 'x is less then zero'
and better or worse then
if x < 0:
raise Exception, 'x is less then zero'
Also, is there anyway to set a business rule like if x < 0 raise error that is always checked with out the try, except, finally so, if at anytime throughout the code x is < 0 an error is raised, like if you set assert x < 0 at the start of a function, anywhere within the function where x becomes less then 0 an exception is raised?
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
I have this code:
filenames=["file1","FILE2","file3","fiLe4"]
def alignfilenames():
#build a string that can be used to add labels to the R variables.
#format goal: suffixes=c(".fileA",".fileB")
filestring='suffixes=c(".'
for filename in filenames:
filestring=filestring+str(filename)+'",".'
print filestring[:-3]
#now delete the extra characters
filestring=filestring[-1:-4]
filestring=filestring+')'
print "New String"
print str(filestring)
alignfilenames()
I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Any idea what's going on or how to fix it?
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack.
def expires():
'''return a UNIX style timestamp representing 5 minutes from now'''
epoch = datetime.datetime(1970, 1, 1)
seconds_in_a_day = 60 * 60 * 24
five_minutes = datetime.timedelta(seconds=5*60)
five_minutes_from_now = datetime.datetime.now() + five_minutes
since_epoch = five_minutes_from_now - epoch
return since_epoch.days * seconds_in_a_day + since_epoch.seconds
Is there a module or function that does the timestamp conversion for me?
I have someting like this
class A:
__a = 0
def __init__(self):
A.__a = A.__a + 1
def a(self):
return A.__a
class B(A):
def __init__(self):
# how can I access / modify A.__a here?
A.__a = A.__a + 1 # does not work
def a(self):
return A.__a
Can I access the __astatic variable in B? It's possible writing a instead of __a, is this the only way? (I guess the answer might be rather short: yes :)
Hello, everyone
I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing:
from socket import *
from threading import Thread
from sys import exit
class TestThread(Thread):
def __init__(self,host="localhost",port=9999):
self.sock = socket(AF_INET,SOCK_DGRAM)
self.sock.bind((host,port))
super(TestThread,self).__init__()
def run(self):
while True:
try:
recv_data,addr = self.sock.recvfrom(1024)
except (KeyboardInterrupt, SystemExit):
sys.exit()
if __name__ == "__main__":
server_thread = TestThread()
server_thread.start()
while True: pass
The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom().
Please, help me resolve this.
say ive got a matrix that looks like:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
how can i make it on seperate lines:
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
and then remove commas etc:
0 0 0 0 0
And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like:
_ 1 2 _ 1 _ 1
(spaces not underscores)
thanks
I have a game loop like this:
#The velocity of the object
velocity_x = 0.09
velocity_y = 0.03
#If the location of the object is over 5, bounce off.
if loc_x > 5:
velocity_x = (velocity_x * -1)
if loc_y > 5:
velocity_y = (velocity_y * -1)
#Every frame set the object's position to the old position plus the velocity
obj.setPosition([(loc_x + velocity_x),(loc_y + velocity_y),0])
Basically, my problem is that in the if loops, I change the variable from its original value to the inverse of its old value. But because I declare the variable's value at the beginning of the script, the velocity variables don't stay on what I change it to.
I need a way to change the variable's value permanently.
Thank you!
I have a directory /tmp/dir with two types of file names
/tmp/dir/abc-something-server.log
/tmp/dir/xyz-something-server.log
..
..
and
/tmp/dir/something-client.log
I need append a few lines (these lines are constant) to files end with "client.log"
line 1
line 2
line 3
line 4
append these four lines to files end with "client.log"
and For files end with "server.log"
I needed to append after a keyword say "After-this".
"server.log " file has multiple entries of "After-this" I need to find the first entry of "After-this" and append above said four lines keep the remaining file as it is.
Any help will be great appreciated :) Thanks in advance.
hello
i never worked with web programming and
i've been asked lately to write a web-based software to manage assets and tasks. to be used by more than 900 persons
what are the recommended modules , frameworks , libraries for this task.
and it will be highly appreciated if you guyz recommend some books and articles that might help me. thanks in advance
I have two functions:
def f(a,b,c=g(b)):
blabla
def g(n):
blabla
c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that?
Someone suggested:
def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
But this doesn't work, because maybe the user intended c to be None and then c will have another value.
I was unsuccessful browsing web for a solution for the following simple question:
How to draw 3D polygon (say a filled rectangle or triangle) using vertices values?
I have tried many ideas but all failed, see:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [zip(x, y,z)]
ax.add_collection3d(PolyCollection(verts),zs=z)
plt.show()
I appreciate in advance any idea/comment.
Updates based on the accepted answer:
import mpl_toolkits.mplot3d as a3
import matplotlib.colors as colors
import pylab as pl
import scipy as sp
ax = a3.Axes3D(pl.figure())
for i in range(10000):
vtx = sp.rand(3,3)
tri = a3.art3d.Poly3DCollection([vtx])
tri.set_color(colors.rgb2hex(sp.rand(3)))
tri.set_edgecolor('k')
ax.add_collection3d(tri)
pl.show()
Here is the result:
I am creating a 'Euromillions Lottery generator' just for fun and I keep getting the same numbers printing out. How can I make it so that I get random numbers and never get the same number popping up:
from random import randint
numbers = randint(1,50)
stars = randint(1,11)
print "Your lucky numbers are: ", numbers, numbers, numbers, numbers, numbers
print "Your lucky stars are: " , stars, stars
The output is just:
>>> Your lucky numbers are: 41 41 41 41 41
>>> Your lucky stars are: 8 8
>>> Good bye!
How can I fix this?
Regards
I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.)
I'm specifically thinking of newsletters that often come from the same address, and repeat the product/service/group's name in the subject.
I'm aware that I could search/sort by the common occurrence of items from a particular email address (and I intend to), but I'd like to correlate that data with repeating subject lines....
Now, many subject lines would fail a string match, but
"Google Friends : Our latest news"
"Google Friends : What we're doing today"
are more similar to each other than a random subject line, as is:
"Virgin Airlines has a great sale today"
"Take a flight with Virgin Airlines"
So -- how can I start to automagically extract trends/examples of strings that may be more similar.
Approaches I've considered and discarded ('because there must be some better way'):
Extracting all the possible substrings and ordering them by how often they show up, and manually selecting relevant ones
Stripping off the first word or two and then count the occurrence of each sub string
Comparing Levenshtein distance between entries
Some sort of string similarity index ...
Most of these were rejected for massive inefficiency or likelyhood of a vast amount of manual intervention required. I guess I need some sort of fuzzy string matching..?
In the end, I can think of kludgy ways of doing this, but I'm looking for something more generic so I've added to my set of tools rather than special casing for this data set.
After this, I'd be matching the occurring of particular subject strings with 'From' addresses - I'm not sure if there's a good way of building a data structure that represents how likely/not two messages are part of the 'same email list' or by filtering all my email subjects/from addresses into pools of likely 'related' emails and not -- but that's a problem to solve after this one.
Any guidance would be appreciated.
Suppose I have a list of lists of elements which are all the same (i'll use ints in this example)
[range(100)[::4], range(100)[::3], range(100)[::2], range(100)[::1]]
What would be a nice and/or efficient way to take the intersection of these lists (so you would get every element that is in each of the lists)?
For the example that would be:
[0, 12, 24, 36, 48, 60, 72, 84, 96]
I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach:
in_1 = open(input_1)
in_2 = open(input_2)
out_1 = open(output_1, "w")
out_2 = open(output_2, "w")
# Read one line from each 'in_' file
# Do many operations on the DNA sequences included in the input files
# Append one line to each 'out_' file
in_1.close()
in_2.close()
out_1.close()
out_2.close()
The files are huge (each potentially approaching 1Go, that is why I am reading through these input files one at a time. I am guessing that this is not a very Pythonic way to do things. :) Would using the following form good?
with open("file1") as f1:
with open("file2") as f2: # etc.
If yes, could I do it while avoiding the highly indented code that would result? Thanks for the insights!