예제 #1
0
def do(str1, str2):
    if str1 is None:
        str1 = ""
    len1 = len(str1)
    len2 = len(str2)
    splited1 = list(str1)
    splited2 = list(str2)
    short = splited1 if len1 < len2 else splited2
    if len1 != len2:
        add = range(0,abs(len2-len1))
       
        for i in add:
            
            short += "_"
      
    zipped = zip(splited1, splited2)
    colorStr1 = colorStr2 = ''
    for (i, j) in zipped:
        
        
        
        iRepr = util.goodRepr(i)
        jRepr = util.goodRepr(j)
        if i == j:
            colorStr1 += color.color(iRepr, 'green')    
            colorStr2 += color.color(jRepr, 'green')    
        else:
            colorStr1 += color.color(iRepr, 'red')  
            colorStr2 += color.color(jRepr, 'yellow')   
    color.red('diff:')        
    print(colorStr1)        
    print(colorStr2)
예제 #2
0
파일: dither.py 프로젝트: zhester/hzpy
def generate_samples():
    """
    Generates the sample images for review.
    """

    # set image dimensions
    width  = 512
    height = 1024

    # set the base gradient start and stop colors
    start = color.color( 0x001620 )
    stop  = color.color( 0x08262A )

    # create the base gradient with noticeable "banding"
    make_image(
        'base.png',
        width,
        height,
        make_base( start, stop, width, height )
    )

    # create a gradient with some noise applied to it
    make_image(
        'noise.png',
        width,
        height,
        make_dith_noise( start, stop, width, height )
    )
예제 #3
0
def test():
    # generate a filename by time
    now = time.strftime("%Y%m%d%H%M%S", time.localtime())
    filename = now + '.jpg'
    
    # path config
    base_dir = os.path.join('static', 'pic')
    ori_path = os.path.join(base_dir, 'original', filename)
    prp_path = os.path.join(base_dir, 'preprocessed', filename)
    rst_path = os.path.join(base_dir, 'result', filename)

    # save the file
    f = request.files['file']
    f.save(ori_path)

    # preprocess
    myutils.img_prep(ori_path, prp_path)

    # color
    color.color(prp_path, rst_path)

    # return the URL
    ori_url = myutils.strip(ori_path)
    rst_url = myutils.strip(rst_path)
    return render_template('result.html', ori=ori_url, rst=rst_url)
예제 #4
0
파일: gamemap.py 프로젝트: kidaa/bttext
    def drawAll(self, dst):
        self.drawAllFlag = False
        for h in range(self.h):
            for  w in range(self.w):
                pos = (self.pos[0] + (self.w/2 - w),
                       self.pos[1] + (self.h/2 - h))
                if (pos[0] < 0) or (pos[1] < 0) or \
                   (pos[0] >= LEVEL_WIDTH) or \
                   (pos[1] >= LEVEL_HEIGHT):
                    continue

                if configs.misc.COLORED == True:
                    if tuple(pos) in self.foreground:
                        mapDraw = self.foreground[tuple(pos)]
                        dst.addstr(self.y + self.h - h,
                                   self.x + self.w - w,
                                   mapDraw[0],
                                   color.color(mapDraw[1], mapDraw[2]))
                        self.foreground.pop(pos)
                    elif tuple(pos) in self.persons:
                        mapDraw = self.persons[tuple(pos)].mapDraw
                        dst.addstr(self.y + self.h - h,
                                   self.x + self.w - w,
                                   mapDraw[0],
                                   color.color(mapDraw[1], mapDraw[2]))
                    else:
                        dst.addstr(self.y + self.h - h,
                                   self.x + self.w - w,
                                   self[pos]['ascii'],
                                   color.color(self[pos]['fg'],
                                   self[pos]['bg']))
                else:
                    dst.addstr(self.y + self.h - h,
                               self.x + self.w - w,
                               self[pos]['ascii'])
예제 #5
0
    def connect_to_contacts(self, link_name, contact_list=[]):
        rx, tx = sub, pub = 0, 1
        #print "will connect to contact list: ", contact_list
        for contact in contact_list:
            if contact not in self.this_contact.contact_list:
                for ip in contact['ip-list']:
                    conn_str = "%s:%d:%d" % (ip, contact['ports'][rx],
                                             contact['ports'][tx])
                    print_msg = ("%s\t%d %d\tvia %s" %
                                 (ip, contact['ports'][rx],
                                  contact['ports'][tx], link_name))
                    print_msg = color.color(print_msg, fg_light_green=True)
                    print color.color("connecting to\t",
                                      fg_green=True) + print_msg
                    rx_addr = "tcp://%s:%d" % (ip, contact['ports'][rx])
                    tx_addr = "tcp://%s:%d" % (ip, contact['ports'][tx])
                    self.link[link_name].pub.connect(rx_addr)
                    self.link[link_name].sub.connect(tx_addr)
                    self.connection_list.append(conn_str)

                    #print "full connection list: ", self.connection_list
            else:
                m = "not connecting to itself: " + display_contact(contact)
                print color.color(m, fg_orange=True)
                pass
예제 #6
0
파일: __main__.py 프로젝트: tslight/cjson
def cjson(screen, path):
    curses.curs_set(0)
    color()
    header(screen)
    footer(screen)
    div, txt = body(screen)
    data = get_json(path)
    eventloop(screen, div, txt, data)
예제 #7
0
def main():
    for line in sys.stdin:
        if line.startswith('+'):
            sys.stdout.write(color(line, YELLOW))
        elif line.startswith('-'):
            sys.stdout.write(color(line, GRAY, bg=0))
        else:
            sys.stdout.write(line)
예제 #8
0
파일: VKBotLib.py 프로젝트: jag-k/VKBot
def print_message_info(message):
    print_log(color(message['symbol'] + '  ' + name(message['rid'], full=True), 34 if message['out'] else 32) +
              "%s:" % ('' if message['rid'] in users_list() else ' (\x1b[31mnot in user_list\x1b[0m)'),
              message['body'], print_log=False)
    print_log('   ', color(message['type'].title(), 32) + ':',
              color(name(message['pid']), 36), print_log=False)
    print_log(print_log=False)
    print_log(message, print_stdout=False)
