python – Printing colourful text to terminal

colors.py

type_error = "Expected an int or str type but given {} type"


def _condition_for_int(color):
    return (isinstance(color, int) and (color >= 0 and color < 256)) or (
        color.isnumeric() and (int(color) >= 0 and int(color) < 256)
    )


class Color:
    accepted_color_alias = {
        "black",
        "red",
        "green",
        "yellow",
        "blue",
        "magenta",
        "cyan",
        "white",
    }
    RESET = "33(0m"


class FontColor(Color):
    """
    Font color class
    """

    black = "33(30m"
    red = "33(31m"
    green = "33(32m"
    yellow = "33(33m"
    blue = "33(34m"
    magenta = "33(35m"
    cyan = "33(36m"
    white = "33(37m"

    @classmethod
    def get_color(self, color, value="", add_reset=True):
        if not isinstance(color, (int, str)):
            raise TypeError(type_error.format(type(color).__name__))

        _reset = self.RESET * add_reset

        if _condition_for_int(color):
            return "33(38;5;{}m{}{}".format(color, value, _reset)

        if color not in self.accepted_color_alias:
            raise ValueError("Unknown color given {}".format(color))
        return getattr(self, color) + str(value) + _reset


class BackgroundColor(Color):
    """
    Background colors class
    """

    black = "33(40m"
    red = "33(41m"
    green = "33(42m"
    yellow = "33(43m"
    blue = "33(44m"
    magenta = "33(45m"
    cyan = "33(46m"
    white = "33(47m"

    @classmethod
    def get_color(self, color, value, add_reset=True):
        if not isinstance(color, (int, str)):
            raise TypeError(type_error.format(type(color).__name__))

        _reset = self.RESET * add_reset

        if _condition_for_int(color):
            return "33(48;5;{}m{}{}".format(color, value, _reset)

        if color not in self.accepted_color_alias:
            raise ValueError("Unknown color given {}".format(color))

        return getattr(self, color) + str(value) + _reset


class FontStyle(Color):
    """
    Font style class
    """

    bold = "33(1m"
    italic = "33(3m"
    underline = "33(4m"

    @classmethod
    def get_style(self, style, value="", add_reset=True):
        if not isinstance(value, str):
            raise TypeError("Only str type allowed")

        return getattr(self, style) + value + self.RESET * add_reset


#s = f'{FontColor.get_color("red", "STOP")} {BackgroundColor.get_color("cyan", "danger")}'
# print(s)
# print(FontStyle.get_style('underline', 'HEllO'))

Output from the commented lines at the end of the file
         

utils.py

from colors import Color, FontStyle, FontColor, BackgroundColor
import sys
from time import sleep


def cprint(
    text,
    color=None,
    background=None,
    bold=False,
    italic=False,
    underline=False,
    end="n",
):
    """
    prints the given text to stdout with color `color`
    and `background` resets back to normal after printing.
    Supported colors are 'black', 'red', 'green', 'yellow',
    'blue', 'magenta', 'cyan', 'white'.
    """

    _reset = Color.RESET
    bg = "" if background is None else _set_background(background)
    font_color = "" if color is None else _set_color(color)
    font_style = _set_font_style(bold=bold, italic=italic, underline=underline)
    output_style = bg + font_color + font_style
    sys.stdout.write(output_style)
    sys.stdout.write(text)
    sys.stdout.write(_reset + end)


def _set_color(color):
    """
    For setting color of the cursor with `color`.
    Accepted colors alias are 'black', 'red', 'green',
    'yellow', 'blue', 'magenta', 'cyan', 'white'.
    Can also gives an values between 0 to 255.
    Check `get_color_codes()` for more info.
    """

    return FontColor.get_color(color, add_reset=False)


def _set_background(color):
    """
    Returns the background of the cursor with color
    `color` ansi esacape code. Accepted colors alias are
    'black', 'red', 'green','yellow', 'blue', 'magenta',
    'cyan', 'white'. Can also gives an values between 0 to 255.
    """

    return BackgroundColor.get_color(color, add_reset=False)


def _set_font_style(**styles):
    return "".join(
        (
            FontStyle.get_style(style, add_reset=False)
            for style, cond in styles.items()
            if cond
        )
    )


def get_color_codes(animation=False, background=False):
    """
    prints color codes in it's respective color,
    used for visual reference.
    """

    ansi_code = "33(48;5;{}m{}" if background else "33(38;5;{}m{}"
    v = 0.1 if animation else 0
    for i in range(32):
        for j in range(8):
            sleep(v)
            code = str(i * 8 + j)
            sys.stdout.write(ansi_code.format(code, code.ljust(4)))
            sys.stdout.write("33(0m")
        sys.stdout.write("n")


#cprint("hello world", color="123", bold=True, italic=True)

# get_color_codes(background=True)

The output from commented lines at the end of the file

export – how to save in stl formate for 3D printing

Good morning, I have the code of a spherical gyroid written in Mathematica and I am unable to save it in STL format. The image is shown in the figure below and the code is shown below. I need help with a code on how to save it as an STL file.
enter image description here

***r = 2 Pi;
model = ContourPlot3D(
  Sin(x) Cos(y) + Sin(y) Cos(z) + Sin(z) Cos(x) == 0, {x, -r, 
   r}, {y, -r, r}, {z, -r, r},
  RegionFunction -> ({x, y, z} (Function) x^2 + y^2 + z^2 <= r^2),
  Mesh -> None, PlotTheme -> "ThickSurface", 
  Method -> {"Extrusion" -> .3})***

