Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that you write from tkinter import * after from graphics import *. Some objects defined in the graphics.py package get shadowed by objects defined in the tkinter package. In this case, the graphics.py Text class is shadowed by the tkinter Text widget. The best thing to do is to avoid the import * idiom, especially with tkinter. You can do

import tkinter as tk

...

root = tk.Tk()

The code works this way. It would be a good idea to add a button to kill the window and exit the game, because I had to kill the process from the outside.

Gribouillis 1,391 Programming Explorer Team Colleague

Read the file by chunks and also write chunks:

with open("portrait1.dng", "rb") as binaryfile :
    with open("readfile.raw", "wb") as newFile:
        while True:
            chunk = binaryfile.read(4096)
            if not chunk:
                break
            newFile.write(binascii.hexlify(chunk))

my whole university life is on this (translation, if it dies i die).

Make sure you backup your files regularly on a separate disk.

Gribouillis 1,391 Programming Explorer Team Colleague

Before even thinking of using python for this, you need to define what the computer will do and what the human player(s) will do. You don't need a specific programming language for this.

Gribouillis 1,391 Programming Explorer Team Colleague

Don't use readline() with binary files, because they are not organized in lines. If this is a big file, invoke read() with a size argument to read iteratively chunks of binary data.

with open(filename, 'rb') as infile:
    while True:
        data = infile.read(1024)
        if not data:
            break # we have reached the end of the file
        # do something with the bytes read
        print(hexlify(data).decode('utf-8'))
Gribouillis 1,391 Programming Explorer Team Colleague

In python 3, the value returned by binascii.hexlify() is a bytes instance instead of a str instance. As setText() is expecting a str instance, you need to convert hexadecimal to str. This is done by

hexa_str = hexadecimal.decode('utf-8')
Gribouillis 1,391 Programming Explorer Team Colleague

The sorted() function has a boolean reverse parameter that allows to sort in descending order

sorted(lines, key=itemgetter(3), reverse=True)

This is much more efficient than trying to write your own quicksort method.

Gribouillis 1,391 Programming Explorer Team Colleague

Strange code and strange specifications as usual, but well ... Two points:

  1. Why do you want the vector to hash as a tuple ? What's the use of this ? There must be a good reason as this breaks your code.
  2. There is a serious drawback in your properties: the vector instances inserted in the dictionaries will never be garbage collected. The properties' dictionaries create memory leak.

Here is a version that addresses both issues. I aggregate a new small object named _key to each vector and this object is hashed in the property dictionary instead of the vector instance. Second, I use a WeakKeyDictionary, so that vectors can again be garbage collected.

from weakref import WeakKeyDictionary

def newProp():
    newdict = WeakKeyDictionary()
    def getter(vec):
        return newdict.get(vec._key)
    def setter(vec, val):
        newdict[vec._key] = val
    def wrapper(vec,val):
        if val is None: return
        vtype = val.__class__
        if vtype is str: setter(vec, float(val) ); return
        if numtype(vtype): setter(vec,val)
    return property(getter, wrapper)

class Key(object):
    __slots__ = ('__weakref__',)

class vector(object):
    __slots__ = ('_key',)
    X = newProp()
    Y = newProp()
    Z = newProp()
    W = newProp()
    def __init__(vec, *other): # other is for special initialization
        vec._key = Key()
        vec.X = vec.Y = vec.Z = vec.W = None
    def __hash__(vec):
        return hash( (vec.X, vec.Y, vec.Z, vec.W) )

def main():
    v = vector()
    print(hash(v))

if __name__ == '__main__':
    main()

I'm sure you won't like this, but you can still change your specifications and your algorithm.

rproffitt commented: Classy. +12
Gribouillis 1,391 Programming Explorer Team Colleague

There is something interesting in your last post. You could indeed create a single UVproxy for each facepoint, only if and when it is needed. Just like a cached property. It would work very well.

Gribouillis 1,391 Programming Explorer Team Colleague

The 7L comes because you are using python 2 instead of python 3, which I disapprove, but it is your choice, and there are two integer types in python 2, namely int and long, so 7L is a long because the module you used to read the database returns long integers when it meets an integer.

As the Grid only accepts str and unicode value, we're going to convert the value