예제 #9
0
파일: tracking.py 프로젝트: ComSciCtr/vroom
   def draw(self):
      for obj in self.tracked_objects:
         if hasattr(obj, 'active'):
            color(red)
         else:
            color(0.25)

         pushMatrix()
         translate(obj.origin)
         obj.region.draw()
         popMatrix()
예제 #10
0
 def str(self, colored = True):
     'Displays the card as text'
     # For Windows, "colored" is deprecated and set always to be False
     sysName = system() # obtain the OS's name
     colored &= sysName != 'Windows'
     mnToStr = lambda mnTuple, indexOfSuites: \
         'Undefined card' if mnTuple[0] < 0 or mnTuple[1] < 0 else \
         card.__suites[indexOfSuites][mnTuple[0]] + card.__numbers[mnTuple[1]]
     #####################################################################################
     # the current decision is that if windows, output SHCD and otherwise output unicode #
     #####################################################################################
     return ((color() if self.getMN()[0] % 2 == 0 else color('red')).text \
         if colored else (lambda x: x))(mnToStr(self.getMN(), 'Windows' == sysName))
예제 #11
0
    def LoadPreSetColors(self):

        with open('basecolors.txt', 'r') as txtfile:

            for line in txtfile:

                 line = line.strip() 

                 if line:

                        Name, LeftAngle, RightAngle = line.split(" ")

                        color(Name, int(LeftAngle), int(RightAngle))
예제 #12
0
    def test_testName(self):
        color.blue("test here baby")

        result = filer2.read(os.path.join(currentFolder, '../../find_usages_plugin.py'))

        indexes = range(638)


        for i in indexes:
            # color.red(str(i)+result[i])
            number = color.color(str(i), "red")
            char = color.color(repr(result[i]), "green")
            line = "{0} - {1}".format(number, char)
            print(line)
예제 #13
0
    def find(self, target):
        target = target.strip()
        if ( len(target) == 0 ): return False

        res = []
        col_obj = color()
        ldd_obj = ldd(self.gdb, self.f_path)
        libc = ldd_obj.get_libc()

        cmd = 'strings -at x {} | grep "{}"'.format(libc, target)
        try:
            r = subprocess.check_output(cmd, shell = True)
        except: return False
        r = r.decode('utf-8').strip().split('\n')
        

        for i in r:
            i = i.strip()
            tmp = i.split(' ')
            ofst = '0x{}'.format(tmp[0])
            name = []

            for j in range(1, len(tmp)):
                if ( len(tmp[j].strip()) != 0 ): name.append(tmp[j].strip())

            name = ' '.join(name)
            # highlight the key word
            name = name.replace(target, '{}{}{}'.format(col_obj.l_red, target, col_obj.dft))

            tmp = 'offset: {}name: {}'.format(ofst.ljust(11, ' '), name)
            res.append(tmp)

        return res
예제 #14
0
def dimensionality_reduction(data, n_dim=None, thold=0.9, method="PCA", help_me=False, **arg_d):
    """Dimensionality reduction

    Parameters
    ==========
    data:    n_samples x n_features
    n_dim:   n-dimension
    thold:   Float, threshold
    method:  String, decomposition method
             {"主成分分析":   ["PCA", "IncrementalPCA", "KernelPCA",
                               "MiniBatchSparsePCA", "SparsePCA",
                               "TruncatedSVD"],
              "因子分析":     ["FactorAnalysis"],
              "独立成分分析": ["FastICA"],
              "字典学习":     ["DictionaryLearning",
                               "MiniBatchDictionaryLearning"],
              "高级矩阵分解": ["LatentDirichletAllocation", "NMF"],
              "其他矩阵分解": ["SparseCoder"]}
    help_me: Boolean
    arg_d:   Dict[args of sklearn.decomposition.?]
             Dict{name:value}

    Return
    ======
    decomodel: decomposition model
    data_:     data after transform

    Examples
    ========
    >>> dec,data_ = dimensionality_reduction(data, thold=0.9, method="PCA"):

    Reference
    =========
    - [Zhihu](https://zhuanlan.zhihu.com/p/59591749)
    - [Oreilly](https://www.oreilly.com/learning/an-illustrated-introduction-to-the-t-sne-algorithm)
    - [Scikit](http://lijiancheng0614.github.io/scikit-learn/modules/generated/sklearn.decomposition.PCA.html)
    """
    methods = ["DictionaryLearning", "FactorAnalysis", "FastICA",
               "IncrementalPCA", "KernelPCA", "LatentDirichletAllocation",
               "MiniBatchDictionaryLearning", "MiniBatchSparsePCA", "NMF",
               "PCA", "SparseCoder", "SparsePCA", "TruncatedSVD"]
    if method not in methods:
        raise NameError("Method %s not in sklearn.decomposition"%color(method))
    alias = getattr(decomposition, method)
    if n_dim is not None:
        decomodel = alias(n_components=n_dim, **arg_d)
        decomodel.fit(data)
        return decomodel, decomodel.transform(data)
    elif thold is not None:
        decomodel = alias(**arg_d)
        decomodel.fit(data)
        if "explained_variance_ratio_" in dir(decomodel):
            ratio = decomodel.explained_variance_ratio_
            index = np.sum(np.cumsum(ratio) < thold)
            decomodel.components_ = decomodel.components_[:index]
        else:
            raise NotImplementedError("TODO")
        return decomodel, decomodel.transform(data)
    else:
        raise ValueError("There must be at most two None in n_dim and thold.")
