Ejemplo n.º 1
0
def listen_to_offers():
    UDP_PORT = 13117
    MAGIC_COOKIE = 0xfeedbeef
    MSG_TYPE = 0x2

    print(colorize.colorize('Client started, listening for offer requests...'))

    # init socket to address family (host, port) and for UDP connection and broadcast
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.bind(('', UDP_PORT))

    got_offer = False
    while not got_offer:
        try:

            data, addr = sock.recvfrom(1024)  # buffer size is 1024 bytes

            msg = struct.unpack('!IBH', data)

            # validate offer
            if len(msg) == 3 and msg[0] == MAGIC_COOKIE and msg[1] == MSG_TYPE:
                got_offer = True
                sock.close()

                # return tuple (server ip, server tcp port)
                return addr[0], msg[2]
            time.sleep(0.5)

        except Exception as exc:
            print(colorize.colorize(exc, colorize.Colors.error))
Ejemplo n.º 2
0
def connect_to_clients(sock, teams, group1, group2):
    BUFFER_SIZE = 1024

    # start game after 10 seconds
    start_time = time.time()
    group_index = 1
    while time.time() - start_time < 10:
        try:

            sock.settimeout(time.time() - start_time)
            conn, _ = sock.accept()
            conn.setblocking(False)

            data = conn.recv(BUFFER_SIZE)
            team_name = data.decode("utf-8")[:-1]
            print(
                colorize.colorize(f'Team: {team_name}',
                                  colorize.Colors.server))

            teams[team_name + "_" + str(group_index)] = conn

            # assign team to a group
            if group_index % 2 == 0:
                group2.append(team_name + "_" + str(group_index))
            else:
                group1.append(team_name + "_" + str(group_index))

            time.sleep(0.1)
            group_index += 1
        except Exception as exc:
            if str(exc) != 'timed out':
                print(colorize.colorize(exc, colorize.Colors.fatal))

    sock.settimeout(None)
    return group_index > 1
Ejemplo n.º 3
0
def play(client_socket):
    thread = Thread(target=write_input, args=[client_socket])
    thread.start()
    buffer = ''
    while True:

        # check if we can read from server or write to it
        readable, _, _ = select([client_socket], [], [])
        if readable:
            data = client_socket.recv(1024)

            # EOF means server disconnected
            if not data:
                if buffer:
                    print(colorize.colorize(buffer, colorize.Colors.server))
                print(
                    colorize.colorize('Disconnected from server',
                                      colorize.Colors.title))
                break
            buffer += data.decode()
            if '\n' in buffer:
                print(colorize.colorize(buffer, colorize.Colors.server))
                buffer = ''

        time.sleep(0.5)
    print(colorize.colorize('Press anything to continue',
                            colorize.Colors.pink))
    thread.join()
Ejemplo n.º 4
0
def transform_points(
    xyz,
    listener,
    to_frame,
    from_frame,
    n_tries=10,
    ):

    # listener.waitForTransform(to_frame, from_frame, rospy.Time.now(), rospy.Duration(1))

    for i in xrange(n_tries):
        try:
            (trans, rot) = listener.lookupTransform(to_frame,
                    from_frame, rospy.Time(0))
            break
        except Exception:
            print 'tf exception:'
            print colorize(traceback.format_exc(), 'yellow')
            rospy.sleep(.1)
            time.sleep(.05)
    if i == n_tries - 1:
        raise Exception('f**k tf')
    hmat = conversions.trans_rot_to_hmat(trans, rot)

    xyz1 = np.c_[xyz.reshape(-1, 3), np.ones((xyz.size / 3, 1))]
    xyz1_tf = np.dot(xyz1, hmat.T)
    xyz_tf = xyz1_tf[:, :3].reshape(xyz.shape)
    return xyz_tf
Ejemplo n.º 5
0
def friendly_repr(model):
    """
        Rails-style string representation. Ex:
        #<models.Person@0x12a8db50 id: 123, name: "John Doe">
    """

    attrs = __friendly_attrs(model.attributes)
    model = model.__module__ + "." + model.__class__.__name__ + '@' + hex(id(model))
    return "#<%s %s>" % (colorize('yellow', model), colorize('bold', ", ".join(attrs)))
Ejemplo n.º 6
0
def diff(oldlist, newlist):
    for i in oldlist.keys():
        if i not in newlist.keys():
            print(colorize("have been deleted: " + i, 'cyan'))
        elif oldlist[i] == newlist[i]:
            pass
        elif oldlist[i] != newlist[i]:
            print(colorize("changed: " + i, 'green'))
    for i in newlist.keys():
        if i not in oldlist.keys():
            print(colorize("new file: " + i, 'red'))
Ejemplo n.º 7
0
    def pp(self, results, mark=None):
        order = ['I_ID', 'I_DATE', 'I_TIME', 'I_MOVES', 'I_COMPL']
        widths = [8, 20, 10, 5, 10]
        headings = ['Game #', 'Date/Time', 'Time', 'Moves', 'Complete']

        total_width = sum(widths) + 3*len(widths) + 1

        col_fmts = ['{N:>{w[N]}}'.replace('N', str(n)) for n in range(0,5)]
        line_fmt = '| ' + ' | '.join(col_fmts) + ' |'
        border = '-' * total_width

        table = [border, line_fmt.format(*headings, w=widths), border]

        for r in results:
            args = []
            highlight = mark and r[mark[0]] == mark[1]
            for prop in order:
                value = r[getattr(self, prop)]
                width = widths[order.index(prop)]
                if prop == 'I_TIME' and value not in headings:
                    value = '{}:{:02}:{:02}'.format(
                        value // 3600, value // 60 % 60, value % 60
                    )
                elif prop == 'I_COMPL' and value not in headings:
                    value = 'X' if value else ' '
                elif highlight and prop == 'I_ID':
                    value = '{:*>{w}}'.format(value, w=width)
                args.append(value)
            line = line_fmt.format(*args, w=widths)
            if highlight:
                line = colorize(line, var='rev')
            table.append(line)

        table.append(border)
        print '\n'.join(table)
