Gribouillis 1,391 Programming Explorer Team Colleague

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')]
"""
Gribouillis 1,391 Programming Explorer Team Colleague

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)
Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

Your favorite search engine can help you with SQL syntax. Here is an answer to your question.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

Not working --> Exception thrown. Solve the issue described by the exception traceback !

Look here.

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

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()
Gribouillis 1,391 Programming Explorer Team Colleague

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))
Gribouillis 1,391 Programming Explorer Team Colleague

Try ''.join(sorted(sec))

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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'.

Gribouillis 1,391 Programming Explorer Team Colleague

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 
Gribouillis 1,391 Programming Explorer Team Colleague

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

Gribouillis 1,391 Programming Explorer Team Colleague

Why don't you simply call Namespace's constructor ?

import argparse
obj = argparse.Namespace(filter='b', list="['hi','by']")
Gribouillis 1,391 Programming Explorer Team Colleague

define a __repr__() method.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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
Gribouillis 1,391 Programming Explorer Team Colleague

Startpage led to this blog entry. Perhaps you have lxml on one OS and not on the other.

Gribouillis 1,391 Programming Explorer Team Colleague

It is probably /usr/bin/env . Try which env in a terminal.

Gribouillis 1,391 Programming Explorer Team Colleague

Did you try with the options before the file argument ?

python -m nose.core --tests -s --with-coverage $1
Gribouillis 1,391 Programming Explorer Team Colleague

Did you check that the coverage module is installed ?

$ pydoc coverage

In linux mint, coverage is available via the package python-coverage .

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

see this thread. It looks like the same issue.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

Use startpage ! Here is a related discussion. You should try and modify net.py according to the last suggestion.

Gribouillis 1,391 Programming Explorer Team Colleague

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

  1. The Thread's run() method must contain the thread's action, instead of its __init__() method.
Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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 ?

Gribouillis 1,391 Programming Explorer Team Colleague

i guess i can use eval(str)

No! Use json.loads()

Gribouillis 1,391 Programming Explorer Team Colleague

Because in your code, package_weight is a local variable in function main(). It exists only in this function's body.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

May I suggest virtualbox + linux ? (just installed rpy2 in one click in linux mint kde)

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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))
Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

What's the output of ping run from a terminal while the script alternates return codes ?

Gribouillis 1,391 Programming Explorer Team Colleague

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.

ddanbe commented: Helpful +14
Gribouillis 1,391 Programming Explorer Team Colleague

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.

Gribouillis 1,391 Programming Explorer Team Colleague

Read the doc

Gribouillis 1,391 Programming Explorer Team Colleague

Have look at the os.walk() function.

Gribouillis 1,391 Programming Explorer Team Colleague

Dos' tasklist command seems to support connecting to a remote system.

Gribouillis 1,391 Programming Explorer Team Colleague

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()
Gribouillis 1,391 Programming Explorer Team Colleague

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)
                    ...
Gribouillis 1,391 Programming Explorer Team Colleague

In the past I used copssh on windows and it was very easy to install and use.