예제 #1
0
    class Signature(HasTraits):
        color = String(desc='color signature name')
        dimmest = Color(desc='dimmest allowable RGB intensities')
        brightest = Color(desc='brightest allowable RGB intensities')

        def __eq__(self, other):
            return self.dimmest == other.dimmest or self.brightest == other.brightest

        def __ne__(self, other):
            return self.dimmest != other.dimmest and self.brightest != other.brightest

        def __hash__(self):
            return hash(
                (hash(self.dimmest), hash(self.brightest))
            )  # color signature is all that matters for identification purposes

        def __setattr__(self, attribute, setting):
            if attribute == 'dimmest' and hasattr(self, 'brightest'):
                assert self.brightest != setting, '{} `dimmest` and `brightest` attributes are equal ({})'.format(
                    self.__class__.__name__, setting)
            elif attribute == 'brightest' and hasattr(self, 'dimmest'):
                assert self.dimmest != setting, '{} `dimmest` and `brightest` attributes are equal ({})'.format(
                    self.__class__.__name__, setting)
            HasTraits.__setattr__(self, attribute, setting)

        def __str__(self):
            return '{}(color:{}, dimmest:{}, brightest:{})'.format(
                self.__class__.__name__, self.color, self.dimmest,
                self.brightest)
예제 #2
0
 def create(_self_, target, settings):
     name = target.split(
         ' <:> '
     )[1]  # [Section] name suffix (after <:>) assumed to be the machine name on local network
     width = settings.getint(target, 'width')
     height = settings.getint(target, 'height')
     port = settings.getint(target, 'port')
     color = settings.get(target, 'color')
     dimmest = settings.get(target, 'dimmest')
     brightest = settings.get(target, 'brightest')
     dimmest = Color(**dict(
         zip(('Red', 'Green',
              'Blue'), [int(this) for this in dimmest.split(',')])))
     brightest = Color(**dict(
         zip(('Red', 'Green',
              'Blue'), [int(this) for this in brightest.split(',')])))
     assert brightest != dimmest, '{} `dimmest` and `brightest` attributes are equal ({})'.format(
         self.__name__, dimmest)
     signature = _self_.Signature(color=color,
                                  brightest=brightest,
                                  dimmest=dimmest)
     monitor = _self_.Monitor(width=width, height=height)
     log = logging.getLogger(name)
     parameters = dict(
         zip(('name', 'color', 'signature', 'monitor', 'port', 'log'),
             (name, color, signature, monitor, port, log)))
     return _self_(**parameters)
예제 #3
0
 def blink(self, delay=0.25, num_blinks=4):
     backup = self._array
     for i in range(num_blinks):
         self._array = [[Color(0, 0, 0) for i in range(self._height)]
                        for j in range(self._width)]
         self.display()
         time.sleep(delay)
         self._array = backup
         self.display()
         time.sleep(delay)
예제 #4
0
def main():
    color = Color()
    draw_picture()
    cli_args = parse_args()  # parse CLI for arguments
    try:
        i_pwned = HIBPApi(passwd=cli_args.password,
                      file_passwd=cli_args.file_passwd)
        i_pwned.make_request_to_hibp()

    except KeyboardInterrupt:
        print(color.brush('\ninterrupted by user. Shutting down', 'purple'))
        sys.exit()
예제 #5
0
    def mutate(self):
        # Randomly choose the amount of mutation to be done.
        mutation_size = max(1, int(round(random.gauss(15, 4)))) // 100

        # Randomly choose the mutation type from PARAMS.
        # Options --> diameter, pos, color
        mutation_type = random.choice(Gene.PARAMS)

        if mutation_type == "diameter":
            self._diameter = max(
                1,
                random.randint(int(self._diameter * (1 - mutation_size)),
                               int(self._diameter * (1 + mutation_size))))

        elif mutation_type == "pos":
            x = max(
                0,
                random.randint(int(self._pos.x * (1 - mutation_size)),
                               int(self._pos.x * (1 + mutation_size))))
            y = max(
                0,
                random.randint(int(self._pos.y * (1 - mutation_size)),
                               int(self._pos.y * (1 + mutation_size))))
            self._pos = Point(min(x, self._width), min(y, self._height))

        # mutation_type == color
        else:
            r = min(
                max(
                    0,
                    random.randint(int(self._color.r * (1 - mutation_size)),
                                   int(self._color.r * (1 + mutation_size)))),
                255)
            g = min(
                max(
                    0,
                    random.randint(int(self._color.g * (1 - mutation_size)),
                                   int(self._color.g * (1 + mutation_size)))),
                255)
            b = min(
                max(
                    0,
                    random.randint(int(self._color.b * (1 - mutation_size)),
                                   int(self._color.b * (1 + mutation_size)))),
                255)
            alpha = min(
                max(
                    0,
                    random.randint(
                        int(self._color.alpha * (1 - mutation_size)),
                        int(self._color.alpha * (1 + mutation_size)))), 255)

            self._color = Color(r, g, b, alpha)
