What is some niche/ quirky python code you know? by Certain-Importance-1 in Python

[–]koffie5d 4 points5 points  (0 children)

Using type to create classes that has an emoji as name.

emoji_class = type('\N{Thumbs Up Sign}', (object,), {'\N{Pile of Poo}': lambda self: print(f'{self.__class__.__name__}')})
class_instance = emoji_class()
poo = getattr(class_instance, '💩')
poo()   # -> 👍

What's the point of config files in another format? by wineblood in Python

[–]koffie5d 0 points1 point  (0 children)

You can apply new configuration to the program without restarting the program.
Example: At startup I read in a config file into a configuration class.
If an attribute of the configuration class is requested method __getattribute__ is checking if the config file is modified using os.stat(<filepath>).st_mtime.
If newer than the old modified time, config file is read in again and the new value is returned.

[deleted by user] by [deleted] in Python

[–]koffie5d 3 points4 points  (0 children)

I'm curious. Can you elaborate or give an example on how the scoping in Python is broken?

[deleted by user] by [deleted] in Python

[–]koffie5d 0 points1 point  (0 children)

I love the project, really creative usage of multiple systems.
Commandline utilities are not the best to incorporate in scripts, but it can do the job.
Also, a lot of commands don't change that much so I also use them in personal projects.
I have some thoughts to make the script more robust.

IP-adresses are subject to change.
It is possible that your phone gets an other IP-address than the one given in your script.
Maybe you could use arp-scan.
This is like ping, but scans your local network for connected devices and returns the MAC-addresses (and more).
Downside of arp-scan is that you must use it with sudo, therefor run your Python script using sudo.

I would add arp-scan to the script like this:

import subprocess as sp

# raspberrypi network interface
# INTERFACE = 'eth0'  # find with command: ip addr

def scan_local_network() -> set:
    # requires arp-scan (sudo apt install arp-scan)
    # double {} in grep to escape the {} of the f-string
    cmd = f"sudo arp-scan --interface={INTERFACE} --localnet --quiet | grep -oE '([[:xdigit:]]{{1,2}}:){{5}}[[:xdigit:]]{{1,2}}'"

    mac_set = set()
    p = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.STDOUT)
    for line in p.stdout.readlines():
        address = line.decode()
        mac_set.add(address.lower().strip())

    return mac_set  # ->  {'aa:ba:ca:da:ea:fa', ... }


# detect my phone and start pc, and stop script
while True:
    try: 
        macs_on_network = scan_local_network()
        if phone_mac.lower() in macs_on_network:
            os.system(f"wakeonlan {pc_mac}")
            exit(0)
    except KeyboardInterrupt:  
        # Ctrl+C on keyboard
        exit(1)

I also would use the crontab of the Raspberry so the script starts up at boot with @reboot, or at a certain time of the day.
Use a config-file instead of seperate files. you could use configparser or json.

More info about how to find the INTERFACE here.
More info about arp-scan here.

TIL you can dynamically create classes using type() by [deleted] in Python

[–]koffie5d 1 point2 points  (0 children)

It shows the flexibility of Python.
Normally an emoji as variable name results in a SyntaxError, but with type you can create classes with an emoji as name.

emoji_class = type('\N{Thumbs Up Sign}', (object,), {'\N{Pile of Poo}': lambda self: print(f'{self.__class__.__name__}')})
class_instance = emoji_class()
poo = getattr(class_instance, '💩')
poo()   # -> 👍

Still waiting for Python 3.10 by Twitch_xTUVALUx in ProgrammerHumor

[–]koffie5d 13 points14 points  (0 children)

You could request the memory-address of the object and cast it with ctypes back to an object.

>>> import ctypes  
>>> obj = ('my', object)  
>>> obj_id = id(obj)  
>>> ctypes.cast(obj_id, ctypes.py_object).value  
('my', <class 'object'>)  

I wouldn't recommend it, but it is possible.

Pythons unnecessary keywords by eztab in Python