import datetime # <-- this near the top of your file

# ...

for i, seq in enumerate(data):
    for j, v in enumerate(seq):
        if isinstance(v, (int, long,)):
            v = str(v)
        elif isinstance(v, datetime.datetime):
            v = v.strftime('%Y-%m-%dT%H:%M:%S.%f')
        try:
            self.SetCellValue(i, j, v)
        except TypeError:
            raise RuntimeError(('SetCellValue failed with TypeError', i, j, v))
Gribouillis 1,391 Programming Explorer Team Colleague

Why not return iterables indeed? It all depends on what the user wants to do with it. The risk is to store a whole list of all instances when one only needs a few of them. I like the UVproxy solution because I already used such objects in the past with connection to databases and they turned out to be very flexible: it is easy to fine tune the behaviour of the proxies.

Concerning the video, it is a modern trend to say that OOP is bad. I think it is pure ideology. Consider how OOP spontaneously appeared in the 70's. At that time, good C programmers who used C structures (struct) wrote bunches of helper functions to manipulate these structures. The object appeared from packing up the structure and the helper functions in a single entity.

This original version of OOP is fundamentally GOOD, it was a great progress in programming. Big OOP theories and constructions with a lot of subclassing are probably bad. Some people now think they will gain flexibility by unpacking the whole thing, and in a way it is true, but it comes at the cost of an efficient program's organization and I think there are other ways. I tried to develop small entities centered around an algorithm instead of a piece of memory. I call them algons, grains of algorithms. I think there are other ways to flexibility than simply throw away OOP.

So, if you want my advice, don't rush to follow this …

Gribouillis 1,391 Programming Explorer Team Colleague

A remark: if you create a lot of proxies such as UVProxy above, it is a good idea to make them flyweight by using the __slot__ attribute. Basically, they are nothing more than a smart pointer.

Gribouillis 1,391 Programming Explorer Team Colleague

The error means that you tried to insert in a grid cell a value v which type is not str or unicode, and the Grid type doesn't accept that. We can get more information about what this value was by using

for i, seq in enumerate(data):
    for j, v in enumerate(seq):
        try:
            self.SetCellValue(i, j, v)
        except TypeError:
            raise RuntimeError(('SetCellValue failed with TypeError', i, j, v))

When we'll see which value v was rejected, we'll be able to take appropriate action such as inserting nothing, or another value.

Gribouillis 1,391 Programming Explorer Team Colleague

It's impossible that facepoint.UV behaves like facepoint.UV[0], because the result of facepoint.UV[1] would be the same as facepoint.UV[0][1]: in facepoint.UV[1], the expression facepoint.UV is computed first. There is no way out of this in python.

What you could do is that facepoint.UV returns a proxy of the real UV. I'm thinking about a symbolic reference that stores nothing but the facepoint. Something along the line of

class UVdescriptor(object):
    def __get__(self, obj, cls):
        if obj is not None:
            return UVproxy(obj)

class Facepoint(object):
    UV = UVdescriptor()

def _getuvitem(facepoint, index):
    return backend_peer(facepoint).UV[index]

def _setuvitem(facepoint, index, value):
    backend_peer(facepoint).UV[index] = value

class UVproxy(object):
    def __init__(self, facepoint):
        self.facepoint = facepoint

    def __getitem__(self, index):
        return _getuvitem(self.facepoint, index)

    def __setitem__(self, index, value):
        _setuvitem(self.facepoint, index, value)

However there is a good chance that you reach only an illusory feeling of security with your proxies. You know that python code has very powerful introspection capabilities and it is a real challenge to ensure that the user of some python code can not completely expose the inside.

Gribouillis 1,391 Programming Explorer Team Colleague

Hi Tcll, it's been a while indeed!

I don't think there is a flaw in python's descriptor implementation. Also I don't understand why you think there is a security issue nor which 'private object' is 'passed into your backend'.

If Attr is a descriptor in the class, then indeed Instance.Attr is translated in Instance.__class__.Attr.__get__(Instance, Instance.__class__).

It can't be Instance.__class__.Attr because the value of Instance.__class__ is simply the class and does not remember which instance it was accessed from. It means that we need the instance again to retrieve the value of the attribute.

