Exemplo n.º 1
0
    def load(self, path):
        case_insensitive_path = path.casefold()
        for f in self.zip_file.infolist():
            if f.filename.casefold() == case_insensitive_path:
                return ZipResource(self.zip_file, f)

        return None
Exemplo n.º 2
0
def find_gams_directory():
    """
    Returns GAMS installation directory or None if not found.

    On Windows systems, this function looks for `gams.location` in registry;
    on other systems the `PATH` environment variable is checked.

    Returns:
        a path to GAMS installation directory or None if not found.
    """
    if sys.platform == "win32":
        try:
            with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT,
                                "gams.location") as gams_location_key:
                gams_path, _ = winreg.QueryValueEx(gams_location_key, None)
                if not _windows_dlls_exist(gams_path):
                    return None
                return gams_path
        except FileNotFoundError:
            return None
    executable_paths = os.get_exec_path()
    for path in executable_paths:
        if "gams" in path.casefold():
            return path
    return None
Exemplo n.º 3
0
def png(path, resize_to=None, error=None, algo=Image.LANCZOS):
    """Loads in an image for use in TKinter.

    - The .png suffix will automatically be added.
    - Images will be loaded from both the inbuilt files and the extracted
    zip cache.
    - If resize_to is set, the image will be resized to that size using the algo
    algorithm.
    """
    if not path.casefold().endswith(".png"):
        path = path + ".png"
    orig_path = path

    if (orig_path, resize_to) in cached_img:
        return cached_img[orig_path, resize_to]

    if not os.path.isfile(os.path.join("../images", path)):
        # If not in the main folder, load from the zip-cache
        path = os.path.join("../images/cache/", path)
    path = os.path.join("../images", path)

    if os.path.isfile(path):
        image = Image.open(path)
    else:
        print('ERROR: "images\\' + orig_path + '" does not exist!')
        return error or img_error

    if resize_to:
        image = image.resize((resize_to, resize_to), algo)

    img = ImageTk.PhotoImage(image=image)
    cached_img[path, resize_to] = img
    return img
Exemplo n.º 4
0
def png(path, resize_to=0, error=None, algo=Image.NEAREST):
    """Loads in an image for use in TKinter.

    - The .png suffix will automatically be added.
    - Images will be loaded from both the inbuilt files and the extracted
    zip cache.
    - If resize_to is set, the image will be resized to that size using the algo
    algorithm.
    - This caches images, so it won't be deleted (Tk doesn't keep a reference
      to the Python object), and subsequent calls don't touch the hard disk.
    """
    if not path.casefold().endswith(".png"):
        path += ".png"
    orig_path = path

    try:
        return cached_img[path, resize_to]
    except KeyError:
        pass

    base_path = os.path.abspath(
        os.path.join(
            os.getcwd(),
            "../",
            "images",
            path,
        ))
    cache_path = os.path.abspath(
        os.path.join(
            os.getcwd(),
            "../",
            "images",
            "cache",
            path,
        ))

    if os.path.isfile(base_path):
        path = base_path
    else:
        # If not in the main folder, load from the zip-cache
        path = cache_path

    try:
        img_file = open(path, 'rb')
    except FileNotFoundError:
        LOGGER.warning('ERROR: "images/{}" does not exist!', orig_path)
        return error or img_error
    with img_file:
        image = Image.open(img_file)
        image.load()

    if resize_to:
        image = image.resize(tuple_size(resize_to), algo)

    tk_img = ImageTk.PhotoImage(image=image)

    cached_img[orig_path, resize_to] = tk_img
    return tk_img
Exemplo n.º 5
0
def is_image(path):
    image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".svg", ".tif", ".bmp", ".mp4")
    if path is None:
        return False
    for i in image_extensions:
        if path.casefold().endswith(i):
            ext = i
            return ext
    return False