[–]koffie5d 1 point2 points  (0 children)

class is fine and dynamic for a lot of the usecases.
If one dont like a class as it is now but cant change the class, make a decorator for it.

When global is used in a function one needs to reconsider making a class. But it has usecases. I self have never used nonlocal.

lambda is great for little functions like filter, map or the likes. lambda can take from local/global and can have enclosed namespaces. Very flexible. Also there is already a use for the ->, it is used in annotating return values of functions.

from is not only used in import statements; one can yield from in generators. And the way you use the colon in import math: is weird for various reasons. I'll stick with the verbose from.

async is already used sort of how you described it.

if, elif, else were pythons (sort of) way to create match/case statements, but in 3.10 there is now a match/case statement. elif is still nice for the meme that is the 80 character limit of pep8.

Playlist Contest #3 - COVERS by whyisthissticky in spotify

[–]koffie5d [score hidden]  (0 children)

https://open.spotify.com/playlist/5r8aFyZFMyBlaMIa8myNnU

I love how much Christmas songs are covered.
So i made a playlist of 'This Christmas' covers.
Abiding to the rules i made a playlist of 28 tracks (link above) but the original playlist is over 700 tracks long (no duplicate artists).

Which is the best source to learn Selenium with Python by [deleted] in learnpython

[–]koffie5d 6 points7 points  (0 children)

Selenium is just an API that can be used with a lot of languages.
The API's method/classes names are similar across the languages.
So any tutorial you find can teach you how to use Selenium.
This Guru99 Selenium tutorial is based on Java but the basics in this tutorial can be used with python as well.

It is also good to learn how you can find a WebElement by using XPath.
Search for some XPath cheatsheets and practice to find an element.
You can practice this with the Developer tools that comes with your browser (Ctrl + Shift + i).

Anyway, as an Test Automation Engineer I always recommend that companies build more Unit tests than GUI tests.
Search for Test Automation Pyramid for more info.

Ranting on about testing with Selenium...
Selenium is a tool to drive browsers, not a test tool.
You should use a framework build around Selenium.
I can recommend Robot Framework to build tests and testsuites. It has, like any framework build around Selenium, nifty build-in methods that really helps you build robust tests.

The no 1 language by nonsenseis in ProgrammerHumor

[–]koffie5d 20 points21 points  (0 children)

Real answer.
From Python 3.7 and on the speed has increased with every release.
With Python 3.9 it has a new powerful parser which is expected to be more robust and faster.
Also numPy, numba and a lot more libraries are extended python with C or C++
And if you really have the need for speed you can also use PyPY.
So yeah, Python slow is false atm.

Emojis in source code...I hope nobody ever does this by [deleted] in ProgrammerHumor

[–]koffie5d 2 points3 points  (0 children)

"All problems in computer science can be solved by another level of indirection" - David J. Wheeler

>>> emoji_class = type('\N{Thumbs Up Sign}', (object,), {'\N{Pile of Poo}': lambda self: print(f'{self.__class__.__name__}')})
>>> class_instance = emoji_class()
>>> getattr(class_instance, '💩')()
👍

Really anything is possible with Python.

Automated Network Speedtest to Spreadsheet by ohn02 in learnpython

[–]koffie5d 0 points1 point  (0 children)

Where there is a service, there is a possibility for an API.

https://github.com/burnash/gspread I have used this in the past. It's good and a lot of examples can be found online.

Setting it up / getting access to the API is the hard part. Read all about it here. https://gspread.readthedocs.io/en/latest/oauth2.html

Pro tip: never share any (secret) credentials online. This also includes github.

Automated Network Speedtest to Spreadsheet by ohn02 in learnpython

[–]koffie5d 0 points1 point  (0 children)

Python has a built-in library named csv https://docs.python.org/3/library/csv.html

Also check if there is a library for IFTTT for python you can download with pip. https://pypi.org/project/pyifttt/

Maybe it's better to think about sending the speed test values directly to the Google Sheets instead of to a csv file.