예제 #15
0
파일: relf.py 프로젝트: sheng9571/ctf_tools
    def invoke(self, arg, tty):
        try:
            if ( len(arg.strip()) == 0 ): raise Exception('please give one argument!')

            if (not self.init()):
                raise Exception('process is not running!')
            else:
                pid, f_path = self.init()


            ldd_obj = ldd(gdb, f_path)
            libc = ldd_obj.get_libc()
            del ldd_obj
            if (len(libc.strip()) == 0): raise Exception('could not get libc path!')

            
            cmd = 'readelf -a {} | grep "{}"'.format(libc.strip(), arg.strip())
            r = subprocess.check_output(cmd, shell = True)
            r = r.decode('utf-8').strip().split('\n')

            col_obj = color()
            res = []
            res_1 = []

            for i in r:
                tmp = []
                for j in i.strip().split(' '):
                    if(len(j.strip()) != 0): tmp.append(j)

                res.append(tmp)
                
            for i in res:
                tmp = []
                if ( len(i) == 7 ):
                    # ex: stdout
                    # 0000003c3f50  041300000006 R_X86_64_GLOB_DAT 00000000003c5708 stdout@@GLIBC_2.2.5 + 0
                    # offset
                    tmp.append(hex(int(i[3].strip(), 16)))
                    name = []
                    # name
                    for j in range(4, len(i)): name.append(i[j].strip())
                    tmp.append(' '.join(name))
                    res_1.append(tmp)
                elif ( len(i) == 8 ):
                    # 803: 00000000003c5620   224 OBJECT  GLOBAL DEFAULT   33 _IO_2_1_stdout_@@GLIBC_2.2.5
                    # offset
                    tmp.append(hex(int(i[1].strip(), 16)))
                    # name
                    tmp.append(i[7].strip())
                    res_1.append(tmp)


            res = []
            for i in res_1:
                res.append('offset: {}name: {}'.format(i[0].ljust(15, ' '), i[1].replace(arg, '{}{}{}'.format(col_obj.l_red, arg, col_obj.dft))))


            for i in res: print(i)

        except Exception as e:  print('Error Occurred: {}'.format(str(e)))
예제 #16
0
파일: frame.py 프로젝트: olpa/tex
    def setType(self, type):

        #Delete old panels
        for i in self.GetChildren():
            if i.GetName() in ["imagePanel", "customPanel", "colorPanel", "rotationPanel", "textPanel", "vartextPanel"]:
                i.Destroy()

        if type == "color":
            self.color = color(self)
            self.customSizer.Add(self.color, 1, wx.EXPAND|wx.ALL, 4)
        if type == "image":
            self.image = image(self)
            self.customSizer.Add(self.image, 1, wx.EXPAND|wx.ALL, 4)
        if type == "text":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND|wx.ALL, 4)
            self.text = text(self)
            self.customSizer.Add(self.text, 1, wx.EXPAND|wx.ALL, 4)
        if type == "vartext":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND|wx.ALL, 4)
            self.vartext = vartext(self)
            self.customSizer.Add(self.vartext, 1, wx.EXPAND|wx.ALL, 4)

        self.SetSizerAndFit(self.sizer)

        self.Layout()
        self.parent.Layout()
        self.parent.propertiesPanel.Layout()
예제 #17
0
def validaColor(pos_ini):
    x = pos_ini[0]
    y = pos_ini[1]
    color = [0,0]
    
    if x > 0 and x <= 35 and y > 245 and y <= 280:
        color[0] = Amarillo
    if x > 0 and x <= 35 and y > 280 and y <= 315:
        color[0] = Azul  
    if x > 0 and x <= 35 and y > 315 and y <= 350:
        color[0] = Rojo 
    if x > 0 and x <= 35 and y > 350 and y <= 385:
        color[0] = Verde
    if x > 0 and x <= 35 and y > 385 and y <= 420:
        color[0] = Naranja
    if x > 0 and x <= 35 and y > 420 and y <= 455:
        color[0] = Negro
    if x > 0 and x <= 35 and y > 455 and y <= 490:
        color[0] = Cafe
    if x > 0 and x <= 35 and y > 490 and y <= 525:
        color[0] = Rosa
    if x > 0 and x <= 35 and y > 525 and y <= 560:
        color[0] = Morado
    if x > 0 and x <= 35 and y > 560 and y <= 595:
        color = cl.color()

    return color[0]
예제 #18
0
def print_hangman():
    with open(f'assets/lives/{lives}.txt') as f:
        hangman = f.readlines()

    for line in hangman:
        line = line.replace('\n', '')
        print(color(line))
예제 #19
0
  def cast_ray(self, orig, direction):
    material, intersect = self.scene_intersect(orig, direction)

    if material is None:
      return self.background_color

    light_dir = norm(sub(self.light.position, intersect.point))
    light_distance = length(sub(self.light.position, intersect.point))

    offset_normal = mul(intersect.normal, 1.1)  # avoids intercept with itself
    shadow_orig = sub(intersect.point, offset_normal) if dot(light_dir, intersect.normal) < 0 else sum(intersect.point, offset_normal)
    shadow_material, shadow_intersect = self.scene_intersect(shadow_orig, light_dir)
    shadow_intensity = 0

    if shadow_material and length(sub(shadow_intersect.point, shadow_orig)) < light_distance:
      shadow_intensity = 0.9

    intensity = self.light.intensity * max(0, dot(light_dir, intersect.normal)) * (1 - shadow_intensity)

    reflection = reflect(light_dir, intersect.normal)
    specular_intensity = self.light.intensity * (
      max(0, -dot(reflection, direction))**material.spec
    )

    diffuse = material.diffuse * intensity * material.albedo[0]
    specular = color(255, 255, 255) * specular_intensity * material.albedo[1]
    return diffuse + specular
예제 #20
0
    def invoke(self, arg, tty):
        try:
            if (not self.init()):
                raise Exception('process is not running!')
            else:
                pid, f_path = self.init()

            f_info = file_info(f_path)
            arch = f_info.get_arch()
            bit = f_info.get_bit()
            del f_info

            l_map = linux_map(bit)
            l_map = l_map.parse(pid)

            col_obj = color()

            libc_base, libc_text_idx = self.get_libc_base(l_map, bit)
            if (len(libc_base.strip()) == 0):
                raise Exception('could not get libc path!')
            del l_map

            libc = ldd(gdb, f_path).get_libc()

            print('libc: {}{}{}'.format(col_obj.purple, libc, col_obj.dft))
            print('libc base: {}{}{}'.format(col_obj.purple, libc_base,
                                             col_obj.dft))

        except Exception as e:
            print('Error Occurred: {}'.format(str(e)))