C# Label printing with p-Touch Brother Error: System.IO.FileNotFoundException

guys,

i’m trying to write a program that changes and prints an existing label “label.lbx” from a p-Touch Brother printer.
But my program stops at:

bpac.Document doc = new bpac.Document();

The error message:

System.IO.FileNotFoundException: “The COM class directory for the component with CLSID {B940C105-7F01-46FE-BF41-E040B9BDA83D} could not be retrieved due to the following error: 8007007e The specified module was not found. (HRESULT exception: 0x8007007E).

I have already removed and added the Interop.bpac.dll file. Project cleaned up and rebuilt. Moved the file to the Debug Order. But it didn’t help.

Does anyone have an idea why the error message is coming?

My Code:

string path = @"C:UserssourcereposLabelToollabel.lbx";

bpac.Document doc = new bpac.Document();

doc.Open(path);
doc.SetPrinter("Printer", true);

doc.GetObject("ReplacePlace").Text = textBox1.Text;

doc.StartPrint("", bpac.PrintOptionConstants.bpoDefault);
doc.PrintOut(1, bpac.PrintOptionConstants.bpoDefault);
doc.EndPrint();
doc.Close();

Printing a JPG as a gift

I want to print a picture for my dad, who loves history, as a gift. I’m worried the file is kinda low quality, but I’m not sure.

enter image description here
It’s 720×900 and 255 kB.

Now, to keep the ratio can I just transpose the pixel ratio to mm? For instance 500×625?

At that size, will the picture still look good?

printing – What steps should I be taking specifically for print when shooting?

Like the title says, I have a project in mind that I envision as a book in the end. I’m using a Z6 with a variety of lenses, from the kit lens to a few F-mount prime lenses (I’ll have to use the FTZ adapter).

What should I be doing to ensure the best quality in my final prints?

  • Steps I should take in-camera?
  • Steps I should take in Lightroom?
  • Specific color profiles I should use?
  • Steps I should take when sending the images off to a printer?

programming challenge – Printing 1000000 in 1 sec. in Python

Here’s a fairly simple task from CSES Problem Set – Permutations 1070 that reads:

A permutation of integers 1,2,…,n is called beautiful if there are no
adjacent elements whose difference is 1.

Given n, construct a beautiful permutation if such a permutation exist

The constraints are pretty tight:

  • Time limit: 1.00 s
  • Memory limit: 512 MB
  • 1≤n≤10^6

Here’s the code:

n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
elif n == 1:
    print(1)
elif n == 4:
    print("3 1 4 2")
else:
    for i in range(1, n + 1, 2):
        print(str(i) + " ", end=" ")
    for i in range(2, n + 1, 2):
        print(str(i) + " ", end=" ")

It passes all tests except for n = 1000000. For that test it takes 15 sec. on my machine. The code is in Python 3.8

The question is, what can can be improved in terms of printing the numbers?

theming – phpwkhtmltopdf engine pdf printing configuration issues

The screenshot below shows my Entity Print configurations for created styled PDFs from node content.
enter image description here

As shown in the screenshot I am using the phpwkhtmltopdf engine.

However, when I try generating the target PDF, the following errors results:

Error generating document: Failed to generate PDF:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 1:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: cannot open
?php: No such file
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 2:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: namespace:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 4:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: use: not
found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 6:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: /bin:
Permission denied
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 7:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: INSTALL.txt:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 8:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: INSTALL.txt:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 9:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: INSTALL.txt:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php:
10: /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php:
INSTALL.txt: not found
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 12:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: Syntax
error: newline unexpected

I gave Pdf.php 777 permissions too.

Can anyone help, please?

Why is there a delay in printing (even a single page) using Ubuntu 12.4 ? The print starts after a duration of 16 to 18 seconds

A hand held device is operating on ubuntu 12.4, CUPS and QT application. The printer used is HP Officejet 200 mobile printer. The time taken for starting the print operation for a single page is ~16 to 18sec.
The printing happe

35mm – Printing negatives: from scans or direct?

Is there a fundamental difference between legacy printers that print from negatives, versus trendy-film shops that print from scans?

I’m just surprised that my printed 35mm film photos aren’t proportionally better than genuinely old photographs with respect to the change in technology. This is especially when I look at photos from my grandparents.

web development – Custom print cost calculator for printing business

First of all, I am not a web developer. I manage a small printing business. I manage our company’s website and our company’s social media profiles, as well as our Google Ads campaigns.

Our website was built using Google sites. I know it isn’t the best website builder, but all we needed was a website with a couple of pages that showcase our work, so our customers can inform themselves about what we do and what services we offer. And it has actually been working better that you’d initially think. I have had quite a few customers compliment us on how nice our website was.

However, I’d like to expand to something completely different that most of the website building platforms in the market don’t seem to offer; calculating the cost of e.g. printing a .pdf file online and then giving the customer to pay for that service.

Take for example: https://doxzoo.com/pdf-printing

You can upload your .pdf file, and their website calculates the cost based on the number of pages on that file, taking into account input from the user, things like whether it will be a full colour or B&W print, if they want it to be spiral bound, etc.

Is there any platform, like e.g Shopify or Woocommerce, or some extension for one of those platforms, that allow you to do something like that, even without all the features that I mentioned earlier? Anything that doesn’t require extensive coding knowledge goes. I would really like to make this happen myself, so I can have full control over it throughout its lifespan.

Thanks in advance.