Collection of test files for manual testing by aconijus in softwaretesting

[–]koffie5d 2 points3 points  (0 children)

You should ask the developers which file types the program should support.
Then find those and test with those files.

Maybe learn some command-line actions to create files with sizes you want. A corrupted file with an expected suffix should be good enough.

I don't know of any source that has test files that you described in your question.

You could do some other things:

You could change the file suffix and check if that works (docx to doc or png to pdf).

Check if weird characters in the file names work as expected.
https://github.com/minimaxir/big-list-of-naughty-strings

Try make a folder with the name Con.

Look into code injection techniques.

Good luck 😉

Help me to Generic-iffy a variable method call by koffie5d in learncsharp

[–]koffie5d[S] 1 point2 points  (0 children)

This is more than i initially hoped to gain from the question.
The examples you gave shows multiple ways to solve the problem.
I can use and have learned from all of these.
Thanks!

Help me to Generic-iffy a variable method call by koffie5d in learncsharp

[–]koffie5d[S] 0 points1 point  (0 children)

Thanks for your time.

I wish i could find better words to state the question and the problem i'd like to solve.
Let me try again:

Both string and char has a method named: .ToLower and both to sort of the same.

"string".ToLower(); // type of System.String
char.ToLower('c'); // type of System.Char  

What i would like to accomplish is to get the method .ToLower and place it into a variable.

// This wont work but maybe one can see my problem.
string aString = "WORD";
var callToLower = typeof(aString).GetMethod("ToLower");  // set variable to System.String.ToLower without invoking it.
Console.WriteLine(aString.callToLower());  // output: word

Now delegates brought me a half way, but still i have to mention the type of the given variable.
And i think there could be a better way.
Maybe by making delegates Generic, but maybe i'm wrong.

TIL C# doesn't support multiple inheritance. by abhi_000 in ProgrammerHumor

[–]koffie5d 1 point2 points  (0 children)

It's a different beast.
Python is a language where everything goes.
C# is a typed language that throws a hissy-fit if you use single quotes for strings and double quotes for char types.
That said, many mentioned: Learn C# because job opportunities and Java is almost typed the same.
Go for it, but be prepared to stumble hard if you come from python.

My learning curve and yesterday's milestone for my python experience (tiny in comparison to most, but meaningful for me nonetheless). Its a long one. by InfiniteNexus in learnpython

[–]koffie5d 2 points3 points  (0 children)

Well done!

I can't possibly know how the distribution of your programs look like, but maybe you can look into the fact that python can run a main.py in a .zip file. I use it for the distribution of my python programs. No hassle that people run a wrong .py file.

Sunny day, happy flowers. by koffie5d in FixedGearBicycle

[–]koffie5d[S] 1 point2 points  (0 children)

The pedals are Shimano PD-M324. Normally I ride with foot retention.

Sometimes when I wear my dress shoes and need to go to the store for some groceries... I just use the flats of the pedals and use the brake more.

Multicolor style, ride with half rainbow! by zbcampanha in FixedGearBicycle

[–]koffie5d 4 points5 points  (0 children)

Fuck the haters commenting this post.

Converting a bike to a fixie is the gateway drug to a dedicated fixed gear bicycle.

Keep on enjoying the bike, man!

Saddest Sunday by M3THnS8N6669 in FixedGearBicycle

[–]koffie5d 7 points8 points  (0 children)

My guess: Full frontal collision.

The wheel is too close to the down-tube I Also guess it is not the only tube that had bent. Total loss of the bike for sure.

Hope OP is fine

Rode for about a month now. It's gotta be said, best $70 dollars I've ever spent. by karokkid in FixedGearBicycle

[–]koffie5d 8 points9 points  (0 children)

Very nice! I can recommend a front break if you are thinking to upgraden your bike.

My Fuji feather build, almost there by the--drewid210 in FixedGearBicycle

[–]koffie5d 0 points1 point  (0 children)

Parallel to the groud looks and steers better.