예제 #21
0
    def invoke(self, arg, tty):
        try:
            if (len(arg.strip()) == 0):
                raise Exception('please give a .so file name with it\'s path')
            col_obj = color()

            cmd = 'set environment LD_PRELOAD'
            gdb.execute(cmd, to_string=True)
            print('Set environment variable "LD_PRELOAD" to null!')

            cmd = 'set environment LD_PRELOAD {}'.format(arg)
            gdb.execute(cmd, to_string=True)

            cmd = 'show environment LD_PRELOAD'
            r = gdb.execute(cmd, to_string=True)
            r = r.strip().split(' = ')

            if (len(r) != 2):
                raise Exception(
                    'Set environment variable "LD_PRELOAD" {}failed{}!'.format(
                        col_obj.red, col_obj.dft))

            print(
                'Set environment variable "LD_PRELOAD" to {}{}{} {}success{}!'.
                format(col_obj.l_blue, r[1].strip(), col_obj.dft,
                       col_obj.green, col_obj.dft))

        except Exception as e:
            print('Error Occurred: {}'.format(str(e)))
예제 #22
0
def compute_or_fecth_pickle(imgPath, nbResize=0, printImg=True, circleSize=5):
    img = cv2.imread(imgPath, 1)
    for i in range(nbResize):
        img = cv2.resize(img, dsize=(0, 0), fx=0.5, fy=0.5)

    print_images([img], name='baseImg')

    myImg = img.copy()
    imgGray = myImg[:, :, 1]


    myDesc, myKps = None, None
    if pickleExist(imgPath):
        print("Using pre-computed key-points")
        myDesc, myKps = loadPickle(imgPath)
    else:
        print("No precomputed key-points. Start computing key-points")
        myDesc, myKps = doSift(imgGray)
        savePickle(payloadKps(myDesc, myKps), imgPath)

    myFinalImg = img.copy()

    if printImg:
        for kp in myKps:
            y, x = kp[0], kp[1]
            cv2.circle(myFinalImg, (x, y), circleSize, color('lb'), thickness=-1)
        print_image(myFinalImg, name='KP kept')

    return img, myDesc, myKps, myFinalImg
예제 #23
0
    def setType(self, type):

        #Delete old panels
        for i in self.GetChildren():
            if i.GetName() in [
                    "imagePanel", "customPanel", "colorPanel", "rotationPanel",
                    "textPanel", "vartextPanel"
            ]:
                i.Destroy()

        if type == "color":
            self.color = color(self)
            self.customSizer.Add(self.color, 1, wx.EXPAND | wx.ALL, 4)
        if type == "image":
            self.image = image(self)
            self.customSizer.Add(self.image, 1, wx.EXPAND | wx.ALL, 4)
        if type == "text":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND | wx.ALL, 4)
            self.text = text(self)
            self.customSizer.Add(self.text, 1, wx.EXPAND | wx.ALL, 4)
        if type == "vartext":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND | wx.ALL, 4)
            self.vartext = vartext(self)
            self.customSizer.Add(self.vartext, 1, wx.EXPAND | wx.ALL, 4)

        self.SetSizerAndFit(self.sizer)

        self.Layout()
        self.parent.Layout()
        self.parent.propertiesPanel.Layout()
예제 #24
0
 def __init__(self, width, height):
   self.width = width
   self.height = height
   self.background_color = color(0, 0, 0)
   self.scene = []
   self.light = None
   self.clear()
예제 #25
0
def cycle(key, key2color, bg, text=None):
    if text is None:
        text = key
    col = key2color.get(key)
    if not col:
        col = COLORS[len(key2color) % len(COLORS)]
        key2color[key] = col
    return color(text, col, bg=bg)
예제 #26
0
def main():
    nbResize = 0
    circleSize = 5 // (nbResize + 1)
    if len(sys.argv) > 1:
        imgPath = sys.argv[1]
    else:
        imgPath = chooseImagePath()
    if len(sys.argv) > 2:
        imgPathRef = sys.argv[2]
    else:
        imgPathRef = chooseImagePathRef()
    # for imgPath in listOfPaths():
    #     try:
    #         print('>>>>>>>>>>>>>>>', imgPath)
    #         img, myDesc, myKps, myFinalImg = compute_or_fecth_pickle(imgPath, nbResize=nbResize, circleSize=circleSize, printImg=False)
    #     except:
    #         print('######### FAILED FOR', imgPath)
    #         continue

    print('>>>>>>>> Start Computing key-points for tested Image')
    img, myDesc, myKps, myFinalImg = compute_or_fecth_pickle(imgPath, nbResize=nbResize, circleSize=circleSize,
                                                             printImg=False)
    print('>>>>>>>> Start Computing key-points for ref Image')
    imgRef, refDesc, refKps, myFinalImgRef = compute_or_fecth_pickle(imgPathRef, printImg=False)

    commonPoints = doKDtree(refDesc, myDesc)
    print('match', len(commonPoints), 'on', len(refDesc), 'proportion', len(commonPoints) / len(refDesc))

    # printing kps that matched
    refKps, imgKps = [], []
    for cp in commonPoints:
        sKp = cp[0][1]
        pKp = cp[0][0]

        y, x = sKp
        y2, x2 = pKp
        imgKps.append(Point(x2, y2))
        refKps.append(Point(x, y))

        cv2.circle(myFinalImg, (x, y), 5, color('g'), thickness=-1)
        cv2.circle(myFinalImgRef, (x2, y2), 5, color('g'), thickness=-1)

    myPrintKeyDiff(img, imgRef, imgKps, refKps)

    # tryOCVSift(img, imgRef, myFinalImg)
    return
예제 #27
0
 def read_pattern(self, pattern: str):
     '''Save the pattern in matrix'''
     row_list = pattern.split("\n")
     c = self.color
     bold = self.bold
     for m in range(len(row_list)):
         for n in range(len(row_list[m])):
             self.matrix[m][n] = color(row_list[m][n], color=c, bold=bold)
