Thu, Apr 18, 8:22 PM CDT

Welcome to the Poser Python Scripting Forum

Forum Moderators: Staff

Poser Python Scripting F.A.Q (Last Updated: 2024 Mar 19 1:03 pm)

We now have a ProPack Section in the Poser FreeStuff.
Check out the new Poser Python Wish List thread. If you have an idea for a script, jot it down and maybe someone can write it. If you're looking to write a script, check out this thread for useful suggestions.

Also, check out the official Python site for interpreters, sample code, applications, cool links and debuggers. This is THE central site for Python.

You can now attach text files to your posts to pass around scripts. Just attach the script as a txt file like you would a jpg or gif. Since the forum will use a random name for the file in the link, you should give instructions on what the file name should be and where to install it. Its a good idea to usually put that info right in the script file as well.

Checkout the Renderosity MarketPlace - Your source for digital art content!



Subject: Useful Code Snippets


  • 1
  • 2
adp001 ( ) posted Wed, 03 November 2021 at 3:16 AM

Maybe this one is more robust:

fname = os.path.join(os.environ["APPDATA"], "Poser", str(version), "LibraryPrefs.xml")
if not os.path.exists(fname):
fname.replace("Poser", "Poser Pro")




structure ( ) posted Wed, 03 November 2021 at 3:37 AM · edited Wed, 03 November 2021 at 4:41 AM
Forum Coordinator

adp001 posted at 3:16 AM Wed, 3 November 2021 - #4429836

Maybe this one is more robust:

fname = os.path.join(os.environ["APPDATA"], "Poser", str(version), "LibraryPrefs.xml")
if not os.path.exists(fname):
fname.replace("Poser", "Poser Pro")
that works fine thank you 

How do we take into account, poser builds from 11.2 and poser builds past 12 - right now this is adequate for my needs, but do we just update it for every build?

do remember to edit the line
fname.replace("Poser", "Poser Pro") to read

fname = fname.replace("Poser", "Poser Pro")

Locked Out


adp001 ( ) posted Wed, 03 November 2021 at 3:55 AM

In my opinion, a version number should not be assumed to be a float. Version numbers can also look like this: "12.3.0.3". This is where "float" fails severely.

My method is something like Python's "sys.version_info.major", where Python's version number contains several decimal points.




adp001 ( ) posted Wed, 03 November 2021 at 3:59 AM
structure posted at 3:37 AM Wed, 3 November 2021 - #4429837

How do we take into account, poser builds from 11.2 and poser builds past 12 - right now this is adequate for my needs, but do we just update it for every build?

Since we can't guess which scheme Bondware will follow for the version numbers and the resulting file structure, there is nothing left to do but wait until the case occurs that it doesn't work as it is anymore :)





structure ( ) posted Wed, 03 November 2021 at 4:11 AM
Forum Coordinator
adp001 posted at 3:55 AM Wed, 3 November 2021 - #4429838

In my opinion, a version number should not be assumed to be a float. Version numbers can also look like this: "12.3.0.3". This is where "float" fails severely.

My method is something like Python's "sys.version_info.major", where Python's version number contains several decimal points.

right - this would be a better method

Locked Out


adp001 ( ) posted Wed, 03 November 2021 at 5:27 AM
structure posted at 3:37 AM Wed, 3 November 2021 - #4429837

do remember to edit the line
fname.replace("Poser", "Poser Pro") to read

fname = fname.replace("Poser", "Poser Pro")

Ups!

Maybe post a complete and tested version. I'm working out of the blue at the moment because I don't have a working Poser version here anymore.




structure ( ) posted Wed, 03 November 2021 at 5:29 AM
Forum Coordinator

ok - will do that soonly - why no working poser?

Locked Out


structure ( ) posted Wed, 03 November 2021 at 5:35 AM · edited Wed, 03 November 2021 at 5:36 AM
Forum Coordinator

tested and working :

def get_library_paths():
    version = int(poser.Version().split(".")[0]) if globals().get("poser", False) else 12
    fname = os.path.join(os.environ["APPDATA"], "Poser", str(int(version)), "LibraryPrefs.xml")
    if not os.path.exists(fname):
        fname = fname.replace("Poser", "Poser Pro")
    re_libs = re.compile(r"<ContentFolder.*?folder=\"([^\"]+)\"")
    if os.path.exists(fname):
        with open(fname, "r") as fh:
            for line in fh:
                res = re.search(re_libs, line)
                if res:
                    yield res.group(1)
if __name__ == "__main__":
    for entry in get_library_paths():
        print(entry)