Perhaps you want to implement an alternative to python's descriptors, an object to put in the class that would have __getitem__ and __setitem__ methods instead of __get__ and __set__ methods. But why would this be better? can you explain in a more detailed way ?

Gribouillis 1,391 Programming Explorer Team Colleague

Hi, it's been a long time since I last used wxpython, but I think it should be something like

for i, seq in enumerate(data):
    for j, v in enumerate(seq):
        self.SetCellValue(i, j, v)

You should find good examples in the Mouse vs Python series, which cover many things concerning wx python, see this article for an introduction to grids.

Also don't miss the class reference such as this one.

Gribouillis 1,391 Programming Explorer Team Colleague

I tried to make all the print statements python2/python3 compatible

Do you know you can use

 from __future__ import print_function

to get immediate compatibility ?

Gribouillis 1,391 Programming Explorer Team Colleague

I'm sure only a few of us know that dazah was already online in year 2000!

Gribouillis 1,391 Programming Explorer Team Colleague

Well, you can use P_1*.txt to work only with these files. For the rna files, you can use rna*.txt or simply rna* if only .txt files start with this prefix.

Note that if you know regular expressions (the re module), you can get a regular expression equivalent to your glob pattern by using fnmatch.translate(), for example

>>> import fnmatch
>>> fnmatch.translate('P_1*.txt')
'P_1.*\\.txt\\Z(?ms)'

The re module could be used for more sophisticated filtering.

Gribouillis 1,391 Programming Explorer Team Colleague

@Sue_2 You can improve this by opening the ouput file only once. Also, you can use fileinput to iterate over the lines of many files

with open('merge_BLASTP_results.out', 'w') as f:
    for line in fileinput.input(glob.glob('/Users/sueparks/BlastP_Results/*')):
        f.write(line)  # write lines to new file

Also * may be a little too permissive, if the directory contains binary files for example. Depending on what you need, *.txt
or *.dat for example is safer.

Gribouillis 1,391 Programming Explorer Team Colleague

Is there a setup.py file in the extracted hierarchy? If so, open a terminal (cmd window), go to the directory where the setup.py file is and type python setup.py install. Before that, make sure that the python command invokes the python 3.6 interpreter.

EDIT: from what I read on the pyqt5 website, the best way to install pyqt5 is not by downloading the zip file, but by running

pip3 install pyqt5

in a cmd window, or perhaps py -m pip install pyqt5 (because the pip interface changed slightly in python 3.4 and I don't use windows)

Don't you have a C:\Python36 folder ? You can get the path to your python executable by running

python -c "import sys; print(sys.executable)"

You can get the paths that python use to import modules by running

python -c "import sys; print(sys.path)"
Gribouillis 1,391 Programming Explorer Team Colleague

There will probably be some time before Dani is given a fine for abusing market dominance ;)

Gribouillis 1,391 Programming Explorer Team Colleague

Well, engines such as Qwant seem to be on their way to partially achieve these incredibly complicated and expensive tasks. I don't think their financial wealth and their software production capabilities are anywhere near Microsoft's. Of course, only a small number of people will favour their search engine in the beginning, but it's growing: I discovered them less than one month ago!

cereal commented: Thanks for sharing, Qwant seems great! +0
Gribouillis 1,391 Programming Explorer Team Colleague

There are other engines, such as Startpage, I know a french engine named Qwant, a german engine named Metager, etc. If you had your own engine, you could insert some Dazah results: you're the master in your own house. You don't need to gain a massive traffic similar to Google's.

Gribouillis 1,391 Programming Explorer Team Colleague

@alc6379 The code reads a list of file names in an excel (xlsx) file. The image files (.jpg) are displayed in a resizable window and the video files (mp4) are played in an external process with a player named omxplayer. As this thread is 6 months old, I suspect Nazneen_1 has finished rewriting the code by now :)

ddanbe commented: Yep! +15
rproffitt commented: Here's to hope. +12
Gribouillis 1,391 Programming Explorer Team Colleague

I don't think it's correct to blame Google for Q&A sites' success. I think these sites meet a specific programmers' need: we want to use software and libraries and we don't have time to learn APIs or read every manual. So we need expert answers to specific use cases. The Q&A site fills the gap between the use case and the API.