예제 #28
0
def debug(locals_=None):
    for k, v in locals_.items():
        locals()[k] = v
    print("\n\n\n")
    hint = "`Enter` if not debug: "
    if input(color(hint, "蓝")):
        del k, v, locals_, hint
        embed(colors="Neutral")
예제 #29
0
def findCorners(img,
                kpList,
                thresh=10000,
                opti_r=5,
                k=0.05,
                window_size=5,
                printCorner=False):
    dy, dx = np.gradient(img)
    Ixx = dx**2
    Ixy = dy * dx
    Iyy = dy**2
    height = img.shape[0]
    width = img.shape[1]
    cornerList = []
    offsetX, offsetY = window_size, window_size
    img2 = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    # Loop through image and find our corners
    for y, x in kpList:
        if not (x > window_size and x + 1 < width - window_size
                and y > window_size and y + 1 < height - window_size):
            continue
        windowIxx = Ixx[y - offsetY:y + offsetY + 1,
                        x - offsetX:x + offsetX + 1]
        windowIxy = Ixy[y - offsetY:y + offsetY + 1,
                        x - offsetX:x + offsetX + 1]
        windowIyy = Iyy[y - offsetY:y + offsetY + 1,
                        x - offsetX:x + offsetX + 1]
        Sxx = windowIxx.sum()
        Sxy = windowIxy.sum()
        Syy = windowIyy.sum()
        # Find determinant and trace, use to get corner response
        det = (Sxx * Syy) - (Sxy**2)
        trace = Sxx + Syy
        r = det - k * (trace**2)
        # If corner response is over threshold, color the point and add to corner list

        if r > thresh:
            # print('Corner!', x, y, r, opti_r)
            cornerList.append([y, x])
            cv2.circle(img2, (x, y), 3, color('g'), thickness=-1)
        else:
            # print('Not corner :(', x, y, r)
            cv2.circle(img2, (x, y), 3, color('r'), thickness=-1)
    if printCorner:
        print_image(img2, name='Harris')
    return cornerList
예제 #30
0
def sendToClientFromID(clientId, msg):
    """ Internal use only """
    assert isString(msg)
    msg = color.color(msg + "{@")
    if clientId in clientMsgs:
        clientMsgs[clientId] = clientMsgs[clientId] + msg
    else:
        clientMsgs[clientId] = msg
예제 #31
0
def calc_accuracy(y_true, y_predict, display=True):
    """Analysis the score with sklearn.metrics.
    This module includes score functions, performance metrics
    and pairwise metrics and distance computations.

    Parameters
    ==========
    y_true:    numpy.array
    y_predict: numpy.array
    display:   Boolean

    Return
    ======
    result: Dict{name:value}

    Examples
    ========
    >>> result = analysis(y_true, y_predict, display=True)
    """
    score  = ["explained_variance_score", "r2_score"]
    error  = ["max_error", "mean_absolute_error", "mean_squared_error",
              "mean_squared_log_error", "median_absolute_error"]
    result = dict()
    names  = ["score", "error"]
    ignore = []
    for name in names:
        result[name] = dict()
        for item in locals()[name]:
            try:
                result[name][item] = getattr(metrics, item)(y_true, y_predict)
            except Exception as e:
                print(color(("↓ %s has been removed since `%s`." % \
                    (item.capitalize(), e))))
                ignore.append(item)
    if display:
        tabu,numerical = None, None
        for name in names:
            tabu = PrettyTable(["Name of %s"%color(name), "Value"])
            for item in locals()[name]:
                if item in ignore:
                    continue
                numerical = "%.3e" % result[name][item]
                tabu.add_row([color(item,"青"), numerical])
            print(tabu)
    return result
예제 #32
0
 def render(self,stereogram=False):
   fov = int(pi/2)
   for y in range(self.height):
     for x in range(self.width):
       i =  (2*(x + 0.5)/self.width - 1) * tan(fov/2) * self.width/self.height
       j =  (2*(y + 0.5)/self.height - 1) * tan(fov/2)
       direction = norm(V3(i, j, -1))
       if(stereogram):
         eye1 = self.cast_ray(V3(0.4,0,0), direction)
         eye2 = self.cast_ray(V3(-0.4,0,0), direction)
         if not eye1.equals(self.background_color):
           eye1 = eye1*0.57 + color(100,0,0)                                          #times 0.57 for it to not exceed 255 
         if not eye2.equals(self.background_color):
           eye2 = eye2*0.57 + color(0,0,100)                                          #times 0.57 for it to not exceed 255  
         eye_sum = eye1 + eye2
         self.pixels[y][x] = eye_sum
       else:
         self.pixels[y][x] = self.cast_ray(V3(1,0,0), direction)
예제 #33
0
 def init_sky(self, symbol=" ") -> list:
     '''生成sky的二维矩阵,将sky所有位置赋值=symbol'''
     matrix = []
     edge = self.edge
     for i in range(self.height * edge):
         row = []
         for j in range(self.width * edge):
             row.append(color(symbol))
         matrix.append(row)
     return matrix
예제 #34
0
def cutUpperBody(img, upperHexCode):
    img_h = img.shape[0]
    img_w = img.shape[1]
    cutToUpper = img[int((img_h / 10) * 1):int((img_h / 10) * 6), :img_w]
    # global upperHexCode
    find = color(upperHexCode, cutToUpper)
    if not find:
        return int(0), ""
    # print("Upper True")
    return int(1), cutToUpper
예제 #35
0
 def show_cell(self):
     '''Print the final appearence of cell'''
     matrix = self.matrix
     c = self.color
     bold = self.bold
     for row in matrix:
         line = ""
         for bit in row:
             line += color(bit, color=c, bold=bold)
         print(line)
예제 #36
0
    def SaveColor(self, instance):

        self.ColorInstance = color(self.ColorArray[0], int(self.ColorArray[1]), int(self.ColorArray[2]))

        self.SetTextInputToRead()

        self.remove_widget(self.SaveColorButton)
        self.remove_widget(self.Placeholder)
        
        self.add_widget(self.RemoveColorButton)
        self.add_widget(self.VisualizeColorButton)