Locked Out


adp001 ( ) posted Wed, 03 November 2021 at 6:29 AM

structure posted at 5:29 AM Wed, 3 November 2021 - #4429845

ok - will do that soonly - why no working poser?

Fine.

Rest: See sitemail.




adp001 ( ) posted Wed, 03 November 2021 at 4:01 PM
adp001 posted at 2:49 AM Wed, 3 November 2021 - #4429830

class ignore_error(object):
    def __init__(self, *args):
        self.tolerable = args

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else True


with ignore_error(NameError, poser.error):
    actor = poser.Scene().Actor("not existing actor")




Made a mistake in:

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else True

the default result must be False, not True:

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else False






structure ( ) posted Thu, 04 November 2021 at 4:38 AM · edited Thu, 04 November 2021 at 4:52 AM
Forum Coordinator

adp001 posted at 2:49 AM Wed, 3 November 2021 - #4429830


class ignore_error(object):
    def __init__(self, *args):
        self.tolerable = args

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else True


with ignore_error(NameError, poser.error):
    actor = poser.Scene().Actor("not existing actor")




Made a mistake in:

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else True

the default result must be False, not True:

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else False



nice addition,  this could be used in conjunction with contextlib.suppress
which captures all kinds of errors and ignores them.

in this simple example, I am trying to print a non-digit string as an integer,
and the output is suppressed. 


import contextlib

with contextlib.suppress(NameError, TypeError, WindowsError):
    def do_something(*args, **kwargs):
        try:
            print(int(message))
        except ValueError:
            raise TypeError("%s is invalid" %(message))

    message = "nothing to see here, move along"
    do_something()


without the contextlib.suppress in place the output is 
TypeError: nothing to see here, move along is invalid

In the following amended example the output is printed as
nothing to see here, move along

import contextlib

with contextlib.suppress(NameError, TypeError, WindowsError):
    def do_something(*args, **kwargs):
        try:
            print(message)
        except ValueError:
            raise TypeError("%s is invalid" %(message))

    message = "nothing to see here, move along"
    do_something()

            

I am unsure that I have found every type of python error, but here is an
almost comprehensive list of errors that contextlib.suppress can capture. 

errorlist = [ArithmeticError, AssertionError, BrokenPipeError, BufferError,
ChildProcessError, ConnectionAbortedError,  ConnectionError,
ConnectionRefusedError, ConnectionResetError, EOFError, FileExistsError,
FileNotFoundError, FloatingPointError, ImportError, IndentationError,
IndexError, InterruptedError, IsADirectoryError, KeyError, LookupError,
MemoryError, ModuleNotFoundError, NameError, NotADirectoryError,
NotImplementedError, OverflowError, ProcessLookupError, ReferenceError,
RuntimeError, SyntaxError, SystemError, TabError, TimeoutError, TypeError,
UnboundLocalError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError,
ValueError, WindowsError, ZeroDivisionError, ]

Locked Out


structure ( ) posted Thu, 04 November 2021 at 5:45 AM · edited Thu, 04 November 2021 at 7:54 AM
Forum Coordinator

Get poser AppLocation outside of poser ( WINDOWS ONLY ) (you need to add this to POSER_FAKE by adp001, a separate file would be the best option probably. e.g. in the poser fake folder, add Applocation.py)

import winreg as reg
import POSER_FAKE as poser

class _REGISTRY:
    def _find_poser_win(self, version):
        # versions = ( 11, 12 ) # select version you want
        poser = r"SOFTWARE\Poser Software\Poser\Poser %d" %version
        with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, poser ) as key:
            if poser.endswith( str(version) ) and key:
                return(reg.QueryValueEx(key, "InstallDir" )[0])

def AppLocation(installdirs = []):
    installdir = _REGISTRY()._find_poser_win(Version())
    if not installdir in installdirs:
        installdirs.append( installdir )
    return os.path.join(installdir, "Poser.exe")
print(poser.AppLocation())


Locked Out


structure ( ) posted Thu, 04 November 2021 at 6:07 AM · edited Thu, 04 November 2021 at 6:40 AM
Forum Coordinator

get poser templocation / prefslocation outside of poser (you need to add these to POSER_FAKE by adp001, separate files would be the best option probably. e.g. in the poser fake folder, add Templocation.py and PrefsLocation.py)

import POSER_FAKE as poser

def TempLocation():
    return os.path.join(os.environ["TEMP"],"Poser")