Ejemplo n.º 8
0
def play(server_socket):
    teams = {}
    group1 = []
    group2 = []

    try:
        game = connect_to_clients(server_socket, teams, group1, group2)

        # if no teams don't start game
        if not game:
            return False

        for conn in teams.values():
            conn.sendall(b'Welcome to Keyboard Spamming Battle Royale.\n')
            conn.sendall('Group 1 :\n==\n{0}\n'.format(
                '\n'.join(group1)).encode())
            conn.sendall('Group 2 :\n==\n{0}\n'.format(
                '\n'.join(group2)).encode())

        # shutdown automatically
        with concurrent.futures.ThreadPoolExecutor() as executor:
            scores_futures = []
            for team, conn in teams.items():
                scores_futures.append(
                    executor.submit(player_runnable,
                                    team=team,
                                    conn=conn,
                                    game_time=10))
                conn.sendall(b'START SPAMMING!!!!!\n')

            # Main thread computes results
            g1_res = 0
            g2_res = 0
            for res in concurrent.futures.as_completed(scores_futures):
                res = res.result()
                if res[0] in group1:
                    g1_res += res[1]
                else:
                    g2_res += res[1]

        game_over_msg = f'Game Over!\n Group 1 score: {g1_res}\n Group 2 score: {g2_res}\n'
        if g1_res > g2_res:
            game_over_msg += 'Winners : Group 1 !\n'
        elif g2_res > g1_res:
            game_over_msg += 'Winners : Group 2 !\n'
        else:
            game_over_msg += 'Tie !\n'

        for conn in teams.values():
            conn.sendall(game_over_msg.encode())

    except Exception as exc:
        print(colorize.colorize(exc, colorize.Colors.fatal))

    finally:
        time.sleep(len(teams))
        for conn in teams.values():
            conn.close()

    return True
Ejemplo n.º 9
0
def predice_image(img_msg):
    global g_kinect_img

    feature_vision = np.zeros([1, 256, 512, 34], dtype=np.float32)
    #np_arr = np.fromstring(img_msg.data, np.uint8)
    #image = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)
    image = bridge.imgmsg_to_cv2(img_msg)
    g_kinect_img = image * 1
    # print('     image shape recieved:', image.shape)
    # image = bridge.imgmsg_to_cv2(img_msg)

    image = sp.misc.imresize(image, image_shape[1:], interp='bilinear')

    image = image[..., ::-1]  # bgr to rgb

    image = (image - image.mean()) / image.std()

    feed_dict = {image_op: image[np.newaxis, ...]}

    prediction_label = sess.run(predictions_op, feed_dict=feed_dict)
    feature_vision = sess.run(predictions_op_prob, feed_dict=feed_dict)

    #     pickle.dump(prediction_prob, open("/home/xi/workspace/labels/prob.p", "wb"))
    prediction_label = colorize(prediction_label, cityscapes.augmented_labels)
    # image_message = bridge.cv2_to_imgmsg(prediction_label)
    # label_pub.publish(image_message)

    #cv2.imshow("prediction_label", prediction_label)
    #cv2.waitKey(0)

    # prediction_label = prediction_label[..., ::-1] # rgb to bgr
    # prediction_publisher.publish(bridge.cv2_to_imgmsg(prediction_label))

    # print(' CNN feature done')
    return feature_vision
Ejemplo n.º 10
0
def _colorize_raw_frames(source_path, model):
    for img in os.listdir(str(bw_frames_root)):
        img_path = bw_frames_root + '/' + img

        if os.path.isfile(str(img_path)):
            color_image = colorize(img_path, model, (256, 256))
            skimage.io.imsave(str(rgb_frames_root + '/' + img), color_image)
Ejemplo n.º 11
0
    def body():
        return p(
            _("Setting this variable suppresses the automatic output file name "
              "determination and makes Frescobaldi look for output documents "
              "(PDF, MIDI, etc.) with the specified basename, or comma-"
              "separated list of names."),
            _("If a name ends with a directory separator, output files are "
              "looked for in the specified directory. "),
            _("All names are relative to the document's filename."),
            _("For example:"),
            colorize(r"""\version "2.14.2"
% -*- output: pdfs/;
\book {
  \bookOutputName #(string-append "pdfs/" some-variable)
  \score {
    \relative c' {
      c d e f g
    }
  }
}"""),
            _("You can set this variable if the automatic output file name "
              "determination would be time-consuming (as Frescobaldi parses "
              "the document and all the documents it includes, searching for "
              "the LilyPond commands that specify the output name, such as "
              "<code>\\bookOutputName</code>, etc); or when the automatic "
              "output file name determination does not work due to complicated "
              "LilyPond code."),
            )
Ejemplo n.º 12
0
def main():
    signal.signal(signal.SIGINT, quit)
    signal.signal(signal.SIGTERM, quit)

    IP = None
    if len(sys.argv) > 1 and sys.argv[1] == '-t':
        IP = get_if_addr("eth2")
    else:
        IP = get_if_addr("eth1")

    TCP_PORT = 2086
    print(colorize.colorize(f'Server started, listening on IP address {IP}'))

    try:

        # init socket to address family (host, port) and for TCP connection
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind((IP, TCP_PORT))

        # make socket a server's one, 5 is only advisory for num of connections
        server_socket.listen(5)

        while True:
            thread = Thread(target=send_offer, args=[IP])
            thread.start()
            game = play(server_socket)
            thread.join()
            if game:
                print('Game over, sending out offer requests...')
            else:
                print('Looking for players...')
            time.sleep(1)
    finally:
        server_socket.close()
Ejemplo n.º 13
0
 def code_start(self, code, specifier=None):
     if specifier == "lilypond":
         import colorize
         self._html.append(colorize.colorize(code))
     else:
         self.tag('code')
         self.tag('pre')
         self.text(code)