예제 #6
0
    def __init__(self, size):
        # Let diameter of circle be randomly from [2, 15)
        self._diameter = random.randint(2, 15)
        self._size = size
        self._width, self._height = self._size

        # Randomly choose a pixel point in the image space.
        self._pos = Point(random.randint(0, self._width),
                          random.randint(0, self._height))

        # Randomly assign color to pixel with random opacity
        self._color = Color(random.randint(0, 255), random.randint(0, 255),
                            random.randint(0, 255), random.randint(0, 255))
예제 #7
0
def lines(state: State, place: Place) -> Tuple[str, str]:
    """
    For given member place, get the tf status line strings (two lines per member)

    <player name> <hp>/<hpmax> <hpdiff to max>
    <player state> <ep> <sp>/<spmax> <* if player is cast target>

    For example:
         Ruska  408/ 445  -37
      ldr  224 1404/1404

    :param member: member data
    :returns: Tuple of two strings for tf status lines
    """

    if place not in state.places:
        return ("                        ", "                        ")

    member = state.places[place]
    name = colorize("{0: >9}".format(member.name[:8]), nameColor(member))
    hp = colorize(
        "{0: >4}".format(member.hp),
        greenRedGradient(member.hp, member.maxhp, 200, 0.2),
    )
    maxhp = "{0: >4}".format(member.maxhp)
    hpdiff = colorize(
        "{0: >5}".format(member.hp - member.maxhp or ""), Color(0xEA, 0x22, 0x22)
    )
    memberStateTuple = getMemberState(member)
    memberState = colorize("{0: >5}".format(memberStateTuple[0]), memberStateTuple[1])
    memberIsTarget = (
        colorize("{0:4}".format("*"), YELLOW) if state.target == member.name else "    "
    )

    return (
        "{0} {1}/{2}{3}".format(
            name,
            hp,
            maxhp,
            hpdiff,
        ),
        "{0} {1: >3} {2: >4}/{3: >4} {4}".format(
            memberState,
            member.ep if member.ep is not None else "?",
            member.sp if member.sp is not None else "?",
            member.maxsp if member.maxsp is not None else "?",
            memberIsTarget,
        ),
    )
예제 #8
0
def greenRedGradient(
    n: int, n_max: int, all_red_abs: int, all_red_ratio: float
) -> Color:
    all_red = max(all_red_abs, int(n_max * all_red_ratio + 0.5))

    if n < all_red:
        return RED
    if n >= n_max:
        return GREEN

    # http://stackoverflow.com/a/340245
    # green is 0 and red 1, so invert the ratio to get maximum to be green
    # also, bottom 10% is already handled, so reduce 10% of maximum from both
    n_ratio = 1 - ((n - all_red) / (n_max - all_red))
    r = int(255 * n_ratio + 0.5)
    g = int(255 * (1 - n_ratio) + 0.5)
    return Color(r, g, 0)
예제 #9
0
    def _initFrames(self):
        
        if self.curvature is not None:
            cmin, cmax = 0., 0.
            for frame, cont in self.curvature.items():
                for _, C in cont:
                    if np.max(C) > cmax:
                        cmax = np.max(C)
                    if np.min(C) < cmin:
                        cmin = np.min(C)
            
            color = Color(scaleMin=cmin, scaleMax=cmax)
        
        frames = list()
        for frame in range(1,len(self.data)+1):
            # Plot the localisations
            kernel, Z, Xgrid, Ygrid, extent = self.data[frame] # This is the contour.kdfEstimate
            im = plt.imshow(np.exp(Z), extent=extent, origin='lower', cmap=plt.cm.Greys_r)            
            artists = [im, ]
            
            if self.plotContour:
                contourPaths = list()
                ax = im.get_axes() # get the image axes
                
                if self.curvature is not None:
#                    for frame, cont in self.curvature.items():
                    for contour, C in self.curvature[frame]:
                        XY = contour.vertices
                        cColor = [ color(i) for i in C ]
                        contourPaths.append( ax.scatter(x=XY[:,0], y=XY[:,1], c=cColor, alpha=self.alpha, edgecolor='none', s=self.s, cmap=plt.cm.seismic_r) )
                elif self.contour is not None:
                    for path in self.contour[frame]:                    
                        XY = path.vertices
                        contourPaths.append( ax.scatter(x=XY[:,0], y=XY[:,1], c='red', alpha=self.alpha, edgecolor='none', s=self.s, cmap=plt.cm.seismic_r) )
                else:
                    print("Cannot plot the contour. It is not (yet) available?")

                # Add the artists to the frame
                artists.extend(contourPaths)
                
            frames.append( artists )
        
        return frames
예제 #10
0
    def __init__(self,
                 width=20,
                 height=32,
                 pin=18,
                 freq_hz=800000,
                 dma=5,
                 invert=False,
                 brightness=50):
        # 1D LED strip
        self._strip = rpi_ws281x.PixelStrip(width * height, pin, freq_hz, dma,
                                            invert, brightness)
        self._strip.begin()
        self._width = width
        self._height = height

        # Color data for each pixel, in list-of-lists format
        self._array = [[Color(0, 0, 0) for i in range(height)]
                       for j in range(width)]  #Index as _array[row][col]

        # List to use for indexing into led strip (vectorization)
        self._indices = [i for i in range(width * height)]
예제 #11
0
def visualize_seam_on_image(pixels, seam_xs):
    """
    Draws a red line on the image along the given seam. This is done to
    visualize where the seam is.

    This is NOT one of the functions you have to implement.
    """

    h = len(pixels)
    w = len(pixels[0])

    new_pixels = [[p for p in row] for row in pixels]

    for y, seam_x in enumerate(seam_xs):
        min_x = max(seam_x - 2, 0)
        max_x = min(seam_x + 2, w - 1)

        for x in range(min_x, max_x + 1):
            new_pixels[y][x] = Color(255, 0, 0)

    return new_pixels
예제 #12
0
def visualize_seam_end_on_image(pixels, end_x):
    """
    Draws a red box at the bottom of the image at the specified x-coordinate.
    This is done to visualize approximately where a vertical seam ends.

    This is NOT one of the functions you have to implement.
    """

    h = len(pixels)
    w = len(pixels[0])

    new_pixels = [[p for p in row] for row in pixels]

    min_x = max(end_x - 5, 0)
    max_x = min(end_x + 5, w - 1)

    min_y = max(h - 11, 0)
    max_y = h - 1

    for y in range(min_y, max_y + 1):
        for x in range(min_x, max_x + 1):
            new_pixels[y][x] = Color(255, 0, 0)

    return new_pixels
 def pattern_at(self, pattern, point):
     return Color(point.x, point.y, point.z)
예제 #14
0
 def turnOff(self):
     self._array = [[Color(0, 0, 0) for i in range(self._height)]
                    for j in range(self._width)]
     self.display()