Gribouillis 1,391 Programming Explorer Team Colleague

As long as you think the result of an expression is a string, you can append a string operation. For example the result of raw_input('name? ').strip() is a string, so I can append .capitalize(). The same applies to any data type.

Gribouillis 1,391 Programming Explorer Team Colleague

You wrote raw_input(nameAsk) instead of raw_input('What is your name'). I would also use a while loop. The idiom while True means repeat indefinitely, so my loop runs until the break statement exits the loop. The advantage is that I don't have to write the raw_input() statement twice.

while True:
    name = raw_input('What is your name: ').strip()
    if len(name) >= 2:
        break

for c in name:
    print ord(c),

By the way, why are you learning with python 2 instead of python 3 ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you have a working solution, it's OK, although I don't see the difference with my solution...

Gribouillis 1,391 Programming Explorer Team Colleague

It's hard to believe, can you post the same screenshot, but with the code window this time? Or perhaps the console is a part of the Geany editor ? IDE's such as Geany may redefine sys.stdin. Did you try the code in a true terminal?

Gribouillis 1,391 Programming Explorer Team Colleague

No, no, you don't have to play with the select function's arguments. These must be lists of python files, or linux file descriptors. To make things simpler, I wrapped the call to select in a function my_raw_input() that you can use. It works like raw_input(), but it accepts a timeout argument

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

from select import select
import sys

class TimeoutError(RuntimeError):
    pass

def my_raw_input(prompt='', timeout=-1):
    if timeout < 0:
        return raw_input(prompt).decode(sys.stdin.encoding)
    print(prompt, end = '')
    sys.stdout.flush()
    rlist, wlist, xlist = select([sys.stdin],[],[], timeout)
    if rlist:
        return sys.stdin.readline().decode(sys.stdin.encoding).strip('\n')
    else:
        raise TimeoutError

def main():
    try:
        char = my_raw_input('Enter a char: ', timeout=5)
    except TimeoutError:
        print("\nSorry, too late")
        return
    print('You entered', char)

if __name__ == '__main__':
    main()

You can see in the main() function how to use the my_raw_input() function. Note that it works like raw_input, which means that you need to hit the enter key after your input.

Edit: I changed the code so that my_raw_input() returns a unicode string. This is especially useful if you commonly write
non english words, such as french words with accents.

rproffitt commented: Timeouts are nice. +12
Gribouillis 1,391 Programming Explorer Team Colleague

See how your code looks better after I used the astyle beautifier

astyle --style=python --align-pointer=middle --max-code-length=79 atm.c

For human readers, formatting matters in programming