Ejemplo n.º 14
0
def transform_points(xyz, listener, to_frame, from_frame, n_tries=10):
    #listener.waitForTransform(to_frame, from_frame, rospy.Time.now(), rospy.Duration(1))
    for i in xrange(n_tries):
        try:
            trans, rot = listener.lookupTransform(to_frame, from_frame,
                                                  rospy.Time(0))
            break
        except Exception:
            print "tf exception:"
            print colorize.colorize(traceback.format_exc(), "yellow")
            rospy.sleep(.1)
            time.sleep(.05)
    if i == n_tries - 1: raise Exception("f**k tf")
    hmat = conversions.trans_rot_to_hmat(trans, rot)

    xyz1 = np.c_[xyz.reshape(-1, 3), np.ones((xyz.size / 3, 1))]
    xyz1_tf = np.dot(xyz1, hmat.T)
    xyz_tf = xyz1_tf[:, :3].reshape(xyz.shape)
    return xyz_tf
    def render(self):
        outfile = sys.stdout

        row, col = self.s // self.ncol, self.s % self.ncol
        desc = self.desc.tolist()
        desc = [[c.decode('utf-8') for c in line] for line in desc]
        desc[row][col] = colorize(desc[row][col], "red", highlight=True)
        if self.lastaction is not None:
            outfile.write("  ({})\n".format(["Left", "Down", "Right",
                                             "Up"][self.lastaction]))
        else:
            outfile.write("\n")
        outfile.write("\n".join(''.join(line) for line in desc) + "\n")
Ejemplo n.º 16
0
def player_runnable(team, conn, game_time):
    score = 0
    start_time = time.time()
    while time.time() - start_time < game_time:
        readable, _, _ = select([conn], [], [])
        if readable:
            try:
                data = conn.recv(1024)
                if not data: break
                score += len(data)
            except Exception as exc:
                print(colorize.colorize(exc, colorize.Colors.fatal))
        time.sleep(0.5)

    return team, score
Ejemplo n.º 17
0
def iter_prob(size):
    """ Iterate over the probability and return the Percolation Probability """
    data = np.zeros(shape=(19, ), dtype=int)
    prob = 0  # probability of a cell being "on"

    for i in range(19):
        prob += 0.05
        perc = 0  # The number of percolations in 100 tries
        print("==> Percolating 100 times for Probability", prob)
        for _ in range(100):
            print("==> Percolating the", _, "th time for Probability", prob)
            grid = grs(size, prob)
            c_grid = colorize(grid)
            if is_percolated(c_grid):
                perc += 1
        data[i] = perc

    return data
Ejemplo n.º 18
0
    def body():
        return p(
        _("By default, LilyPond creates only a PDF file of the music. "
          "To create a MIDI file, you must wrap the music in a <code>\\score"
          "</code> block and add a <code>\\midi</code> block to it."),
        _("For example:"),
        colorize(r"""\version "2.14.2"

music = \relative c' {
  c4 d e f g2
}

\score {
  \music
  \layout {}
  \midi {}
}"""),
        _("If you omit the <code>\\layout</code> block, no PDF file will be "
          "generated, only a MIDI file."),
        )
Ejemplo n.º 19
0
def connect_to_server(addr):

    # init socket to address family (host, port) and for TCP connection
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        print(f'Received offer from {addr[0]}, attempting to connect...')
        client_socket.connect((addr[0], addr[1]))
        client_socket.setblocking(False)

        team_name = b'Catan settlers\n'
        client_socket.sendall(team_name)
        play(client_socket)

    except Exception as exc:
        print(colorize.colorize(exc, colorize.Colors.fatal))

    finally:

        client_socket.close()
Ejemplo n.º 20
0
    def colorize_sketch(self):
        if self.sketch_img is None:
            self.print_error('Please Load Sketch Image')
            return
        gpu = self.use_gpu.get()
        use_512 = self.use_512.get()
        enable_str = 'enabled' if gpu else 'disabled'
        self.print_status(f'Colorize with {512 if use_512 else 256}px model / GPU {enable_str}')

        target_img = self.sketch_img # ImageOps.autocontrast(self.sketch_img, ignore=255)
        
        try:
            color_img = colorize.colorize(target_img, 
                self.choice_box.get_selected(), 
                gpu=self.use_gpu.get(),
                input_size=512 if use_512 else 256)
            self.set_img(color_img)
            w, h = color_img.size
            self.print_status(f'Colorized result: ({w}x{h})px')
        except Exception:
            traceback.print_exc()
            self.print_error('Failed to colorize sketch. Check stack trace')
Ejemplo n.º 21
0
def test_all(stop=False):
    nPass,nFail = 0,0
    for (name,func) in TEST_FUNCS.items():
        print colorize("function: %s"%name,"green")
        try:
            t_start = time()
            func()
            t_elapsed = time() - t_start
            print colorize("PASSED (%.3f sec)"%t_elapsed,"blue")
            nPass += 1
        except Exception:    
            traceback.print_exc(file=sys.stdout)
            if stop: raise
            print colorize("FAILED","red")
            nFail += 1
            
            
    print "%i passed, %i failed"%(nPass,nFail)
Ejemplo n.º 22
0
    print
    print "Example: socket_io_client websocket.example.org 8888 client.example.org /socket.io/websocket"
    sys.exit(1)

  HOST = len(sys.argv) <= 1 and 'websocket.security.localhost' or sys.argv[1]    # The remote host
  PORT = len(sys.argv) <= 2 and 8124 or int(sys.argv[2])                           # The remote port
  ORIGIN = len(sys.argv) <= 3 and 'victim.security.localhost' or sys.argv[3]     # origin to simulate
  PATH = len(sys.argv) <= 4 and '/socket.io/websocket' or sys.argv[4]

  interactive = os.isatty(0)

  sys.stderr.write("Connecting to " + HOST + ":" + str(PORT) + "\n")
  client = WebSocketsClient.SocketIoClient(host=HOST,port=PORT,origin=ORIGIN,path=PATH)

  if (interactive):
    prompt = colorize("\nWhat to send (nothing: quit, ~jXXX: json object, ~rXXX - raw socket data XXX):", fg='green')
  else:
    prompt = ""

  quit = False
  p = 0

  import random
  while not quit:
    try:
      sys.stderr.flush()

      # Wait for input from stdin & socket
      inputready, outputready,exceptrdy = select.select([0],[],[], 0)
      if client.can_recv():
        inputready.append(client.socket)