def PrefsLocation():
    if Version() >= 11.2 or Version() < 11.2 and not IsPro():
        return os.path.join(os.environ["APPDATA"], "Poser", str(int(Version())))
    elif Version() < 11.2 and IsPro():
        return os.path.join(os.environ["APPDATA"], "Poser Pro", str(int(Version())))
    else:
        return None


def Version():
    return 12

def IsPro():
    return True

print(poser.TempLocation())
print(poser.PrefsLocation())


you should likely add checks to see if the actual location exists. 



Locked Out


adp001 ( ) posted Fri, 05 November 2021 at 6:37 PM
structure posted at 4:38 AM Thu, 4 November 2021 - #4429892

nice addition,  this could be used in conjunction with contextlib.suppress
which captures all kinds of errors and ignores them.


"contextlib.suppress" is not present in Python 2.7. And 2.7 is currently much more important than Python 3, because Poser 12 is only used by a few people.

Code that runs only under Python 3 should be explicitly marked. Otherwise beginners look for supposed errors where there are none.





adp001 ( ) posted Tue, 09 November 2021 at 6:11 AM · edited Tue, 09 November 2021 at 6:11 AM

Function to trim/extend array, tuple,  bytes or string to a fixed number of elements:

def trimmed(arg, nr_of_elements, f=None):
return (arg + arg.__class__([f, ] * nr_of_elements)
if isinstance(arg, (tuple, list))
else (arg + arg.__class__((f or " ") * nr_of_elements)
if isinstance(arg, (str, bytes))
else [arg, ] + [f, ] * nr_of_elements))[:nr_of_elements]

("f" is what is used to fill missed elements; should be compatible with 'arg')


trimmed([1,2,3], 5) # returns list: [1, 2, 3, None, None]

trimmed((1,2,3), 5) # returns tuple: (1, 2, 3, None, None)

trimmed([1, 2, 3, 4, 5, 6, 7, 8, 9], 5) # returns list: [1, 2, 3, 4, 5]

trimmed("Sample", 10, ".") # returns string: "Sample...."

trimmed(b'123', 5, b'.') # returns bytes: b'123..'

trimmed(10, 5, 1) # returns [10, 1, 1, 1, 1]

trimmed(10, 5, [1, 2, 3]) # returns [10, [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

trimmed([], 5, 1) # returns list: [1, 1, 1, 1, 1]

trimmed((), 5, 1) # returns tuple: (1, 1, 1, 1, 1)








adp001 ( ) posted Tue, 09 November 2021 at 7:03 AM · edited Tue, 09 November 2021 at 7:04 AM

Some more about error handling. This time as decorator to "protect" functions:

def no_err(f):
def _f():
try:
f()
except Exception as err:
pass
return(_f)


@no_err
def test(*args, **kwargs):
a = 3
print(a) # ok
print(a + b) # generates error
print("unreachable because of error")





structure ( ) posted Sun, 14 November 2021 at 10:55 AM · edited Sun, 14 November 2021 at 10:56 AM
Forum Coordinator

Get the users Language (windows):

def Language():
    import locale
    import ctypes
    windll = ctypes.windll.kernel32
    return locale.windows_locale[windll.GetUserDefaultUILanguage()]

Locked Out


structure ( ) posted Sun, 14 November 2021 at 11:22 AM
Forum Coordinator

possible alternative to ExecFile

import runpy
runpy.run_path(filepath)

Locked Out


Y-Phil ( ) posted Wed, 29 December 2021 at 12:46 PM

I don't know if this can help someone, but just in case...
These last months, I've been writing a toolbox with a few wxpython script to import, as the main script has more than 1100 lines. The problem with python is that once a module is imported, it remains in memory, and I've been searching a way to pop it out if there's an error in it, hence this method (I'm writing for Poser12):

import sys

try: sys.modules.pop('my_module')
except: pass
from my_module import MyClass


PhYl.


Win10 on i7 8700K@4.3Ghz, 64Gb, Asus TUF Gaming RTX 4070 OC Edition, 2x 2Tb ssd + 6+4Tb hd  + 1x 8Tb hd + 1 10T NAS, Poser 11, Poser 12  and now Poser 13 


vholf ( ) posted Thu, 10 February 2022 at 10:57 PM

How about opening a repo in github and upload stuff there?, you can upload/update your own scripts and contribute to an organized repository of scripts.


structure ( ) posted Sat, 26 February 2022 at 8:04 AM
Forum Coordinator

Y-Phil posted at 12:46 PM Wed, 29 December 2021 - #4432576

I don't know if this can help someone, but just in case...
These last months, I've been writing a toolbox with a few wxpython script to import, as the main script has more than 1100 lines. The problem with python is that once a module is imported, it remains in memory, and I've been searching a way to pop it out if there's an error in it, hence this method (I'm writing for Poser12):