#include<stdio.h>
#include<conio.h>
void main() {
    float bal=0,dep=0,withd=0;
    int n1,n2;
    clrscr();
    do {
        clrscr();
        printf("\n\t\t************************\t\t\n");
        printf("\t\tWelcome To ATM Services\n");
        printf("\t\tSelect Your Choice:\n");
        printf( "\t\t1)Deposit Cash\n\t\t2)Withdraw Cash\n\t\t3)Bank Statement\n\t\t4)Fast Cash\n\t\t5)Exit\n");
        printf("\t\t***********************\t\t\n");
        scanf("%d",&n1);
        switch(n1) {
        case 1: printf("Enter the amount to be deposited\n");
            scanf("%f",&dep);
            if(dep>0) {
                bal+=dep;
                printf("You have deposited %f cash. Your current account balance is %f\n",dep,
                    bal); }
            else printf("Invalid amount entered\n");
            printf("Press any key to continue\n");
            break;
        case 2: printf("Enter the amount to be withdrawn\n");
            scanf("%f",&withd);
            if(withd<bal && withd>0) {
                bal-=withd;
                printf("You have withdrawn %f cash. Your current account balance is %f\n",
                    withd,bal); }
            else printf("Insufficient funds in your account\n");
            printf("Press any key to continue\n");
            break;
        case 3:  printf("\t\tYour Current Bank Statement Is:\n");
            printf("\t\t Your account balance is %f.\n",bal);
            printf("Enter any key to continue");
            break;
        case 4: printf("\t\tWelcome To FastCash\n");
            printf("\t\tSelect an alternative:\n");
            printf("\t\t1)Rs100\n\t\t2)Rs500\n\t\t3)Rs1000\n");
            scanf("%d",&n2);
            switch(n2) {
            case 1: printf("You have chosen to withdraw Rs100\n");
                if(bal>=100) {
                    bal-=100;
                    printf("You have withdrawn Rs100. Your balance is %f\n",bal);
                    printf("\t\tPlease Collect Your Cash\n"); }
                else printf("Insufficient Funds in account");
                break;
            case 2: printf("You have chosen to withdraw Rs500.\n");
                if(bal>=500) {
                    bal-=500;
                    printf("You have withdrawn Rs500. Your account balance is %f\n",bal);
                    printf("\t\tPlease Collect Your Cash\n"); }
                else printf("insufficient Funds");
                break;
            case 3: printf("You have chosen to withdraw Rs1000\n");
                if(bal>=1000) {
                    bal-=1000;
                    printf("You have withdrawn Rs1000. Your account balance is %f\n",bal);
                    printf("\t\tPlease Collect Your Cash"); }
                else printf("Insufficient Funds");
                break;
            default: …
Gribouillis 1,391 Programming Explorer Team Colleague

The print part may be a problem if you are using python 2 instead of python 3. If this is the case, my advice is to always write

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

at the very top of every new python 2 program. Among other benefits, the print statement is replaced by a print function with python 3 behavior.
It would be even better to switch to python 3. Python 2 support ends in 2020!

If you don't want all this, you can simply write

print 'Please type something: ',

(notice the comma at the end of the statement)

The select.select() function is an old unix function that comes directly from the C language. It is a part of the Posix standard. It is the traditional linux way for programs to wait until an input/output file descriptor is available. You should start with this function's documentation to understand the arguments.

Gribouillis 1,391 Programming Explorer Team Colleague

This is a long post and there are many questions. Let's first start with a simple code that waits for console input with a timeout. A correct way to do it is by using select.select().

from select import select
import sys

def main():
    timeout = 5
    print('Please type something: ', end = '')
    sys.stdout.flush()
    rlist, wlist, xlist = select([sys.stdin],[],[], timeout)
    if rlist:
        data = sys.stdin.readline()
        print('you entered', data)
    else:
        print('\nSorry, {} seconds timeout expired!'.format(timeout))

if __name__ == '__main__':
    main()

I'll try to understand your code and see how you can add threads in this. Two remarks first

  • It is not usually a good idea to mix calls to time.sleep() with threads. There are other ways to wait, such as queue input and output, the threads join() method, or Lock and Conditions objects etc
  • For your second error, you wrote putEchar() instead of PutEchar()

Edit: actually, I'm not sure the select.select method works in Windows OS. If you're in windows, tell me if it works.

Gribouillis 1,391 Programming Explorer Team Colleague

@jklotzner Thank you for the input, but this has nothing to do with today's python vs yesterday's python. The difference is that your code is written in the local namespace of a main() function while pyTony's code is written in the global namespace. A python program does not need a main() function, although it is often used.

Apart from that do you know that before python 2, there was a python 1? It is still available at python.org. Python 1.5.2 was a very very successful realease :-)

Gribouillis 1,391 Programming Explorer Team Colleague

@sekmani Hi, yes you can directly print my_queue.get(). Also it is a good habit to call my_queue.task_done() after each call to my_queue.get(), although in this simple example, it doesn't change anything. Note that thread1.join() doesn't need to be called before my_queue.get(). You can join the thread at the end of the program, or at any moment when you need to be sure that the thread is finished.

Gribouillis 1,391 Programming Explorer Team Colleague

@diafol You'll probably have a slightly better experience with Idlex, which enhances idle with some missing functionalities. However, a powerful editor such as Kate may be more comfortable to use than an Ide for python.

Gribouillis 1,391 Programming Explorer Team Colleague

Yes this one. It usually works very well to detect installed OSes and repair the boot.

Gribouillis 1,391 Programming Explorer Team Colleague

@DubWine hi, it seems that there are solutions by using the ctypes module and the setconsolewindoinfo method in windows api. See https://stackoverflow.com/questions/3646362/how-to-control-the-size-of-the-windows-shell-window-from-within-a-python-script for example. Also google the keywords python and setconsolewindowinfo.

Edit: you can also read the console dimension without a subprocess as in http://rosettacode.org/wiki/Terminal_control/Dimensions#Python

rproffitt commented: + for Rosettacode. Amazing resource. +12
Gribouillis 1,391 Programming Explorer Team Colleague

I think you get this error because of with open(f, 'r') as var1. It should be
with open(os.path.join(destdir, f), 'r') as var1.

A more up-to-date approach is to use module pathlib

from pathlib import Path
destdir = Path('pathtofile')
files = [p for p in destdir.iterdir() if p.is_file()]
for p in files:
    with p.open() as f:
        ...
Gribouillis 1,391 Programming Explorer Team Colleague

I think you need a file complex.h containing the line

void read_comp(complex, int, int);
Gribouillis 1,391 Programming Explorer Team Colleague

You need at least a return r statement in c(). Also, if you have more errors, please post the whole exception traceback. There are other errors: process_files() expects a sequence of file names, but c() can produce only one file name, you could call process_files([r]) for example.

Gribouillis 1,391 Programming Explorer Team Colleague

Which value is not passed to the function ? Is it the call to processFile(x) ? Did you
try to add statements such as print(sys.argv[1:]) before line 21 or print(x) at the beginning of processFile() ? You could use my printat snippet to help you debug this https://www.daniweb.com/programming/software-development/code/479747/print-with-line-and-file-information

Some remarks

  • Configure you editor to indent python code with 4 space characters when you hit the tab key.
  • Testing against None is best done with if value is not None instead of if value != None
  • It seems to me there is a risk that statement at line 18 fails because lastline could be None.
Gribouillis 1,391 Programming Explorer Team Colleague

The only problem I'm encountering is that I cannot create enough names for all of this by hard-coding it

I'm not sure I understand this question very well. It seems to me that you want to create many instances of a certain class but you don't want to create a variable name for each instance. The solution is to store the instances in one of the many container classes that come with python: list, set, dict, deque, etc.

Gribouillis 1,391 Programming Explorer Team Colleague

It is because after age = raw_input('...'), age is a character string. It needs to be converted to an integer like this

age = raw_input ('enter you age-->')
age = int(age)
Gribouillis 1,391 Programming Explorer Team Colleague

I recommend using the built-in csv module to read csv files. You can simply use

import csv
with open('eggs.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    data = [row[3:] for row in spamreader]
print(data)
Gribouillis 1,391 Programming Explorer Team Colleague

If there is no lines[-1] it means that the lines list is empty (there is no last item). Try to check the length of the list first.

Gribouillis 1,391 Programming Explorer Team Colleague

Normally, the exception traceback that python prints on the screen tells you the line number and statement where the error occurred. Can you post the whole traceback ?

Gribouillis 1,391 Programming Explorer Team Colleague

@James_77 I would try to use the timezone data available in the dateutil module, for example

>>> import dateutil.tz
>>> from datetime import datetime
>>> spain = dateutil.tz.gettz(name='CET')
>>> d = datetime(2017, 3, 15, 17, 14, tzinfo = spain)
>>> d.utctimetuple()
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=15, tm_hour=16, tm_min=14, tm_sec=0, tm_wday=2, tm_yday=74, tm_isdst=0)
>>> d.utcoffset()
datetime.timedelta(0, 3600)

There may be some more work involved, because in summer, Madrid uses CEST instead of CET for example.

Gribouillis 1,391 Programming Explorer Team Colleague

@prince_16 Many python snippets written 7 years ago were written in python 2. That's why they don't work out of the box in python 3. However they can be easily adapted to python 3 with minor changes or with the help of the 2to3 tool.

It is not useful to revive old threads like this. Start your own thread instead with the code you're working on.

Gribouillis 1,391 Programming Explorer Team Colleague

You're right. It may be the tag system that gives the impression that the site is a tote. There used to be a section for each language for example, now every programming thread is in 'Programming Forum > Software Development Forum' and nothing else.

JamesCherrill commented: Yes, I really miss the Java forum +0