Ejemplo n.º 23
0
#Color all the tiles
if grayscale == 0:
    print "Finding pointer of tile palette table from map template 0x%02X..." % map_template
    rom.seek(0x178022+map_template*2)
    tile_pal_table = rom.read(2)
    tile_pal_table = struct.unpack("<H", tile_pal_table)[0] + 0x178000 - 0x4000
    print "Pointer is at 0x%02X to 0x%02X." % (0x178022+map_template*2, 0x178022+map_template*2 + 1)
    rom.seek(tile_pal_table)
    print "Colorizing 16x16 tiles, starting at offset 0x%X..." % tile_pal_table
    for i,v in enumerate(largetiles):
        for j in range(2):
            for k in range(2):
                l = rom.read(1)
                l = (struct.unpack("<b", l)[0])%8
                largetiles[i][j][k] = colorize(largetiles[i][j][k],palettes[l])

rom.close()
print "ROM closed."

#Generate every tile used in the entire map
print "Generating every tile in the map..."
tile_map = tilemap(largetiles,acres)

print "Generating map's tileset..."
tileset = tilemap(largetiles)

outputfile("outputtiles.png",1,tileset,map_tiles,location,grayscale)
print "Finished outputting the tiles."

#Each map has 8x8 acres
Ejemplo n.º 24
0
def quit(sig, frame):
    os.system('reset')
    print(
        colorize.colorize('\nGoodbye! Enter q to quit:',
                          colorize.Colors.title))
    sys.exit(0)
Ejemplo n.º 25
0
    quant.export()

    train_ftr = train_ftr_ext(train_ftr=train, x=x, red=red, perc=perc)
    t2 = train_ftr.run()
    train_ftr.export()

    t3 = ""
    test_ftr = test_ftr_ext(test_ftr=test, x=x, red=red)
    t3 = test_ftr.run()
    test_ftr.export()

    svm = clf_pred(reg=reg)
    t4 = svm.clf()
    t5 = svm.pred()
    svm.export()

    colorizer = colorize(original=test, sobel=sobel)
    t6, output = colorizer.color()
    error = colorizer.compare()
    colorizer.export()

    pd.DataFrame([[
        train, test, k, x, red, perc, reg, sobel, t1, t2, t3, t4, t5, t6,
        np.std(error)
    ]]).to_csv("Record.csv", mode='a', index=False, header=False)

    cv2.imshow('Output', output)
    cv2.imshow('Error', error)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Ejemplo n.º 26
0
                    "   save -- save game and quit\n" \
                    "   q -- quit without saving\n" \
                    "   a/s/d/f/j/k/l/; -- from/to column\n" \
                    "   q/w/e/r -- from/to specific free cell\n" \
                    "   g/t -- to first free cell\n" \
                    "   u/i/o/p -- from/to specific foundation\n" \
                    "   h/t -- to appropriate foundation for from card\n" \
                    "   m -- make all possible foundation moves\n" \
                    "   z -- undo (zz to use in same string as other moves)\n" \
                    "   show -- enter cmd with no args for 'show' help\n" \
                    "   play n restart|resume -- restart/resume game # n\n" \
                    "   ?/help -- show this help\n" \
                    "   py -- enter python interpreter... mostly for inspecting\n" \
                    "         game and history objects\n"

        print colorize(BANNER, fg='green')
        print colorize(gamehelp, fg='yel')

        saved = history.unfinished()
        if saved:
            print colorize('Saved', fg='cyan', var='und')
            history.pp(saved)

        while True:

            try:
                raw_move = raw_input(colorize('move> ', fg='mag'))
            except KeyboardInterrupt:
                move='q'
            else:
                move = raw_move.lower().strip()
Ejemplo n.º 27
0
labelGetter = comm.FileGetter(args.label,"bmp",comm.SingleChannelImageMessage)
ropeInitPub = comm.FilePublisher(args.out,"txt")