예제 #37
0
def generate_samples():
    """
    Generates the sample images for review.
    """

    # set image dimensions
    width = 512
    height = 1024

    # set the base gradient start and stop colors
    start = color.color(0x001620)
    stop = color.color(0x08262A)

    # create the base gradient with noticeable "banding"
    make_image('base.png', width, height, make_base(start, stop, width,
                                                    height))

    # create a gradient with some noise applied to it
    make_image('noise.png', width, height,
               make_dith_noise(start, stop, width, height))
	def test_testNameWithColors(self):
		color.blue("test here baby")
		
		inputText = color.color(repr('\n'), 'green')
		
		result = util.replaceLastAndFirstQuotes(inputText)		

		color.red('inputText')
		print(inputText)

		color.red('result')
		print(result)
예제 #39
0
파일: prompt.py 프로젝트: jjjj222/setup
def get_prompt(prompt):
    o = StringIO()

    try:
        frame = str(gdb.selected_frame().name())
        frame = reduce_frame_str(frame)
    except:
        frame = "<no frame>"

    o.write(color('blue'))
    o.write("[")
    o.write(color('cyan'))
    o.write(frame)
    o.write(color('blue'))
    o.write("] ")
    o.write(color('green'))
    o.write("(gdb)")
    o.write(color("end"))
    o.write(" ")

    gdb.execute("vimtracealign")
    return gdb.prompt.substitute_prompt(o.getvalue())
예제 #40
0
    def connect_to_contacts(self, link_name, contact_list=[]):
        rx, tx = sub, pub = 0, 1
        #print "will connect to contact list: ", contact_list
        for contact in contact_list:
            if contact not in self.this_contact.contact_list:
                for ip in contact['ip-list']:
                    conn_str = "%s:%d:%d" % (ip, contact['ports'][rx], contact['ports'][tx])
                    print_msg = ("%s\t%d %d\tvia %s" %
                          (ip, contact['ports'][rx], contact['ports'][tx], link_name))
                    print_msg = color.color(print_msg, fg_light_green=True)
                    print color.color("connecting to\t", fg_green=True) + print_msg
                    rx_addr = "tcp://%s:%d" % (ip, contact['ports'][rx])
                    tx_addr = "tcp://%s:%d" % (ip, contact['ports'][tx])
                    self.link[link_name].pub.connect(rx_addr)
                    self.link[link_name].sub.connect(tx_addr)
                    self.connection_list.append(conn_str)

                    #print "full connection list: ", self.connection_list
            else:
                m = "not connecting to itself: " + display_contact(contact)
                print color.color(m, fg_orange=True)
                pass
예제 #41
0
파일: gamemap.py 프로젝트: kidaa/bttext
    def draw(self, dst):
        newList = list()
        if self.drawAllFlag == True:
            self.drawAll(dst)
        else:
            for elem in self.drawPos:
                pos = (elem[0], elem[1])

                if (pos[0] < 0) or (pos[1] < 0) or \
                   (pos[0] >= LEVEL_WIDTH) or \
                   (pos[1] >= LEVEL_HEIGHT):
                    continue

                screenpos = self.to_screenpos(pos[0], pos[1])
                if configs.misc.COLORED == True:
                    if tuple(pos) in self.foreground:
                        mapDraw = self.foreground[tuple(pos)]
                        dst.addstr(screenpos[1], screenpos[0],
                                   mapDraw[0],
                                   color.color(mapDraw[1], mapDraw[2]))
                        self.foreground.pop(pos)
                        newList.append(pos)
                    elif tuple(pos) in self.persons:
                        mapDraw = self.persons[tuple(pos)].mapDraw
                        dst.addstr(screenpos[1], screenpos[0],
                                   mapDraw[0],
                                   color.color(mapDraw[1], mapDraw[2]))
                    else:
                        dst.addstr(screenpos[1], screenpos[0],
                                   self[pos]['ascii'],
                                   color.color(self[pos]['fg'],
                                   self[pos]['bg']))
                else:
                    dst.addstr(screenpos[1], screenpos[0], self[pos]['ascii'])


            self.drawPos = newList
예제 #42
0
파일: person.py 프로젝트: kidaa/bttext
    def draw(self, dst):
        pos = [self.gMap.x + self.gMap.w/2 + self.pos[0] - self.gMap.pos[0] + self.gMap.w%2,#xa,
               self.gMap.y + self.gMap.h/2 + self.pos[1] - self.gMap.pos[1] + self.gMap.h%2]#ya]

        if (pos[0] >= self.gMap.x) & \
           (pos[1] >= self.gMap.y) & \
           (pos[0] <= (self.gMap.x + self.gMap.w)) & \
           (pos[1] <= (self.gMap.y + self.gMap.h)):

            if configs.misc.COLORED == True:
                dst.addstr(pos[1], pos[0], self.mapDraw[0],
                           color.color(self.mapDraw[1],
                                       self.mapDraw[2]))
            else:
                dst.addstr(pos[1], pos[0], self.mapDraw[0])
예제 #43
0
파일: gamemap.py 프로젝트: kidaa/bttext
    def drawAll(self, dst):
        self.drawAllFlag = False
        for h in range(self.h):
            for  w in range(self.w):
                pos = (self.pos[0] + (self.w/2 - w),
                       self.pos[1] + (self.h/2 - h))
                if (pos[0] < 0) or (pos[1] < 0) or \
                   (pos[0] >= LEVEL_WIDTH) or \
                   (pos[1] >= LEVEL_HEIGHT):
                    continue

                if configs.misc.COLORED == True:
                    dst.addstr(self.y + self.h - h,
                               self.x + self.w - w,
                               '+', color.color(7, 0))
                else:
                    dst.addstr(self.y + self.h - h,
                               self.x + self.w - w,
                               '+')
