Well, you can use split()
s = """
version: 7.0.0.9
type : NAS
"""
lines = s.strip().split("\n")
lines = [tuple(x.strip() for x in y.split(":")) for y in lines]
print(lines)
""" my output -->
[('version', '7.0.0.9'), ('type', 'NAS')]
"""
Well, you can use split()
s = """
version: 7.0.0.9
type : NAS
"""
lines = s.strip().split("\n")
lines = [tuple(x.strip() for x in y.split(":")) for y in lines]
print(lines)
""" my output -->
[('version', '7.0.0.9'), ('type', 'NAS')]
"""
You can use the Command class in this code snippet. You would write
com = Command("./vershion.sh").run()
if com.failed:
print(com.error)
else:
print(com.output)
I tested the SQL
CREATE TABLE COMPANY(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
in sqliteman on a fresh database and it works.
You must do a depth first traversal for this. The algorithm is very simple: suppose the urls line up at the post office with a number D written on their T-shirt, representing their depth. For every url, a web page is loaded and new urls discovered. The urls which have already been seen are thrown away, the others queue up with T-shirt D+1. Initially, there is only one url in the queue with T-shirt 0.
It is not exactly the scheme. In python there is a DB-API, which many database modules, like sqlite3, try to implement. What this api says in short, si that the pseudo code looks like
create a Connection object (using the db file name)
create a Cursor object for this connection
execute a (SQL) query, using cursor.execute()
for row in cursor:
do something with the row
close cursor
close connection
See the example with a SELECT *
sql request in the module documentation.
It is a very good idea to use a class instance to handle this. You can add a parameter self
to all the functions and refactor the code like this:
import random
# ...
think = ("Tänk på ett fyrsiffrigt tal med olika siffror")
class Mastermind:
def __init__(self):
self.nya_gissningen = None
def inkonsekvent(self, p, gissningar):
# ...
def ny_svar(self):
# ...
# ......... self.nya_gissningen[0] ...
# ...
def mastermind_dator(self):
# ...
self.nya_gissningen = ...
Mastermind().mastermind()
I suggest
import pkgutil
import os
import sys
L = list(sys.builtin_module_names)
L += list(t[1] for t in pkgutil.iter_modules())
L = sorted(L)
dst = os.path.expanduser("~/Desktop/modules.txt")
with open(dst, "w") as ofh:
ofh.write('\n'.join(L))
Try ''.join(sorted(sec))
This forum is not an online homework service. We can help with issues in your implementation of the problem. Show some effort and post your attempts to find the bigrams.
You cannot use s[0]
on en empty string, as s[0]
returns the first char in the string: write the empty strings tests first.
I could not reproduce the bug on my system. Considering that you read the file with mode 'rb', perhaps you should write it in mode 'wb'.
In a sequence if...elif...elif...elif
, only the first true alternative is executed. Use a print to see what happens:
def my_startswith(s1, s2):
print((s1[0] == s2[0], s1[0] != s2[0],
s2 == '', s1 == '' and s2 == ''))
if s1[0] == s2[0]:
return True
elif s1[0] != s2[0]:
return False
elif s2 == '':
return True
elif s1 == '' and s2 == '':
return True
In python 2.7, the Namespace class is defined with this code
class _AttributeHolder(object):
"""Abstract base class that provides __repr__.
The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, ...)
The attributes are determined either by a class-level attribute,
'_kwarg_names', or by inspecting the instance __dict__.
"""
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
arg_strings.append('%s=%r' % (name, value))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
return sorted(self.__dict__.items())
def _get_args(self):
return []
class Namespace(_AttributeHolder):
"""Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple
string representation.
"""
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
__hash__ = None
def __eq__(self, other):
return vars(self) == vars(other)
def __ne__(self, other):
return not (self == other)
def __contains__(self, key):
return key in self.__dict__
Use this code in your program to mock Namespace
Why don't you simply call Namespace's constructor ?
import argparse
obj = argparse.Namespace(filter='b', list="['hi','by']")
define a __repr__()
method.
There are probably many solutions. You can create a symlink in a directory on your path.
Currently I'm using a python app called cherrytree. There is a small python executable /usr/bin/cherrytree
which role is to parse command line arguments using argparse, add a folder in sys.path and import the real app meat which is stored in /usr/share/cherrytree
. You could study this example.
Why don't you write
#!/usr/bin/env python
# -*-coding: utf8-*-
# file: filterList
import os
import sys
fol = os.path.expanduser('~/Development/python/listFilter/python')
sys.path.insert(0, fol)
import filterList
filterList.main()
Another solution would be to make filterList.py executable and create a symlink
ln -s ../python/filterList.py filterList
It is probably /usr/bin/env
. Try which env
in a terminal.
Did you try with the options before the file argument ?
python -m nose.core --tests -s --with-coverage $1
Did you check that the coverage module is installed ?
$ pydoc coverage
In linux mint, coverage is available via the package python-coverage
.
I don't use windows, but I found this blog entry, which is about 1 and a half year old, about possible issues. It may help you.
The test fails before the assertRaises is reached, because the FilterList ctor (method __init__()
) calls checkListItem()
, which means that you cannot even make a test list with invalid types.
As for your approach, it is difficult to answer since we don't know what you want to do with this.
One problem is that you start each year with c = 1 on the first day. Since your criterion for sundays is c%6 == 0
. It means that every year starts with a tuesday.
line 32 to line 35, do change like this:
try:
socket.inet_pton(socket.AF_INET6, address)
except:
return False
replace socket.inet_pton(socket.AF_INET6, address)
by the previous snippet to catch the exception.
Use startpage ! Here is a related discussion. You should try and modify net.py according to the last suggestion.
Here is an example with 2 worker threads. It uses Condition objects to synchronize threads. It is relatively easy to understand if you remember that only one thread may own a given condition at a given time, which means for example that a worker blocks on with G.wcond
if another thread is in a with G.wcond
section, unless the other thread is running a G.wcond.wait()
statement.
from threading import Thread, Condition
import time
class G:
wcond = Condition()
pcond = Condition()
can_work = False
can_process = True
class Worker(Thread):
def run(self):
while True:
with G.wcond:
while not G.can_work: # we wait for permission to work
G.wcond.wait()
self.do_work()
G.can_work = False
with G.pcond: # we give permission to process
G.can_process = True
G.pcond.notify()
def do_work(self):
for i in range(3):
print("working ...", self.name)
time.sleep(0.2)
class Processor(Thread):
def run(self):
while True:
with G.pcond:
while not G.can_process: # we wait for permission to process
G.pcond.wait()
self.do_process()
G.can_process = False
with G.wcond: # we give permission to work
G.can_work = True
G.wcond.notify()
def do_process(self):
for i in range(2):
print("processing ...")
time.sleep(0.2)
w, w2, p = Worker(), Worker(), Processor()
w.start()
w2.start()
p.start()
"""my output -->
processing ...
processing ...
('working ...', 'Thread-4')
('working ...', 'Thread-4')
('working ...', 'Thread-4')
processing ...
processing ...
('working ...', 'Thread-5')
('working ...', 'Thread-5')
('working ...', 'Thread-5')
processing ...
processing ...
('working ...', 'Thread-4')
('working ...', 'Thread-4')
etc
"""
With regard to your code, notice that
run()
method must contain the thread's action, instead of its __init__()
method.This is very interesting BearofNH. Unfortunately it does not work with all hardware (eg my laptop :( ). I'm trying to port this code to python, using the python bindings for v4L2 and opencv2. If it works, I'll make a code snippet. See also the author's blog.
I agree with slate. You want a solution, but you didn't even describe the problem that you want to solve. Invoking the 'consumer producer problem' is far too abstract. Didn't you copy and paste code that you don't understand from the internet ?
i guess i can use eval(str)
No! Use json.loads()
Because in your code, package_weight is a local variable in function main(). It exists only in this function's body.
I would pass json format
command '{"India":["New Delhi", "Bangalore"], "Canada": ["Toronto","Vancouver"]}'
and in python code
import json
self.items = json.loads(items)
This avoids any eval issue, and eases cross programs calls.
May I suggest virtualbox + linux ? (just installed rpy2 in one click in linux mint kde)
I have no idea what to do.
In this case, compute the GPA by hand, without your computer, and write down carefully every detail of your procedure. This should give you the algorithm.
The errors come from bad bookkeeping of the index i
def lapping(x1, x2):
x1, x2 = str(x1), str(x2) # in case integers are passed to lapping()
not_lapped= True #used to test if there was no lapping
i = -1
for sets in Big_Set[:-1]: # don't use the last set
i += 1
if x1 in sets:
y = sets.index(x1) # the first position where x1 is
if x2 == Big_Set[i+1][y]:
print("%s and %s laps in sets: " %(x1, x2))
print("set%d: %s" %(i+1,str(sets)))
print("and")
print("set%d: %s" %(i+2,str(Big_Set[i+1])))
not_lapped= False
if not_lapped:
print("%s and %s do not match the lapping criteria\n" %(x1,x2))
The most flexible solution is that the calling code stores the pointer to the window
def start():
window = MainWindow()
window.show()
return window
# in calling code
import above_module
window = above_module.start()
The other solution is that the pointer is stored in above_module
. For example
window = None
def start():
global window
window = MainWindow()
window.show()
One drawback of this approach is that window is not automatically garbage collected, and if you want several instances, you'll have to use a container.
In the first version, window is a local variable in function start(). It is probably garbage collected when the function exits. You need to keep a pointer to window.
What's the output of ping run from a terminal while the script alternates return codes ?
Congratulations, this is good python code. Its naming style however is unusual for python code. You may want to read pep 8, a style guide written for the developpers of the python language trunk. If you follow this style everybody will think you are a very experienced pythonista.
Also string.Template
is seldom used. Most programmers would choose the method str.format()
for this.
The 5/pi limit explains easily. The polygon perimeter is 10 in your example (n * s)
. This is the perimeter of a circle with radius 5/pi.
os.walk('.')
means that you are traversing the current working directory with os.walk (as returned by os.getcwd()
). If you run the code while in the X0.0 directory, os.walk will never see the X0.05 directory.
The current working directory does not change during the walk. To create psub in a subfolder, you must write
psub = os.path.join(root, 'psub')
with open(psub, 'a') as writer:
...
You can also unindent line 5 as the contents of 'top.txt' is stored in the string data.
Have look at the os.walk()
function.
Dos' tasklist command seems to support connecting to a remote system.
Here is a complete (simplified) running example. Try it in the directory with the .out files
#!/usr/bin/env python3
#-*-coding: utf8-*-
import os
# split the code into several functions to lighten it
def main():
with open('results.txt', 'a') as writer:
for file in os.listdir('.'):
if not file.endswith('.out'):
continue
with open(file, 'r') as reader:
handle_reader(reader, writer)
def handle_reader(reader, writer):
print('reading file:', reader.name, file = writer)
opt_cnt = 0
for line in reader:
s=line.strip()
if s=='**** Optimisation achieved ****':
opt_cnt += 1 # <-- count those lines
print('optimisation line number', opt_cnt, end ='\n', file = writer)
else:
pass
if __name__ == '__main__':
main()
I would rather count the optimisation achieved lines while reading:
import os
with open('results.txt', 'a') as writer:
for file in os.listdir('.'):
if file.endswith('.out'):
print(file + ' ', end= ' ', file=writer)
opt_cnt = 0 # <-- reset counter for each file
with open(file, 'r') as reader:
for line in reader.readlines():
s=line.strip()
if s=='**** Optimisation achieved ****':
opt_cnt += 1 # <-- count those lines
elif s.startswith('Final energy ='):
if opt_cnt >= 1: # <-- base decisions on the current value
print(s + ' ', end=' ', file=writer)
...
In the past I used copssh on windows and it was very easy to install and use.