prev_id = -1
while True:

    
    latest_id = getLastInd(args.label)
    print "latest id", latest_id
    if latest_id == prev_id:        
        sleep(.1)
        continue
    else:
        prev_id = latest_id    
    
    timePrevStart = time()

    xyz,bgr = pcdGetter.recv_id(latest_id).data
    label = labelGetter.recv_id(latest_id).data

    if label is None: raise Exception("could not read label file")
        
    try:
        xyzs,labels = initialize_rope(label,xyz, bgr,plotting=args.plotting)
        ropeInitPub.send(RopeInitMessage(data=(xyzs, labels)))    
        sleep(max(args.pause - (time() - timePrevStart),0))
    except Exception:
        print colorize("exception occurred in rope init:","red")
        traceback.print_exc()
    
    tf.logging.set_verbosity(tf.logging.DEBUG)

    with tf.Graph().as_default():
        init = tf.global_variables_initializer()

        iterator = input_data(TFRecord_file, batch_size=args.batch_size)
        images, labels = iterator.get_next()
        labels_resized = tf.image.resize_images(
            labels, [img_rows // fac, img_cols // fac])
        model_B = create_full_model(images, 'b')

        print(model_B.summary())

        tf.summary.image('input-image', images)
        tf.summary.image(
            'label', tf.map_fn(lambda img: colorize(img, cmap='jet'), labels))
        tf.summary.image(
            'predict',
            tf.map_fn(lambda img: colorize(img, cmap='jet'),
                      tf.image.resize_images(model_B.output, [224, 224])))
        loss_B = loss_funcs(model_B, labels)

        global_step_tensor = tf.train.get_or_create_global_step()
        vars_encoder = [
            var for var in tf.trainable_variables()
            if var.name.startswith("dil")
        ]
        for i in vars_encoder:
            tf.logging.info("Training only variables in: " + str(i))
        optimizer = tf.train.AdamOptimizer(learning_rate=1e-6)
Ejemplo n.º 29
0
def call_and_print(cmd,color='green'):
    print colorize(cmd, color, bold=True)
    subprocess.check_call(cmd, shell=True)
Ejemplo n.º 30
0
            module_dict = dict((splitext(z.filename)[0].replace('/', '.'),
                                zipf.open(z.filename).read())
                               for z in zipf.infolist()
                               if splitext(z.filename)[1] == ".py")
        elif raw_format[0] == 'tar':
            compression = raw_format[1] if len(raw_format) > 1 else ''
            tarf = taropen(fileobj=f, mode="r:" + compression)
            module_dict = dict((splitext(t.name)[0].replace('/', '.'),
                                tarf.extractfile(t.name).read())
                               for t in tarf.getmembers()
                               if splitext(t.name)[1] == ".py")
    else:
        module_dict = {
            module_description[0]: decodestring(module_description[1])
        }
    return Finder(module_dict)


if __name__ == '__main__':
    #So examples works out of the box
    sys.path.append('examples')
    import external_modules

    sys.meta_path.extend(
        get_modules_meta_paths((external_modules.A_MODULE_MYTEST,
                                external_modules.MODULE_COLORIZE)))
    from colorize import colorize, COLORS
    from testmodule import printme

    print(colorize(printme(), COLORS.get('red')))
        format: either 'zip', 'tar', 'tar:gz', 'tar:bz' or a string to be used as module name
        content: a base64 encoded string of a zip archive, a tar(gz/bz2) archive or a plain python module
    """
    raw_format = module_description[0].split(':')
    if raw_format[0] in ('zip', 'tar'):
        f = BytesIO()
        f.write(decodestring(module_description[1]))
        f.seek(0)
        if raw_format[0] == 'zip':
            zipf = PyZipFile(f)
            module_dict = dict((splitext(z.filename)[0].replace('/', '.'), zipf.open(z.filename).read()) for z in zipf.infolist() if splitext(z.filename)[1] == ".py")
        elif raw_format[0] == 'tar':
            compression = raw_format[1] if len(raw_format) > 1 else ''
            tarf = taropen(fileobj=f, mode="r:" + compression)
            module_dict = dict((splitext(t.name)[0].replace('/', '.'), tarf.extractfile(t.name).read()) for t in tarf.getmembers() if splitext(t.name)[1] == ".py")
    else:
        module_dict = {module_description[0]: decodestring(module_description[1])}
    return Finder(module_dict)


if __name__ == '__main__':
    #So examples works out of the box
    sys.path.append('examples')
    import external_modules

    sys.meta_path.extend(get_modules_meta_paths((external_modules.A_MODULE_MYTEST, external_modules.MODULE_COLORIZE)))
    from colorize import colorize, COLORS
    from testmodule import printme

    print(colorize(printme(), COLORS.get('red')))
Ejemplo n.º 32
0
def ColorTableLinks(xlabels, ylabels, data, links, savetag = None,
                    labelfontsize = 18, labelrotation = 45, textsize = 18,
                    spacing = 0.025, colormap = "Blues",
                    fmt = "%.1f", title = None, cmin = None,
                    cmax = None, xlabel = None, ylabel = None,
                    xlabel_spacing = 0.00, ylabel_spacing = 0.00,
                    nancolor = (0.0, 0.0, 0.0), titlefontsize = 20):
    '''
    Creates a `matplotlib.pyplot` version of a simple 2D
    table, where the values in each cell are color coded
    for easy viewing.
    '''

    assert len(xlabels) == data.shape[0]
    assert len(ylabels) == data.shape[1]
    assert data.shape == links.shape

    # Dimensions
    Nx = len(xlabels)
    Ny = len(ylabels)

    # Create vector from 2d data
    datav = data.reshape([-1])

    # Get colormap for data range
    vcolors, smap, cnorm = colorize(datav, cmap=colormap, vmin = cmin,
                                    vmax = cmax)

    # Create figure
    fig, ax = plt.subplots(Ny ,Nx, figsize = (Nx,Ny))

    # Set title, optional
    if title is not None:
        ax[0, int(Nx/2)].set_title(title, fontsize = titlefontsize)

    # Adjust spacing
    plt.subplots_adjust(wspace=spacing, hspace=spacing)

    # Loop over grid cells
    for ix in range(Nx):
        for iy in range(Ny):

            # Remove all ticks
            ax[iy, ix].set_xticks([])
            ax[iy, ix].set_yticks([])

            # Set boxcolor by colormap
            boxcolor = smap.cmap(cnorm(data[ix, iy]))

            if np.isnan(data[ix, iy]):
                boxcolor = nancolor

            # Set the facecolor to boxcolor
            """
            ax[iy, ix].set_facecolor(boxcolor)
            """

            # Get RGB
            R = boxcolor[0] * 255
            G = boxcolor[1] * 255
            B = boxcolor[2] * 255

            # Calculate grey "brightness"
            grey = (R*0.299 + G*0.587 + B*0.114)

            # Set text color based on brightness
            if grey > 186:
                textcolor = "#000000"
            else:
                textcolor = "#ffffff"

            # Catch nans and infs
            if np.isfinite(data[ix, iy]):
                text = fmt %data[ix, iy]
            else:
                text = "%.2f" %data[ix, iy]

            # Determine if greater/less than signs are needed
            if cmax is not None:
                if data[ix, iy] > cmax:
                    text = r"$>$"+fmt %cmax
            if cmin is not None:
                if data[ix, iy] < cmin:
                    text = r"$<$"+fmt %cmin

            # Add text to plot
            """
            ax[iy, ix].text(0.5, 0.5, text, ha="center", va="center",
                            bbox=dict(boxstyle="square", fc="w", ec="w", alpha=0.0),
                            color = textcolor)
            """

            # Using massive scatter points to color axes because set_url
            # actually works for them (as opposed to axis.set_url)
            website = links[ix, iy]
            s = ax[iy, ix].scatter([0.5,2], [0.5,5], s = 100000, c = boxcolor)
            if website is not None:
                s.set_urls([website, website])
            ax[iy, ix].set_xlim(0.4, 0.6)
            ax[iy, ix].set_ylim(0.4, 0.6)
            # Add text to plot
            atext = ax[iy, ix].text(0.5, 0.5, text, ha="center", va="center",
                            bbox=dict(boxstyle="square", fc="w", ec="w", alpha=0.0),
                            color = textcolor, fontsize = textsize)
            if website is not None:
                atext.set_url(website)

            # Get rid of the axis frame
            for spine in ax[iy, ix].spines.values():
                spine.set_visible(False)

    # Loop over x
    for ix in range(Nx):
        # Set tick to be in middle
        ax[-1,ix].set_xticks([0.5])
        # Set tick label by user provided
        ax[-1,ix].set_xticklabels([xlabels[ix]], rotation = labelrotation, fontsize = labelfontsize, ha = "right")

    # Loop over y
    for iy in range(Ny):
        # Set tick to be in middle
        ax[iy,0].set_yticks([0.5])
        # Set tick label by user provided
        ax[iy,0].set_yticklabels([ylabels[iy]], rotation = labelrotation, fontsize = labelfontsize, ha = "right")

    # Set ylabel
    if ylabel is not None:
        fig.text(ylabel_spacing, 0.5, ylabel, ha = "left", va = "center",
            fontsize=mpl.rcParams['font.size'], zorder=10, rotation = 90,
            bbox=dict(boxstyle="square", fc="none", ec="none"))

    # Set xlabel
    if xlabel is not None:
        fig.text(0.5, xlabel_spacing, xlabel, ha = "center", va = "bottom",
                fontsize=mpl.rcParams['font.size'], zorder=10,
                bbox=dict(boxstyle="square", fc="none", ec="none"))

    # Save figure, optional
    if savetag is not None:
        fig.canvas.print_figure(savetag + '.svg', bbox_inches = "tight")

    return fig, ax
Ejemplo n.º 33
0
def main():
    parser = build_parser()
    options = parser.parse_args()

    if not os.path.isfile(options.network):
        parser.error(
            "Network %s does not exist. (Did you forget to download it?)" %
            options.network)

    content_image_gray = imread(options.content_gray)
    style_images = [imread(style) for style in options.styles]
    style_images_gray = [
        imread(style_gray) for style_gray in options.styles_gray
    ]

    width = options.width
    if width is not None:
        new_shape = (int(
            math.floor(
                float(content_image_gray.shape[0]) /
                content_image_gray.shape[1] * width)), width)
        content_image_gray = cv2.resize(content_image_gray, new_shape)
    target_shape = content_image_gray.shape
    for i in range(len(style_images)):
        style_scale = STYLE_SCALE
        if options.style_scales is not None:
            style_scale = options.style_scales[i]
        style_images[i] = cv2.resize(style_images[i], (int(
            style_scale * target_shape[1] / style_images[i].shape[1] *
            style_images[i].shape[0]), int(style_scale * target_shape[1])))
        style_images_gray[i] = cv2.resize(style_images_gray[i], (int(
            style_scale * target_shape[1] / style_images_gray[i].shape[1] *
            style_images_gray[i].shape[0]), int(
                style_scale * target_shape[1])))

    style_blend_weights = options.style_blend_weights
    if style_blend_weights is None:
        # default is equal weights
        style_blend_weights = [1.0 / len(style_images) for _ in style_images]
    else:
        total_blend_weight = sum(style_blend_weights)
        style_blend_weights = [
            weight / total_blend_weight for weight in style_blend_weights
        ]

    initial = options.initial
    if initial is not None:
        initial = cv2.resize(
            imread(initial),
            (content_image_gray.shape[1], content_image_gray.shape[0]))
        # Initial guess is specified, but not noiseblend - no noise should be blended
        if options.initial_noiseblend is None:
            options.initial_noiseblend = 0.0
    else:
        # Neither inital, nor noiseblend is provided, falling back to random generated initial guess
        if options.initial_noiseblend is None:
            options.initial_noiseblend = 1.0
        if options.initial_noiseblend < 1.0:
            initial = content_image

    if options.checkpoint_output and "%s" not in options.checkpoint_output:
        parser.error("To save intermediate images, the checkpoint output "
                     "parameter must contain `%s` (e.g. `foo%s.jpg`)")

    for iteration, image in colorize(
            network=options.network,
            initial=initial,
            initial_noiseblend=options.initial_noiseblend,
            content_gray=content_image_gray,
            styles=style_images,
            styles_gray=style_images_gray,
            preserve_colors=options.preserve_colors,
            iterations=options.iterations,
            style_weight=options.style_weight,
            style_layer_weight_exp=options.style_layer_weight_exp,
            style_blend_weights=style_blend_weights,
            tv_weight=options.tv_weight,
            learning_rate=options.learning_rate,
            beta1=options.beta1,
            beta2=options.beta2,
            epsilon=options.epsilon,
            pooling=options.pooling,
            print_iterations=options.print_iterations,
            checkpoint_iterations=options.checkpoint_iterations):
        output_file = None
        combined_rgb = image
        if iteration is not None:
            if options.checkpoint_output:
                output_file = options.checkpoint_output % iteration
        else:
            output_file = options.output
        if output_file:
            imsave(output_file, combined_rgb)
Ejemplo n.º 34
0
    runopts = tf.RunOptions(report_tensor_allocations_upon_oom = True)
    coloredlogs.install(level='DEBUG')
    tf.logging.set_verbosity(tf.logging.DEBUG)
    
    with tf.Graph().as_default():
        init = tf.global_variables_initializer()
    
        iterator = input_data(TFRecord_file,batch_size=args.batch_size)
        images,labels = iterator.get_next()
        labels_resized = tf.image.resize_images(labels,[img_rows//fac, img_cols//fac])
        model_B = create_full_model(images, 'b')
        
        print (model_B.summary())

        tf.summary.image('input-image', images)
        tf.summary.image('label', tf.map_fn(lambda img: colorize(img, cmap='jet'), labels))
        tf.summary.image('predict', tf.map_fn(lambda img: colorize(img, cmap='jet'), tf.image.resize_images(model_B.output,[224,224])))
        loss_B = loss_funcs(model_B, labels)

        global_step_tensor = tf.train.get_or_create_global_step()
        vars_encoder = [var for var in tf.trainable_variables() if var.name.startswith("dil")]
        for i in vars_encoder:
            tf.logging.info("Training only variables in: " + str(i))
        optimizer = tf.train.AdamOptimizer(learning_rate=1e-6)
<<<<<<< HEAD
        opA = optimizer.minimize(loss_A,global_step=global_step_tensor, var_list=vars_encoder)
=======
        opB = optimizer.minimize(loss_B,global_step=global_step_tensor)
>>>>>>> 7952acaa234ba84ddc616cc82e9b3560c88ae96c
        
    with K_B.get_session() as sess:
Ejemplo n.º 35
0
 def draw(self, width=8):
     color = self.suit.color
     text = '{:>2}{:<2} '.format(self.rank.c, self.suit.filled_symbol)
     return colorize(text.rjust(width), fg=color, bg='white', var='und', bgalt=True)
Ejemplo n.º 36
0
    def body(cls):
        d = {}
        d['example'] = colorize(r"""\relative c'' {
  \time 7/4
  c2 bes4 a2 g a bes4 a( g) f2
}
\addlyrics {
  Join us now and share the soft -- ware!
}""")
        import engrave
        ac = engrave.Engraver.instances()[0].actionCollection
        d['key_engrave'] = shortcut(ac.engrave_preview)
        import panelmanager
        ac = panelmanager.PanelManager.instances()[0].musicview.actionCollection
        d['key_jump'] = shortcut(ac.music_jump_to_cursor)
        d['key_copy_image'] = shortcut(ac.music_copy_image)
        ac = panelmanager.PanelManager.instances()[0].logtool.actionCollection
        d['key_error'] = shortcut(ac.log_next_error)
        d['menu_engrave'] = menu(_("LilyPond"), _("Engrave (publish)"))
        d['menu_preferences_lilypond'] = menu(
            _("menu title", "Edit"),
            _("Preferences"),
            _("LilyPond Preferences"))
        d['menu_clear_error_marks'] = menu(
            _("menu title", "View"),
            _("Clear Error Marks"))
        d['menu_copy_image'] = menu(
            _("menu title", "Edit"),
            _("Copy to Image..."))
        return _("""\
<p>
The default screen of Frescobaldi shows a text document on the left and an
empty Music View window on the right.
</p>

<p>
Now, in the text view, enter some LilyPond code, like this:
</p>

{example}

<p>
Then click the Lily toolbar button or press {key_engrave}.
LilyPond will start to processes your file and the PDF will be displayed 
in the Music View on the right. If LilyPond encounters any errors or 
warnings they will be displayed in the LilyPond Log at the bottom of the screen.
</p>

<p><img src="getting_started1.png"></p>

<p>
The Music View has many possibilities:
<p>

<ul>
<li>
Hovering over notes and other music objects will highlight them in the text
on the left window; clicking on them will place a cursor to the left of the
object also in the left window.
</li>

<li>
Use the Ctrl key and your mouse wheel to zoom in and out. Zooming will center 
around the mouse pointer.
</li>

<li>
Ctrl-left-click-and-hold the mouse to magnify a small section of the Music View
without zooming in the whole view.
</li>

<li>
Selecting text in the main text window will highlight corresponding notes in the 
Music View; press {key_jump} to explicitly center and highlight a note or other objects
in the Music View.
</li>

<li>
Shift-drag a selection and then press {key_copy_image} or {menu_copy_image}
to copy the selected music as a raster image to the clipboard, a file or
another application.
</li>
</ul>

<p>
When your music score is complete, run LilyPond once more but with
clickable notes turned off: menu {menu_engrave}. This significantly
reduces the size of the PDF.
</p>

<p>
If LilyPond does not start at all, check if you have installed LilyPond
correctly and that the lilypond command is in your system's PATH environment
variable. If needed, provide the exact path to your LilyPond executable under
{menu_preferences_lilypond}.
</p>

<p>
If LilyPond encounters any warnings or errors in your document they will show up in the 
LilyPond Log window at the bottom of the screen. Frescobaldi will then highlight 
these lines in the text view where the errors are. Clicking the error in 
the Log Window or pressing {key_error} immediately brings the text cursor to the 
offending line in your text view. Pressing {key_error} again will move to the 
next error message, and so on. LilyPond will remove any previous error line 
highlights the next time it is run but you can also remove any error line markings 
manually with the option {menu_clear_error_marks}.
</p>
""").format(**d)
Ejemplo n.º 37
0
def call_and_print(cmd, color='green'):
    print colorize(cmd, color, bold=True)
    subprocess.check_call(cmd, shell=True)
Ejemplo n.º 38
0
def ColorTable(xlabels, ylabels, data, savename = None,
               labelfontsize = 18, labelrotation = 45, textsize = 18,
               spacing = 0.025, colormap = "Blues",
               fmt = "%.1f", title = None, cmin = None,
               cmax = None, xlabel = None, ylabel = None,
               xlabel_spacing = 0.00, ylabel_spacing = 0.00,
               nancolor = (0.0, 0.0, 0.0), nantext = "", titlefontsize = 20,
               data_pm = None):
    '''
    Creates a `matplotlib.pyplot` version of a simple 2D
    table, where the values in each cell are color coded
    for easy viewing.

    Parameters
    ----------
    xlabels : list or `numpy.array`
    ylabels : list or `numpy.array`
    data : `numpy.array`
    data_pm : list or tuple
        List or tuple of two `numpy.array`  e.g. ``[data_plus, data_minus]``, one
        array to display as the upper percentile and one array for the lower
        percentile.
    '''

    assert len(xlabels) == data.shape[0]
    assert len(ylabels) == data.shape[1]

    # Dimensions
    Nx = len(xlabels)
    Ny = len(ylabels)

    # Create vector from 2d data
    datav = data.reshape([-1])

    # Get colormap for data range
    vcolors, smap, cnorm = colorize(datav, cmap=colormap, vmin = cmin,
                                    vmax = cmax)

    # Create figure
    fig, ax = plt.subplots(Ny, Nx, figsize = (Nx,Ny))

    # Set title, optional
    if title is not None:
        ax[0, int(Nx/2)].set_title(title, fontsize = titlefontsize)

    # Adjust spacing
    plt.subplots_adjust(wspace=spacing, hspace=spacing)

    # Loop over grid cells
    for ix in range(Nx):
        for iy in range(Ny):

            # Remove all ticks
            ax[iy, ix].set_xticks([])
            ax[iy, ix].set_yticks([])

            # Set boxcolor by colormap
            boxcolor = smap.cmap(cnorm(data[ix, iy]))

            if np.isnan(data[ix, iy]):
                boxcolor = nancolor

            # Set the facecolor to boxcolor
            ax[iy, ix].set_facecolor(boxcolor)

            # Get RGB
            R = boxcolor[0] * 255
            G = boxcolor[1] * 255
            B = boxcolor[2] * 255

            # Calculate grey "brightness"
            grey = (R*0.299 + G*0.587 + B*0.114)

            # Set text color based on brightness
            if grey > 186:
                textcolor = "#000000"
            else:
                textcolor = "#ffffff"

            # Catch nans and infs
            if np.isfinite(data[ix, iy]):

                # Baseline text
                text = fmt %data[ix, iy]

                # Add percentile text if proided
                if data_pm is not None:
                    text += "$^{+%s}_{-%s}$" %(fmt %data_pm[0][ix,iy], fmt %data_pm[1][ix,iy])

                # Determine if greater/less than signs are needed
                if cmax is not None:
                    if data[ix, iy] > cmax:
                        text = r"$>$"+fmt %cmax
                if cmin is not None:
                    if data[ix, iy] < cmin:
                        text = r"$<$"+fmt %cmin

            else:

                # This is not a number. Use nantext
                text = nantext


            # Add text to plot
            ax[iy, ix].text(0.5, 0.5, text, ha="center", va="center",
                            bbox=dict(boxstyle="square", fc="w", ec="w", alpha=0.0),
                            color = textcolor)

            # Get rid of the axis frame
            for spine in ax[iy, ix].spines.values():
                spine.set_visible(False)

    # Loop over x
    for ix in range(Nx):
        # Set tick to be in middle
        ax[-1,ix].set_xticks([0.5])
        # Set tick label by user provided
        ax[-1,ix].set_xticklabels([xlabels[ix]], rotation = labelrotation, fontsize = labelfontsize, ha = "right")

    # Loop over y
    for iy in range(Ny):
        # Set tick to be in middle
        ax[iy,0].set_yticks([0.5])
        # Set tick label by user provided
        ax[iy,0].set_yticklabels([ylabels[iy]], rotation = labelrotation, fontsize = labelfontsize, ha = "right")

    # Set ylabel
    if ylabel is not None:
        fig.text(ylabel_spacing, 0.5, ylabel, ha = "left", va = "center",
            fontsize=mpl.rcParams['font.size'], zorder=10, rotation = 90,
            bbox=dict(boxstyle="square", fc="none", ec="none"))

    # Set xlabel
    if xlabel is not None:
        fig.text(0.5, xlabel_spacing, xlabel, ha = "center", va = "bottom",
                fontsize=mpl.rcParams['font.size'], zorder=10,
                bbox=dict(boxstyle="square", fc="none", ec="none"))

    # Save figure, optional
    if savename is not None:
        fig.savefig(savename, bbox_inches = "tight")

    return fig, ax
Ejemplo n.º 39
0
    def move(self, moves):
        movelist = self.parse_moves(moves)

        for fr, to in movelist:
            card = None

            if fr in self.mv_cols:
                move_from = self.columns[self.mv_cols.index(fr)]
            elif fr in self.mv_cells[:-2]: # the last ones are only for moving 'to'
                move_from = self.freecells.cells[self.mv_cells.index(fr)]
                card = move_from.top_card()
            elif fr in self.mv_found[:-2]: # the last ones are only for moving 'to' 'y', is only for moving to
                key = self.mv_found_order[self.mv_found.index(fr)]
                move_from = self.foundation[key]
                card = move_from.top_card()
            elif fr == 'z':
                pass
            else:
                raise FreecellInvalidMoveError("'{}' is not a move".format(fr))

            if to in self.mv_cols:
                move_to = self.columns[self.mv_cols.index(to)]
            elif to in self.mv_cells:
                if to in 'tg':
                    index = self.freecells.first_open()
                else:
                    index = self.mv_cells.index(to)
                card = move_from.top_card()
                move_to = self.freecells.cells[index]
            elif to in self.mv_found:
                if to in 'yh':
                    key = move_from.top_card().suit.c
                else:
                    key = self.mv_found_order[self.mv_found.index(to)]
                card = move_from.top_card()
                move_to = self.foundation[key]
            elif to == 'z':
                self.undo()
            else:
                raise FreecellInvalidMoveError("'{}' is not a move".format(to))

            success = False

            if card:
                try:
                    success = self.move_card(card, move_from, move_to)
                except:
                    import traceback
                    message = traceback.format_exc().splitlines()[-1]
                    print colorize(message, fg='red')
                    print colorize('move was {}{}'.format(fr,to), fg='cyan')
                    success = False
            elif to == 'z':
                success = True
            else:
                success = self.move_stack(move_from, move_to)

            if success:
                self.replay.append('{}{}'.format(fr, to))
                self.add_history()
            else:
                self.set_state(self.history[-1])
                return False

        return True