예제 #44
0
파일: ipVar.py 프로젝트: niyaa/paper
def nsFile(path):
    os.chdir(path)
    col=color.color();
    cwd=path;
    p1=glob("*/");
    aa=[];bb=[];cc=[];dd=[];ee=[];
    for i in p1:
        try:
            [a,b]=poptFile(cwd+'/'+i);
        except:
            os.chdir(cwd);
            continue;
        try:
            c=funcs.calcReC(a,b);
            if(c>0):
                bb.append(c);
                aa.append(float(i.split('/')[0]));  
        except:
            args='The Critical Reynolds can not be found for '+i;
            print col.YELLOW + args+ col.END;
            cc.append(float(i.split('/')[0]));
            dd.append(a);
            ee.append(b);
            continue;
        os.chdir(cwd);

    l2, l1 = zip(*sorted(zip(aa, bb)));
    l2=list(l2);l1=list(l1);
    c=(l2,l1)
    c=np.asarray(c);
    sVal=cwd.split('/')[-1];
    alpha=cwd.split('/')[-2];
    np.savetxt('ns-'+sVal+'-'+alpha+'-.txt',c.T);
    print(col.DARKCYAN+'The Critical Reynolds can not be found for '+str(cc)+col.END);

    print(col.CYAN+'The corresponding growth rates \t'+col.END);
    print(col.PURPLE+'Reynolds  Number '+col.END);
    for i in range(0,len(dd)):
        c=(dd[i],ee[i]);
        c=np.asarray(c);
        print(col.CYAN+str(c.T[:,0])+col.END);
        print(col.PURPLE+str(c.T[:,1])+col.END);
    return l2, l1;
예제 #45
0
	def drawAll(self, dst):
		self.drawAllFlag = False
		for h in range(self.h):
			for  w in range(self.w):
				pos = [self.pos[0] + (self.w/2 - w),
				       self.pos[1] + (self.h/2 - h)]
				if (pos[0] >= 0) & (pos[1] >= 0) & \
				   (pos[0] < LEVEL_WIDTH) & \
				   (pos[1] < LEVEL_HEIGHT):
					if configs.misc.COLORED == True:
						dst.addstr(self.y + self.h - h,
							   self.x + self.w - w,
							   self.gMap[pos[0]][pos[1]][0],
							   color.color(self.gMap[pos[0]][pos[1]][1],
								       self.gMap[pos[0]][pos[1]][2]))
					else:
						dst.addstr(self.y + self.h - h,
							   self.x + self.w - w,
							   self.gMap[pos[0]][pos[1]][0])
예제 #46
0
파일: gamemap.py 프로젝트: kidaa/bttext
    def draw(self, dst):
        if self.drawAllFlag == True:
            self.drawAll(dst)
        else:
            for elem in self.drawPos:
                pos = (elem[0], elem[1])

                if (pos[0] < 0) or (pos[1] < 0) or \
                   (pos[0] >= LEVEL_WIDTH) or \
                   (pos[1] >= LEVEL_HEIGHT):
                    continue

                screenpos = self.to_screenpos(pos[0], pos[1])
                if configs.misc.COLORED == True:
                    dst.addstr(screenpos[1], screenpos[0], '+',
                               color.color(7, 0))
                else:
                    dst.addstr(screenpos[1], screenpos[0], '+')


                self.drawPos = []
def solve_it(input_data):
    # Modify this code to run your optimization algorithm

    # parse the input
    lines = input_data.split('\n')

    first_line = lines[0].split()
    node_count = int(first_line[0])
    edge_count = int(first_line[1])
    nodes = {i:Node() for i in range(node_count)}

    edges = []
    for i in range(1, edge_count + 1):
        line = lines[i]
        parts = line.split()
        edges.append((int(parts[0]), int(parts[1])))

    #Build graph
    for e in edges:
        nodeA, nodeB = e 
        nodes[nodeA].toNode.append(nodeB)
        nodes[nodeB].toNode.append(nodeA)
    
    #for index in range(node_count):
    #    print 'Node', index, ': ', nodes[index].toNode 
    

    # build a trivial solution
    # every node has its own color
    #solution = range(0, node_count)

    #My solution:
    solution , colorNum= color.color(nodes)

    # prepare the solution in the specified output format
    output_data = str(colorNum) + ' ' + str(0) + '\n'
    output_data += ' '.join(map(str, solution))

    return output_data
예제 #48
0
	def draw(self, dst):
		if self.drawAllFlag == True:
			self.drawAll(dst)
		else:
			for elem in self.drawPos:
#				pos = [self.pos[0] + (self.w/2 - elem[0]), 
#				       self.pos[1] + (self.h/2 - elem[1])]
                                pos = [elem[0],
				       elem[1]]

				if (pos[0] >= 0) & (pos[1] >= 0) & \
				       (pos[0] < LEVEL_WIDTH) & \
				       (pos[1] < LEVEL_HEIGHT):
					if configs.misc.COLORED == True:
						dst.addstr(self.y + elem[1] + self.h/2 - self.pos[1] + self.h%2,
							   self.x + elem[0] + self.w/2 - self.pos[0] + self.w%2,
							   self.gMap[pos[0]][pos[1]][0],
							   color.color(self.gMap[pos[0]][pos[1]][1],
								       self.gMap[pos[0]][pos[1]][2]))
					else:
						dst.addstr(self.y + elem[1] + self.h/2 - self.pos[1] + self.h%2,
							   self.x + elem[0] + self.w/2 - self.pos[0] + self.w%2,
							   self.gMap[pos[0]][pos[1]][0])
			self.drawPos = []
예제 #49
0
파일: style.py 프로젝트: jordsti/stigame
 def get_highlight_foreground(self):
     return color.color(self.lib.Style_getHighlightForeground(self.obj))
예제 #50
0
 def colored_field(self, prop_name):
     my_val = getattr(self, prop_name)
     if prop_name in self.colors():
         return color(self.colors()[prop_name], my_val)
     return my_val
예제 #51
0
	def test_testNameNextLine(self):
		red = color.color(repr("\n"), "red")
		green = color.color(repr("\t"), "green")
		
		print(red + green)
예제 #52
0
	def test_testName(self):
		red = color.color("1", "red")
		green = color.color("2", "green")
		yellow = color.color("3", "yellow")
		print(red + green + yellow)