import sys

try: sys.modules.pop('my_module')
except: pass
from my_module import MyClass

nice, there is also another method : 


import importlib
import module
importlib.reload(module)


Locked Out


structure ( ) posted Sat, 26 February 2022 at 8:06 AM
Forum Coordinator
vholf posted at 10:57 PM Thu, 10 February 2022 - #4434663

How about opening a repo in github and upload stuff there?, you can upload/update your own scripts and contribute to an organized repository of scripts.

If someone has the time to do this, I would be open to adding scripts there. 

Locked Out


Y-Phil ( ) posted Sat, 26 February 2022 at 11:15 AM
structure posted at 8:04 AM Sat, 26 February 2022 - #4435181

Y-Phil posted at 12:46 PM Wed, 29 December 2021 - #4432576

I don't know if this can help someone, but just in case...
These last months, I've been writing a toolbox with a few wxpython script to import, as the main script has more than 1100 lines. The problem with python is that once a module is imported, it remains in memory, and I've been searching a way to pop it out if there's an error in it, hence this method (I'm writing for Poser12):

import sys

try: sys.modules.pop('my_module')
except: pass
from my_module import MyClass

nice, there is also another method : 


import importlib
import module
importlib.reload(module)


Well... Thank you for that nice trick! 😁

PhYl.


Win10 on i7 8700K@4.3Ghz, 64Gb, Asus TUF Gaming RTX 4070 OC Edition, 2x 2Tb ssd + 6+4Tb hd  + 1x 8Tb hd + 1 10T NAS, Poser 11, Poser 12  and now Poser 13 


structure ( ) posted Fri, 11 March 2022 at 1:56 AM · edited Fri, 11 March 2022 at 1:01 PM
Forum Coordinator
example usage of casefold, Counter and count

# setup main tuple
items=("Extra-Terrestrial", "Alien", "Planet", "Star",
        "Galaxy", "Universe", "Black Hole", "White Hole",
        "Astronomy", "Dark-Matter", "Dark-Energy")

# setup comparison tuple
compare=("extra-terrestrial", "alien")

''' use casefold -py3(or upper / lower -py2)
for context insensitive comparison '''
for item in items:
    if any(i.casefold() in item.casefold() for i in compare):
        print(item)

''' use counter to count all words in tuple'''
print(f'\n{Counter(compare)}\n')

''' use count to count how many times comparative
    words appear in tuple'''