예제 #15
0
class HIBPApi(object):

    color = Color()
    uri = 'https://api.pwnedpasswords.com/range/'
    headers = {'user_agent': 'pass_pwned'}

    def __init__(self, passwd, file_passwd):
        self.passwd = passwd
        self.path = file_passwd

    def passwd_check(self, attempts=3):
        """
        Check single password in HIBP database using web-API
        (sleeping between request to prevent HTTP 429 (Rate limit exceeded),
        please refer to https://haveibeenpwned.com/API/v2)
        :param attempts: number of attempts to check
        :return: result of the check as string
        """
        try:
            print('[{}] Checking password in DB:'.format(
                self.color.brush('working', 'cyan')))
            encrypted_pass = PassEncrypt(self.passwd).encrypt()
            for attempt in range(attempts):
                hibp_request = requests.get('{}{}'.format(
                    self.uri, encrypted_pass[:5]),
                                            headers=self.headers)
                if hibp_request.status_code == 200:
                    raw_data = hibp_request.text.split('\n')
                    suffixes = {
                        hash_suff.split(':')[0]:
                        int(hash_suff.split(':')[1].replace('\r', ''))
                        for hash_suff in raw_data
                    }
                    breaches = suffixes.get(encrypted_pass[5:].upper())
                    if breaches is not None:
                        return self.color.brush(
                            'Your password is PWNeD (appears {} times in DB) :('
                            .format(breaches), 'red')
                    return self.color.brush(
                        'Your password is not found in HIBP DB', 'green')
                time.sleep(1.5)
            print('{}'.format(
                self.color.brush('Unexpected response code. Shutting down',
                                 'purple')))
            sys.exit()
        except Exception as e:
            print('[{}] oops, something went wrong: {}'.format(
                self.color.brush('fail', 'red'), e))
            print('{}'.format(
                self.color.brush('Exception raised. Shutting down', 'purple')))
            sys.exit()

    def file_check(self, attempts=3):
        """
        Check set of passwords provided from the file in HIBP
        database using web-API (sleeping between request to prevent
        HTTP 429 (Rate limit exceeded), please refer to
        https://haveibeenpwned.com/API/v2)
        :param attempts: number of attempts to check
        :return: dictionary with password as key and result of the check as
        value
        """
        file_passwd = extract_passwd(self.path)
        pass_dict = {}
        completion = 0
        start_time = time.time()
        num_of_passwd = len(file_passwd)
        print('[{}] Checking passwords in HIBP DB:'.format(
            self.color.brush('working', 'cyan')))
        try:
            for passwd in file_passwd:
                progress_bar(completion, num_of_passwd, start_time)
                encrypted_pass = PassEncrypt(passwd).encrypt()
                for attempt in range(attempts):
                    hibp_request = requests.get('{}{}'.format(
                        self.uri, encrypted_pass[:5]),
                                                headers=self.headers)
                    if hibp_request.status_code == 200:
                        raw_data = hibp_request.text.split('\n')
                        suffixes = {
                            hash_suff.split(':')[0]:
                            int(hash_suff.split(':')[1].replace('\r', ''))
                            for hash_suff in raw_data
                        }
                        breaches = suffixes.get(encrypted_pass[5:].upper())
                        if breaches is not None:
                            pass_dict[
                                passwd] = 'PWNeD (appears {} times in DB) :('.format(
                                    breaches)
                            break
                        pass_dict[passwd] = 'Not found in HIBP DB'
                        break
                    time.sleep(1.5)
                pass_dict.setdefault(passwd, 'Not able to check')
                time.sleep(1.5)
                completion += 1
            progress_bar(completion, num_of_passwd, start_time)
            return pass_dict
        except Exception as e:
            print('[{}] oops, something went wrong: {}'.format(
                self.color.brush('fail', 'red'), e))
            print('{}'.format(
                self.color.brush('Exception raised. Shutting down', 'purple')))
            sys.exit()

    def make_request_to_hibp(self):
        """
        Make single request to HIBP or several requests,
        depends CLI arguments provided (single password or file with passwords)
        """
        if self.passwd is not None:
            checked_passwd = self.passwd_check()
            print(checked_passwd)
            print('[{}] for more information visit: {}'.format(
                self.color.brush('done', 'green'),
                self.color.brush('haveibeenpwned.com', 'purple')))
        else:
            write_pass_to_file(self.file_check())
            print('For more information visit: {}'.format(
                self.color.brush('haveibeenpwned.com', 'red')))
예제 #16
0
def getDamtypeColor(damType: Optional[DamType]) -> Optional[Color]:
    if damType == DamType.ACID:
        return Color(0, 255, 0)  # green
    elif damType == DamType.ASPHYXIATION:
        return Color(202, 31, 123)  # magenta
    elif damType == DamType.COLD:
        return Color(0, 0, 255)  # blue
    elif damType == DamType.ELECTRICITY:
        return Color(125, 249, 255)  # electric blue
    elif damType == DamType.FIRE:
        return Color(226, 88, 34)  # flame
    elif damType == DamType.MAGICAL:
        return Color(255, 130, 67)  # mango tango
    elif damType == DamType.POISON:
        return Color(46, 139, 87)  # sea green
    elif damType == DamType.PSI:
        return Color(10, 186, 181)  # tiffany blue
    elif damType == DamType.HARM:
        return Color(139, 133, 137)  # taupe gray
    elif damType == DamType.PHYSICAL:
        return Color(192, 192, 192)  # silver
    elif damType == DamType.HEAL:
        return Color(253, 245, 230)  # old lace
    else:
        return None