예제 #53
0
파일: style.py 프로젝트: jordsti/stigame
 def get_highlight_background(self):
     return color.color(self.lib.Style_getHighlightBackground(self.obj))
예제 #54
0
    def __init__(self):
        self.redraw = True
        self.ui = open('c_editor/ui.xml', 'r').read()

        window = gtk.Window()
        window.set_title(_('Character Editor'))
        window.set_size_request(1024, 768)
        self.vbox = gtk.VBox()
        window.add(self.vbox)

        # UIManager
        ui = gtk.UIManager()

        # shortcuts group
        shortcut_g = ui.get_accel_group()
        window.add_accel_group(shortcut_g)

        # ActionGroup
        self.actions_g = gtk.ActionGroup('Menu')

        character_s = gtk.combo_box_new_text()

        #search character project
        first_character = None
        for path in os.listdir(CHARACTER_PATH):
            xml_path = CHARACTER_PATH + path + '/' + path + '.xml'
            if not os.path.isfile(xml_path):
                color(_("project directory '" + path \
                    + "' don't use xml file!"), 'red')
                continue
            if not validate_xml(xml_path):
                color(_("project directory " + path \
                    + " use an incorrect xml file!"), 'red')
                continue
            if first_character == None:
                self.project_path = CHARACTER_PATH + path + '/'
                first_character = xml_path
            character_s.append_text(path)

        character_s.set_active(0)

        # get movements list
        self.cp = CP(first_character)
        self.movements = gtk.combo_box_new_text()
        for mov in self.cp.movements:
            self.movements.append_text(mov)

        self.movements.set_active(0)

        self.frame_e = FE(self.cp, self.movements.get_active())

        # zoom selector
        zoom = gtk.combo_box_new_text()
        self.zoom_sizes = [0.25, 0.5, 1, 2, 3]
        for size in self.zoom_sizes:
            zoom.append_text(str(int(size * 100)) + ' %')
        self.size = 1000
        zoom.set_active(2)

        self.timeline = TM(self.cp.get_frames(0))
        self.remote = RC(
            self.frame_e, self.project_path, self.timeline
            )
        self.remote.zoom = zoom
        # actions
        self.actions_g.add_actions([
            ('File', None, 'File'),
            ('New', gtk.STOCK_NEW, _('New'),
                None, _('Create new character'), self.new),
            ('Save', gtk.STOCK_SAVE, _('Save'),
                None, _('Save character'), self.save),
            ('Reload', gtk.STOCK_REFRESH, _('Reload'),
                'F5', _("Reload the current file"), self.reload_file),
            ('Quit', gtk.STOCK_QUIT,
                '_Quit', None, 'Quit program', self.quit),
            ('Help', None, '_Help'),
            ('About', None, '_About'),
            ('Begin', gtk.STOCK_MEDIA_REWIND, _('begin'),
                None, _('go to first frame...'), self.remote.begin),
            ('Previous', gtk.STOCK_MEDIA_PREVIOUS, _('previous'),
                None, _('go to previous frame...'), self.remote.previous),
            ('Play', gtk.STOCK_MEDIA_PLAY, _('Play'),
                None, _('Play animation'), self.remote.play),
            ('Next', gtk.STOCK_MEDIA_NEXT, _('Next'),
                None, _('go to next frame...'), self.remote.next),
            ('End', gtk.STOCK_MEDIA_FORWARD, _('End'),
                None, _('go to last frame...'), self.remote.end)
            ])

        self.actions_g.get_action('Quit').set_property('short-label', '_Quit')

        ui.insert_action_group(self.actions_g, 0)

        ui.add_ui_from_string(self.ui)

        menu_bar = ui.get_widget('/Menu_Bar')
        self.vbox.pack_start(menu_bar, False)

        toolbar = ui.get_widget('/ToolBar')
        tool_item = gtk.ToolItem()
        tool_item.add(character_s)
        toolbar.insert(tool_item, 4)
        tool_item = gtk.ToolItem()
        tool_item.add(self.movements)
        toolbar.insert(tool_item, 5)

        self.vbox.pack_start(toolbar, False)

        self.vbox.pack_start(self.frame_e, expand=True)
        self.vbox.pack_start(self.timeline, False)

        remoteC = ui.get_widget('/RemoteControl')
        tool_item = gtk.ToolItem()
        tool_item.add(zoom)
        remoteC.insert(tool_item, 5)
        self.vbox.pack_end(remoteC, False)

        character_s.connect('changed', self.__character_s)
        self.movements.connect('changed', self.__movements)
        zoom.connect('changed', self.__zoom)
        self.window = window
        window.connect('destroy', self.quit)
        window.show_all()
예제 #55
0
파일: submit3.py 프로젝트: cpausmit/MitProd
            print ' Submission failed  (%s) --> retry once!'%(cmd)
            status = os.system(cmd)

            # keep track of success and failure
            if status == 0:
                nSuccess += 1
            else:
                nFail += 1

        # last action in the loop: increment the merged blocks
        idx += 1
    
    print '  Number of blocks submitted: %d' % nSubmission

    # cleanup in case of total failure
    col = color.color()
    print  "Submission summary:" \
        + col.OKBLUE+col.BOLD + " %d successes "%(nSuccess) + col.ENDC \
        + col.FAIL + " %d failures"%(nFail) \
        + col.ENDC

    if nSuccess == 0 and nFail > 0:
        cmd = "rm -rf crab_" + tag
        print " TOTAL FAILURE -- removing: " + tag
        os.system(cmd)
        


# and cleanup the temporary file for the task
cmd = "rm -f crab_" + crabTask.tag + ".cfg crab_" + crabTask.tag + ".cfg-Template " \
      + cmsswPy + ' ' + cmsswPy + 'c'
예제 #56
0
파일: gamemap.py 프로젝트: kidaa/bttext
 def draw_colored(self, pos, elem):
     dst.addstr(self.y + elem[1] + self.h/2 - self.pos[1] + self.h%2,
                self.x + elem[0] + self.w/2 - self.pos[0] + self.w%2,
                self[pos]['ascii'], 
                color.color(self[pos]['fg'], self[pos]['bg']))