for c in compare:
    tense="time" if items.count(c.title())==1 else "times"
    print(f'{c.title()} appears {items.count(c.title())}

Output:

Extra-Terrestrial Alien

Counter({'extra-terrestrial': 1, 'alien': 1}) Extra-Terrestrial appears 1 time in ('Extra-Terrestrial', 'Alien', 'Planet', 'Star', 'Galaxy', 'Universe', 'Black Hole', 'White Hole', 'Astronomy', 'Dark-Matter', 'Dark-Energy', '') Alien appears 1 time in ('Extra-Terrestrial', 'Alien', 'Planet', 'Star', 'Galaxy', 'Universe', 'Black Hole', 'White Hole', 'Astronomy', 'Dark-Matter', 'Dark-Energy', '')

**note :
.count only takes into account the exact word - so words like
"alienesque" or "alien ship" would not be recognised as containing
the word alien.

Locked Out


structure ( ) posted Sat, 19 March 2022 at 9:32 AM
Forum Coordinator

Wait for Keypress (windows)

from msvcrt import getch

def wait():
    getch()

Locked Out


structure ( ) posted Sun, 20 March 2022 at 8:30 PM
Forum Coordinator

Convert bytes to Kb, Mb, Gb, or Tb

def formatSize(bytes):
    try:
        bytes = float(bytes)
        kb = bytes / 1024
    except:
        return "Error"
    if kb >= 1024:
        M = kb / 1024
        if M >= 1024:
            G = M / 1024
            if G >= 1024:
                T = G / 1024
                return "%.2f Tb" % (T)
            return "%.2f Gb" % (G)
        return "%.2f Mb" % (M)
    else:
        return "%.2f kb" % (kb)

Example Output:




Locked Out


structure ( ) posted Sun, 27 March 2022 at 9:38 AM
Forum Coordinator

convert a string of digits to numeric and remove even or odd numbers



def returnDigits(my_string):
    x = re.findall(r'\b\d+\b', my_string)
    return [int(n) for n in x]


def removenumbers(numbers, even=True):
    return [n for n in numbers if n % 2 == 0] \
        if even == True else [n for n in numbers if n % 2 != 0]


my_string = "0 3 4 321 24 034, 1001, 2022, 1977, 1, 6"

stringed_numbers = returnDigits(my_string)
print(stringed_numbers)

evennumbers = sorted(removenumbers(stringed_numbers))
print(evennumbers)

oddnumbers = sorted(removenumbers(stringed_numbers, False))
print(oddnumbers)


Locked Out


structure ( ) posted Sun, 27 March 2022 at 11:22 AM · edited Mon, 28 March 2022 at 8:10 AM
Forum Coordinator

Install a missing module from inside a running python script, and rerun the script (using rich as an example )


class basic_functions:
    def module_exists(self, module_name):
        from pkgutil import iter_modules
        return module_name in (name for loader, name, ispkg in iter_modules())


if basic_functions().module_exists("rich"):
    from rich.align import Align
    from rich.console import Console
else:
    try:
        from subprocess import check_call
        import os
        import sys
        check_call([sys.executable, "-m", "pip", "install", 'rich'])
        import importlib
        from rich.align import Align
        from rich.console import Console
        importlib.reload(rich)
        os.execv(sys.argv[0], sys.argv)
    except:
        pass


rich allows you to create outputs like this :

Locked Out


EVargas ( ) posted Sat, 23 April 2022 at 7:42 PM · edited Sat, 23 April 2022 at 7:45 PM

Hi guys, so here I go again trying to share something, hopefully not reinventing the wheel.

While learning (or trying) to use HDRI and setup scenes with cameras from multiple angles etc, I found myself accidentally moving the cameras a lot. I don't like saving cameras to the library, and I always missed a way to quickly lock/unlock its position/rotation. The native "object/lock" menu can do this, but the camera have to be selected in order for it to work. I want to simply lock/unlock the current ACTIVE camera, without worrying about selecting it in a list.

I searched G00gle and here but with no success I decided to go for it and, why not, learn some more python along the way. Here I share a few lines that help me a lot. These are two separate files that can be added to the python scripts window, or put in "(...)/Poser Software/Poser 12/Runtime/Python/poserScripts/ScriptsMenu/"

For some reason this only works with the user created cameras ("object/create camera"), but I don't bother with it since I always create a new camera for rendering anyway.

# Lock_Current_Cam.py

scene = poser.Scene()
cam = scene.CurrentCamera()

def lockCurrentCam():
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        camPar = cam.Parameter(parName)
        camPar.SetMinValue(camPar.MinValue() - 1 * camPar.MinValue() + camPar.Value())
        camPar.SetMaxValue(camPar.MaxValue() - 1 * camPar.MaxValue() + camPar.Value())

lockCurrentCam()

# ---------------------------------------

# Unlock_Current_Cam.py

scene = poser.Scene()
cam = scene.CurrentCamera()
 
def unlockCurrentCam():    
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        camPar = cam.Parameter(parName)
        camPar.SetMinValue(-10000)
        camPar.SetMaxValue(10000)

unlockCurrentCam()



Store | Website

"Art exists so that reality does not destroy us" - Friedrich Nietzsche


EVargas ( ) posted Sun, 24 April 2022 at 11:53 AM

Update here, when translating to the "def" syntax I forgot the "Force Limits", fixed below. Another good tip is to set a keyboard shortcut for both, it makes life a lot easier!

# -- -- -- -- -- Lock_Current_Cam.py -- -- -- -- --

scene = poser.Scene()
cam = scene.CurrentCamera()

def lockCurrentCam():
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        camPar = cam.Parameter(parName)
        camPar.SetMinValue(camPar.MinValue() - 1 * camPar.MinValue() + camPar.Value())
        camPar.SetMaxValue(camPar.MaxValue() - 1 * camPar.MaxValue() + camPar.Value())
        camPar.SetForceLimits(1)

lockCurrentCam()

# -- -- -- -- -- Unlock_Current_Cam.py -- -- -- -- --

scene = poser.Scene()
cam = scene.CurrentCamera()
 
def unlockCurrentCam():    
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        camPar = cam.Parameter(parName)
        camPar.SetMinValue(-10000)
        camPar.SetMaxValue(10000)
        camPar.SetForceLimits(0)

unlockCurrentCam()



Store | Website

"Art exists so that reality does not destroy us" - Friedrich Nietzsche


structure ( ) posted Mon, 25 April 2022 at 9:09 AM · edited Mon, 25 April 2022 at 9:10 AM
Forum Coordinator

evargas posted at 11:53 AM Sun, 24 April 2022 - #4437678

Update here, when translating to the "def" syntax I forgot the "Force Limits", fixed below. Another good tip is to set a keyboard shortcut for both, it makes life a lot easier!

# -- -- -- -- -- Lock_Current_Cam.py -- -- -- -- --

scene = poser.Scene()
cam = scene.CurrentCamera()

def lockCurrentCam():
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        camPar = cam.Parameter(parName)
        camPar.SetMinValue(camPar.MinValue() - 1 * camPar.MinValue() + camPar.Value())
        camPar.SetMaxValue(camPar.MaxValue() - 1 * camPar.MaxValue() + camPar.Value())
        camPar.SetForceLimits(1)

lockCurrentCam()

# -- -- -- -- -- Unlock_Current_Cam.py -- -- -- -- --

scene = poser.Scene()
cam = scene.CurrentCamera()
 
def unlockCurrentCam():    
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        camPar = cam.Parameter(parName)
        camPar.SetMinValue(-10000)
        camPar.SetMaxValue(10000)
        camPar.SetForceLimits(0)

unlockCurrentCam()


nice addition - thanks

a slightly shorter version

import poser
# -- -- -- -- -- (un)Lock_Current_Cam.py -- -- -- -- --

scene = poser.Scene()
cam = scene.CurrentCamera()

def lockCurrentCam(lock = True, camPar = None):
    for parName in ('xtran','ytran','ztran','xrot','yrot','zrot'):
        if lock:
            camPar = cam.Parameter(parName)
            camPar.SetMinValue(camPar.MinValue() - 1 * camPar.MinValue() + camPar.Value())
            camPar.SetMaxValue(camPar.MaxValue() - 1 * camPar.MaxValue() + camPar.Value())
            camPar.SetForceLimits(1)
        else:
            camPar = cam.Parameter(parName)
            camPar.SetMinValue(-10000)
            camPar.SetMaxValue(10000)
            camPar.SetForceLimits(0)
    return True if camPar.ForceLimits()==1 else False
           

camlocked = lockCurrentCam() # Lock the cam
camlocked = lockCurrentCam(False) # unlock the cam

Locked Out


structure ( ) posted Wed, 27 April 2022 at 4:57 AM · edited Wed, 27 April 2022 at 5:23 AM
Forum Coordinator
Added to dialog Library:


    def getnumberentry(self, alertmessage, prompt, caption, value, min, max, wx.DefaultPosition):
        NE_dialog = wx.NumberEntryDialog(None, alertmessage, prompt, caption, value, min, max, pos)
        return NE_dialog.GetValue() if NE_dialog.ShowModal() == wx.ID_OK else None
   
example Usage:
   
duplicate = (getnumberentry("How Many %s's ?" % item, "Select a number",
                            "Number Entry Dialog", 0, 0, 100))

Locked Out


structure ( ) posted Tue, 10 May 2022 at 4:35 AM · edited Tue, 10 May 2022 at 4:39 AM
Forum Coordinator

number outside chosen range? select the closest viable number to the chosen number.

from random import randint


def closest_value(value, iterable):
    storage = []

    for i in iterable:
        storage.append((abs(value - i), i))

    result = min(storage)
    return result[1]


for x in range(0, 10):
    variant = randint(-20, 20)
    if variant > 4 or variant < 1:
        # generate viable number
        v = variant
        variant = closest_value(variant, range(1, 5))
        print(f"Original {v} : New {variant}")


Output : 

Original 13 : New 4
Original -1 : New 1
Original -5 : New 1
Original -16 : New 1
Original 17 : New 4
Original -11 : New 1
Original 13 : New 4
Original 11 : New 4
Original 6 : New 4
Original 16 : New 4


Locked Out


structure ( ) posted Wed, 18 May 2022 at 2:57 PM
Forum Coordinator

get screen resolution


import wx

def get_Screen_Resolution():
    try:
        # method to get screen size
        return wx.GetDisplaySize()
    except:
        # alternate method to get screen size
        return wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X), wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