예제 #17
0
import dill  # type: ignore
from multiprocessing.connection import Listener
from os import getuid
from typing import cast, NamedTuple, Optional, Tuple

from partytypes import Member, Place, State
from utils import Color, colorize

SOCKET_FILE = "/var/run/user/{0}/bcproxy-tf-scripts-party".format(getuid())


RED = Color(0xFF, 0, 0)
GREEN = Color(0, 0xFF, 0)
YELLOW = Color(0xFF, 0xFF, 0)
WHITE = Color(0xFF, 0xFF, 0xFF)
OUT_OF_FORMATION_COLOR = Color(204, 153, 255)


def draw(s):
    print("\033c", end="")  # clear screen
    print(s)


def getMemberState(member: Member) -> Tuple[str, Optional[Color]]:
    """
    String and color for member state
    """
    # ambushed is missing as batmud gives that in pss but not in the party
    # status message for batclient
    if member.unconscious == 1:
        return ("unc", RED)
    def pattern_at(self, pattern, point):
        c1 = pattern.a.pattern_at(pattern.a, point)
        c2 = pattern.b.pattern_at(pattern.b, point)

        c3 = Color.add(c1, c2)
        return Color(c3.r/2, c3.g/2, c3.b/2)
예제 #19
0
Floor.material.pattern = CheckerPattern()
Floor.material.reflection = 0.4
Floor.material.ambient = 0.8
Floor.material.diffuse = 0.2
Floor.material.specular = 0.2

_sphere = Sphere()
_sphere.transform = translation(0, 1, -0.5)
_sphere.material = Material()
_sphere.material.diffuse = 0.1
_sphere.material.shininess = 200.0
_sphere.material.transparency = 0
_sphere.material.reflective = 0.6
_sphere.material.refractive_index = 1.52
_sphere.material.ambient = 0.6
_sphere.material.color = Color(1, 0, 0)
_sphere.material.specular = 0.6

_sphere2 = Sphere()
_sphere2.transform = np.matmul(translation(1.7, 0.7, -0.9),
                               scaling(0.7, 0.7, 0.7))
_sphere2.material = Material()
_sphere2.material.diffuse = 0.4
_sphere2.material.shininess = 200.0
_sphere2.material.transparency = 0
_sphere2.material.reflective = 0.2
_sphere2.material.refractive_index = 1.52
_sphere2.material.ambient = 0.8
_sphere2.material.color = Color(0.1, 0.3, 1)
_sphere2.material.specular = 0.8
# glassSphere.transform = scaling(0.5, 0.5, 0.5)
 def __init__(self, primary=Color.white(), secondary=Color(), transform_matrix=identity):
     super().__init__(primary, secondary, transform_matrix)
예제 #21
0
from __future__ import print_function
import sys
import os

sys.path.insert(0,'/home/pi/pixelcanvas')
import numpy
from random import randint
from random import choice
import copy

from utils import Color


BLANK  = Color(000, 000, 000) # empty space
CYAN   = Color(000, 255, 255) #long piece
BLUE   = Color(000, 000, 255) #backwards L
ORANGE = Color(255, 150, 000) #normal L
YELLOW = Color(255, 255, 000) #square
GREEN  = Color(000, 128, 000) #backwards z
PURPLE = Color(128, 000, 128) #t
RED    = Color(255, 000, 000) #normal z

COLORS = [BLANK, CYAN, BLUE, ORANGE, YELLOW, GREEN, PURPLE, RED]

UP = 0
LEFT = 1
DOWN = 2
RIGHT = 3

MOVLEFT = 0
MOVRIGHT = 1
예제 #22
0
    SpellBind,
    SpellBinds,
    SpellsForCategory,
    State,
)
from spells import (
    DamType,
    getDamtypeColor,
    Spell,
)
from utils import Color, colorize


SOCKET_FILE = "/var/run/user/{0}/bcproxy-tf-scripts-caster".format(getuid())

YELLOW = Color(0xFF, 0xFF, 0)


def draw(s):
    print("\033c", end="")  # clear screen
    print(s)


def categoryBindHelp(category: Category, categoryBinds: CategoryBinds) -> str:
    getCatStr: Callable[[CategoryBind], str] = (
        lambda cb: colorize(cb.explanation, YELLOW)
        if cb.category == category
        else cb.explanation
    )
    return "\n".join(map(lambda cbs: " ".join(map(getCatStr, cbs)), categoryBinds))