Exemplo n.º 6
0
    def ValidateURL(cls, path):
        """ValidateURL:  checks to see if the given URL is valid request for
        Historia's web server. If the URL is valid return a dict with the
        parsed URL.

        Valid URLS are defined by the controller and imported into
        HistoriaHTTPHandler.patterns during __init__().
        """

        # if there is a trailing slash, remove it
        if path[-1:] == '/':
            path = path[:-1]

        # If there is a query string, drop it
        if '?' in path:
            path = path.split('?')[0]

        # push the URL to lowercase to avoid case issues, and split it into
        # segments:
        segments = path.casefold().split('/')

        # String should start with / which means an empty string as the first
        # element of the list
        if segments[0] != '':
            raise HTTPException("Invalid URL sent for validation", 403)
        else:
            segments = segments[1:]

        # If Historia's name space is enabled, check for it.
        if HistoriaHTTPHandler.url_namespace is not None and \
                HistoriaHTTPHandler.url_namespace != '':
            if len(segments) == 0:
                raise HTTPException(
                    "Invalid URL sent for validation: required namespace missing",
                    404)
            elif segments[0] != HistoriaHTTPHandler.url_namespace:
                raise HTTPException(
                    "Invalid URL sent for validation: required namespace missing",
                    404)
            else:
                segments = segments[1:]

        # Check for special cases
        if len(segments) == 0:  # site root means we want the home page
            return ('home', '')
        elif segments[0] in HistoriaHTTPHandler.special_cases:
            return (segments[0], '/'.join(segments[1:]))

        # Compare remaining segments against the valid patterns
        request = "/".join(segments)
        if HistoriaHTTPHandler.patterns.match(request) is None:
            raise HTTPException("Location not found: {0}".format(path), 404)
        else:
            return (segments[0], '/'.join(segments[1:]))
Exemplo n.º 7
0
def png(path: str, resize_to=0, error=None, algo=Image.NEAREST):
    """Loads in an image for use in TKinter.

    - The .png suffix will automatically be added.
    - Images will be loaded from both the inbuilt files and the extracted
    zip cache.
    - If resize_to is set, the image will be resized to that size using the algo
    algorithm.
    - This caches images, so it won't be deleted (Tk doesn't keep a reference
      to the Python object), and subsequent calls don't touch the hard disk.
    """
    if not path.casefold().endswith(".png"):
        path += ".png"
    path = path.casefold().replace('\\', '/')
    orig_path = path

    resize_width, resize_height = resize_to = tuple_size(resize_to)

    try:
        return cached_img[path, resize_width, resize_height]
    except KeyError:
        pass

    with filesystem:
        try:
            img_file = filesystem[path]
        except KeyError:
            LOGGER.warning('ERROR: "images/{}" does not exist!', orig_path)
            return error or img_error
        with img_file.open_bin() as file:
            image = Image.open(file)
            image.load()

    if resize_to != (0, 0):
        image = image.resize(resize_to, algo)

    tk_img = ImageTk.PhotoImage(image=image)

    cached_img[orig_path, resize_width, resize_height] = tk_img
    return tk_img
Exemplo n.º 8
0
def png(path, resize_to=None, error=None, algo=Image.LANCZOS):
    """Loads in an image for use in TKinter.

    - The .png suffix will automatically be added.
    - Images will be loaded from both the inbuilt files and the extracted
    zip cache.
    - If resize_to is set, the image will be resized to that size using the algo
    algorithm.
    """
    if not path.casefold().endswith(".png"):
        path += ".png"
    orig_path = path

    if (orig_path, resize_to) in cached_img:
        return cached_img[orig_path, resize_to]

    base_path = os.path.abspath(
        os.path.join(
            os.getcwd(),
            "../",
            "images",
            path,
        )
    )
    cache_path = os.path.abspath(
        os.path.join(
            os.getcwd(),
            "../",
            "images",
            "cache",
            path,
        )
    )

    if os.path.isfile(base_path):
        path = base_path
    else:
        # If not in the main folder, load from the zip-cache
        path = cache_path

    if os.path.isfile(path):
        image = Image.open(path)
    else:
        print('ERROR: "images/' + orig_path + '" does not exist!')
        return error or img_error

    if resize_to:
        image = image.resize((resize_to, resize_to), algo)

    img = ImageTk.PhotoImage(image=image)
    cached_img[path, resize_to] = img
    return img