SCREENW, SCREENH = get_Screen_Resolution()
print((SCREENW, SCREENH))




Locked Out


structure ( ) posted Fri, 20 May 2022 at 2:25 AM
Forum Coordinator

Mirror / reverse data:

INSTANCES for testing what your variable is. ( this is just for printing headings )

class INSTANCES:
    def test_instance(self, value):
        if isinstance(value, type(None)):
            return "NoneType"
        if isinstance(value, str):
            return "string"
        if isinstance(value, int):
            return "int"
        if isinstance(value, float):
            return "float"
        if isinstance(value, list):
            return "list"
        if isinstance(value, tuple):
            return "tuple"
        if isinstance(value, dict):
            return "dict"
        if isinstance(value, set):
            return "set"
        if isinstance(value, object):
            return "object"


Actual Mirror Code:
class MIRROR_DATA:
    def mirror(self, data):
        if isinstance(data, tuple):
            return tuple(map(self.mirror, reversed(data)))
        elif isinstance(data, list):
            return [ele for ele in reversed(data)]
        elif isinstance(data, str):
            return data[::-1]
        elif isinstance(data, dict):
            return dict(reversed(list(data.items())))
        elif isinstance(data, set):
            data = list(data)
            data = self.mirror(data)
            return data
        else:
            return data


example Code:
type(None) == None.__class__
types = (type(None), str, int, float, list, dict, tuple, set, object)
testdata = {0: (0, 1, 2, 3),
            1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ],
            2: "0,1,2,3,4,5,6,7,8,9,",
            3: {0: "0,1,2,3,4,5,6,7,8,9,", 1: 123, 2: "more bullsh*t!"},
            4: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, }
            }


for t in testdata:
    nport = testdata[t]
    print(f"{'-'*5} With a {INSTANCES().test_instance(nport)} {'-'*5}")
    print(nport)
    rport = MIRROR_DATA().mirror(nport)
    if t == 4:
        print(f"before conversion back to a set {rport}")
        rport = set(rport)
        print(f"after conversion back to a set {rport}")
    print(rport)
    print(f"{'-'*24}")
    print()


Output:
····· With a tuple ·····
(0, 1, 2, 3)
(3, 2, 1, 0)
························

····· With a list ·····
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
························

····· With a string ·····
0,1,2,3,4,5,6,7,8,9,
,9,8,7,6,5,4,3,2,1,0
························

····· With a dict ·····
{0: '0,1,2,3,4,5,6,7,8,9,', 1: 123, 2: 'more bullsh*t!'}
{2: 'more bullsh*t!', 1: 123, 0: '0,1,2,3,4,5,6,7,8,9,'}
························

····· With a set ·····
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
before conversion back to a set [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
after conversion back to a set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
························

Locked Out


adp001 ( ) posted Fri, 20 May 2022 at 3:03 PM

According to the motto: Why simple when you can make it complicated :)

test this:

d = dict(a=1, b=2, c=3)

print(d.__class__.__name__)




structure ( ) posted Sat, 21 May 2022 at 1:51 AM
Forum Coordinator
adp001 posted at 3:03 PM Fri, 20 May 2022 - #4438875

According to the motto: Why simple when you can make it complicated :)

test this:

d = dict(a=1, b=2, c=3)

print(d.__class__.__name__)

nice - thanks

Locked Out


adp001 ( ) posted Sun, 22 May 2022 at 6:49 AM

Just for the records:

Python sets and dictionaries are unordered. So not sorted. For this reason there is no "reverse" for it. Because the order is random.

https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset

Exception for dictionaries: Class OrderedDict from lib collections.




adp001 ( ) posted Sun, 22 May 2022 at 7:00 AM

Another thing: Strings are arrays of characters.

So, list(reversed("abcdefg") ) returns ['g', 'f', 'e', 'd', 'c', 'b', 'a']. list(s[::-1]) returns the same.








structure ( ) posted Sun, 22 May 2022 at 12:19 PM · edited Sun, 22 May 2022 at 1:05 PM
Forum Coordinator

in python 3 - reversing "ABRACDABRA"

returns  : ARBADCARBA

Dictionaries are ordered and so can be reversed as is evidenced by 

····· With a dict ·····
{0: '0,1,2,3,4,5,6,7,8,9,', 1: 123, 2: 'more bullsh*t!'}
{2: 'more bullsh*t!', 1: 123, 0: '0,1,2,3,4,5,6,7,8,9,'}
························

sets must be converted to a list to get the data reversed. They also seem to be sorted low to high 

Locked Out


structure ( ) posted Tue, 31 May 2022 at 11:32 AM · edited Wed, 01 June 2022 at 9:07 AM
Forum Coordinator

creating a class for working with colors: (part I)

from matplotlib import colors as colours
from skimage import color as colour

class COLOR_SYSTEM:
    def random_hex(self):
        ''' Generate a random Hex String '''
        return str(["#"+''.join([choice(hex_string)
                                 for loop in range(6)])]).strip("\[\]\'")

    def hex2rgb(self, colorstring): # requires a HEX notated value
        ''' convert #RRGGBB to an (R, G, B) tuple '''
        colorstring = colorstring.lstrip('#')
        return tuple(int(colorstring[_hex:_hex+2], 16) for _hex in (0, 2, 4))

    def rgb2hsv(self, r, g, b):
        ''' convert (R, G, B) to (H, S, V) tuple '''
        (r, g, b) = self.rgb2posercol((r, g, b))
        return tuple(colours.rgb_to_hsv((r, g, b)))

    def rgb2posercol(self, rgb):
        ''' convert (R, G, B) to Poser Notation '''
        return tuple([x/255.0 for x in rgb])#

    def posercol2html(self, col_tuple):
        ''' convert Poser Notation to HEX '''
        return self.rgb2htmlcolor(col_tuple)

    def rgb2htmlcolor(self, rgb_tuple):
        ''' convert (R, G, B) to Hex '''
        return '#%02x%02x%02x'.upper() % rgb_tuple

Locked Out


structure ( ) posted Fri, 03 June 2022 at 12:19 PM · edited Sun, 12 June 2022 at 2:20 AM
Forum Coordinator

Toggle lock keys  * WINDOWS 

importable script: ( I saved this in lib/site-packages under folder _toggle_keys)

from ctypes import windll
from win32con import VK_CAPITAL, VK_NUMLOCK, VK_SCROLL
from win32api import GetKeyState


TEST_STATUS = False
# toggle status is binary 0/1 - on/off


class KEY_SYSTEM:
    def toggle_key(self, key, turn_on=0):
        '''
        toggle_key(int) ->  int

        Turns key on or off and returns whether
        it was originally on or off.        '''

        KEYEVENTF_KEYUP = 2
        KEYEVENTF_EXTENDEDKEY = 1
        KEYEVENTF_KEYUP = 2

        is_on = GetKeyState(key) & 1

        if is_on != turn_on:
            windll.user32.keybd_event(key,
                                      69,
                                      KEYEVENTF_EXTENDEDKEY | 0,
                                      0)
            windll.user32.keybd_event(key, 69,
                                      KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                                      0)
        return is_on

    def get_key_status(self, key):
        # key must be one of the following integer values - 20, 144, 145
        return None if key not in [20, 144, 145] else GetKeyState(key)


script to import and run:

from _toggle_keys import KEY_SYSTEM as toggle
keys = {20: "CAPS",
        144: "NUM",
        145: "SCROLL", }

for k in keys:
    OFFON = toggle.get_key_status(None, k)

    toggle.toggle_key(None, k, not(OFFON))
    print(f"{keys[k]}_LOCK is off", end="\n\n") if OFFON else print(
        f"{keys[k]}_LOCK is on", end="\n\n")

if __name__ == "__main__":
    for k in (20, 144, 145):
        # turn off/on key lock 0 = off, 1 = on
        KEY_SYSTEM().toggle_key(k, not(KEY_SYSTEM().get_key_status(k)))

Locked Out


structure ( ) posted Fri, 03 June 2022 at 12:57 PM · edited Sun, 12 June 2022 at 2:32 AM
Forum Coordinator

getting single characters from keystrokes and building a string from them * WINDOWS

from msvcrt import getche
from _toggle_keys import KEY_SYSTEM as toggle
from importlib import util

FOUND = util.find_spec("rich") is not None
if FOUND:
    from rich import print

hex_string = '0123456789ABCDEF'
chars = "#"
if not toggle.get_key_status(None, 20) == 1:
    toggle.toggle_key(None, 20, 1)  # turn off/on caps lock 0 = off, 1 = on

# getche displays characters as they are typed, getch does not display them
print("Incorrect hex characters will be substituted with a zero (0).")
print(f"Enter Your Hex Value (from {hex_string}) {chars}", end=" : ")
for x in range(1, 7):
    char = str(getche().decode('utf-8')).upper()
    chars += "0" if not char in hex_string else char

if not toggle.get_key_status(None, 20) == 0:
    toggle.toggle_key(None, 20, 0)  # turn off/on caps lock 0 = off, 1 = on

ps = f"[{chars}]" if FOUND else ""

print(f"\n\nYour Selected Color : {ps}{chars}\n")

Locked Out


  • 1
  • 2

Privacy Notice

This site uses cookies to deliver the best experience. Our own cookies make user accounts and other features possible. Third-party cookies are used to display relevant ads and to analyze how Renderosity is used. By using our site, you acknowledge that you have read and understood our Terms of Service, including our Cookie Policy and our Privacy Policy.