Exemple #1
0
 def apply_move(self, move, symbol):
     from util import tuple_replace as replace
     source_row = self.rows[move.row]
     new_row = replace(symbol, move.column, source_row)
     new_board = self.copy
     new_board.update_from_tuple(replace(new_row, move.row, self.rows))
     return new_board
Exemple #2
0
    def add_to_cart(self, product):
        product_ = CRUD.retreive_name('"'+product+'"')
        print(product)
        if(util.check_if_exists(product, self.order_list)):
            index = util.get_index(product, self.order_list)
            self.order_qty[index] = self.Tracker.qty_change
            util.replace(index, self.Table_)
            s = str(index)
        else:
            self.order_list.append(product)
            self.order_qty.append(self.Tracker.qty_change)
            s = 'end'

        print(product_)
        qty = self.Tracker.qty_change
        price = util.wholesale_check(qty, product_)
        total = price * qty
        delta = self.Tracker.qty_change - self.Tracker.qty_ref
        stock = self.Tracker.qty_s - delta
        CRUD.update_stock(str(product), int(stock))
        
        if(qty == 0):
            a = int(util.get_index(product, self.order_list))
            name=self.order_list.pop(a)
            quan=self.order_qty.pop(a)
            # self.focus_item(a)
            # self.Table_.tree.delete(self.Table_.tree.selection())
        else:
            product=product.replace(" ", "")
        
            product=(product+" "+str(qty)+" " + str(price) + " "+ str(total))
            self.Table_.tree.insert('', s, values=(product))

        total = sum(float(self.Table_.tree.set(item,3)) for item in self.Table_.tree.get_children())
        self.totala.set(total)
Exemple #3
0
def test_replace():
    s = '\n'
    s += util.replace('abc', 'a', 'z')
    s += '\n'
    s += util.replace('abc123', 'bc', 'zy')
    s += '\n'
    s += util.replace('abc123', '123', '987')
    s += '\n'
    s += util.replace('abc123', '\d', 'zyx')
    s += '\n'
    s += util.replace('abc 123', '\s', '****')
    s += '\n'
    s += util.replace('abc 123', r'^ab', 'AB')
    s += '\n'
    s += util.replace('abc 123 abcabc', r'ab', 'AB')
    s += '\n'
    s += '\n'
    s += util.replace('abc 123 abcabc\nabcabcxyz', r'^ab', 'AB')
    s += '\n'
    s += '\n'
    s += util.replace('abc 123 abcabc\nabcabcxyz', r'^ab', 'AB', flags=re.MULTILINE)
    s += '\n'
    s += '\n'
    s += util.replace('123abcdefg123 abx abc456xyz789abcdefgxyz', r'ab(?P<name1>.)', r'AB\g<name1>')
    return s
Exemple #4
0
 def doError(self):
     do = len(util.replace(self.code, 'do', 'do', True)[1])
     end = len(util.replace(self.code, 'end', 'end', True)[1])
     if do == end:
         return
     else:
         if do > end:
             self.result = f"Syntax Error: there are {end} end and {do} do is missing {do-end} end"
         else:
             self.result = f"Syntax Error: there are {do} do and {end} end is missing {end-do} end"
def getSummonerStats(summonerId, region):

    ApiKey = util.getApiKey()
    url = BASE_URL

    url = util.replace(url, "{region}", region)
    url = util.replace(url, "{summoner_id}", summonerId)
    url = util.replace(url, "{api_key}", ApiKey)
    url = util.replace(url, "{version}", util.getStatsVersion())

    #try:
    response = urllib2.urlopen(url)
    data = response.read()
    stats = parseJson(data, summonerId)
    return stats
Exemple #6
0
def plot_fs(data, outdir):
    cs = {}
    for name in ['rand', 'nonad', 'ad']:
        cs[name] = util.get_coords(data['ks'], data[name])
        means = []
        ks = np.unique(data['ks'])
        for k in ks:
            means.append(np.mean(np.array(data[name])[data['ks'] == k]))
        cs['mean_' + name] = util.get_coords(ks, means)
    cs['x_max'] = str(max(data['ks']))
    cs['y_max'] = str(max(data['ad']))
    cs['title'] = re.escape(data['model'])
    texname = 'fs_' + data['model'].lower() + '.tex'
    util.replace(outdir, TEMPLATE_FS, cs, texname)
    util.maketex(outdir, texname)
Exemple #7
0
    def OnReplace(self, event):
        if not self.sc.word:
            return

        sp = self.ctrl.sp
        u = undo.SinglePara(sp, undo.CMD_MISC, self.sc.line)

        word = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
        ls = sp.lines

        sp.gotoPos(self.sc.line, self.sc.col)

        ls[self.sc.line].text = util.replace(
            ls[self.sc.line].text, word,
            self.sc.col, len(self.sc.word))

        sp.rewrapPara(sp.getParaFirstIndexFromLine(self.sc.line))

        # rewrapping a paragraph can have moved the cursor, so get the new
        # location of it, and then advance past the just-changed word
        self.sc.line = sp.line
        self.sc.col = sp.column + len(word)

        sp.clearMark()
        sp.markChanged()

        u.setAfter(sp)
        sp.addUndo(u)

        self.gotoNext(False)
Exemple #8
0
def get_one(obj, model):
    lmodel = model.lower()
    if obj[:2] == 'fs':
        resdir = os.path.join(util.DIR_RES, obj[2:], model)
    else:
        resdir = os.path.join(util.DIR_RES, obj, model)
    with open(os.path.join(resdir, lmodel + '.pickle')) as f:
        data = pcl.load(f)
        g = ig.Graph.Read_Edgelist(os.path.join(resdir, 'graph'))
        cs = {}
        ks = np.unique(data['ks'])
        if obj[:2] != 'fs':
            means = []
            stds = []
            for k in ks:
                reps = sum(data['ks'] == k)
                ys_ad = np.array(data['ad'])[data['ks'] == k]
                ys_nonad = np.array(data['nonad'])[data['ks'] == k]
                ys = [(100.0*(foo-bar))/max(foo,bar)
                      for foo, bar in zip(ys_ad, ys_nonad)]
                means.append(np.mean(ys))
                stds.append(np.std(ys)/np.sqrt(reps))
            cs['imp'] = util.get_coords(ks, means, stds)
            if obj == 'influence' or obj == 'maxcut':
                template = TEMPLATE_FS
            else:
                template = TEMPLATE_PS
            texname = OBJ_SHORT[obj] + '_' + lmodel + '.tex'
            util.replace(OUTDIR, template, cs, texname)
        else:
            means_ad = []
            stds_ad = []
            means_nonad = []
            stds_nonad = []
            for k in ks:
                reps = sum(data['ks'] == k)
                ys_ad = np.array(data['ad'])[data['ks'] == k]
                means_ad.append(np.mean(ys_ad))
                stds_ad.append(np.std(ys_ad)/np.sqrt(reps))
                ys_nonad = np.array(data['nonad'])[data['ks'] == k]
                means_nonad.append(np.mean(ys_nonad))
                stds_nonad.append(np.std(ys_nonad)/np.sqrt(reps))
            cs['mean_ad'] = util.get_coords(ks, means_ad, stds_ad)
            cs['mean_nonad'] = util.get_coords(ks, means_nonad, stds_nonad)
            texname = OBJ_SHORT[obj] + '_' + lmodel + '.tex'
            util.replace(OUTDIR, TEMPLATE_FAVG, cs, texname)
        print '---------'
Exemple #9
0
 def repeatError(self):
     for key in self.keywords:
         for c in range(0, len(self.lines)):
             wordKey = len(util.replace(self.lines[c], key, key, True)[1])
             do = len(util.replace(self.lines[c], 'do', 'do', True)[1])
             if wordKey == 0:
                 continue
             if wordKey == do and wordKey <= 1:
                 self.doError()
             else:
                 if wordKey == do:
                     self.result = f"Syntax Error: you can only put one conditional in a line but there are {wordKey} {key}"
                 elif wordKey > 1:
                     self.result = f"Syntax Error: there are {wordKey} {key}, but you can onpy put one {key} in a line"
                 elif do > wordKey:
                     self.result = f"Syntax error: there are {wordKey} {key}, but {do} do."
                 elif do < wordKey:
                     self.result = f"Syntax error: there are {wordKey} {key}, but only {do} do."
Exemple #10
0
def getSummonerStats(summonerId, region):

	ApiKey = util.getApiKey()
	url = BASE_URL

	url = util.replace(url, "{region}", region)
	url = util.replace(url, "{summoner_id}", summonerId)
	url = util.replace(url, "{api_key}", ApiKey)
	url = util.replace(url, "{version}", util.getStatsVersion())

	#try:
	response = urllib2.urlopen(url)
	data = response.read()
	stats = parseJson(data, summonerId)
	return stats
	#except:
		#print response.getcode()

#getSummonerStats("32280833", "na")
Exemple #11
0
def main():

    while True:
        ip = Get_local_ip()
        if ip and ip != "127.0.0.1":
            #修改IP地址
            with open('/home/nvidia/Horus/config.cnf') as f:
                cnf = json.load(f)
                cnf['host_ip'] = ip
                jsonstr = json.dumps(cnf, ensure_ascii=False, sort_keys=True)
                util.replace('/home/nvidia/Horus/config.cnf', jsonstr)

            file_thread = myFileThread()
            file_thread.start()
            createDaemon()

            break

        else:
            continue
Exemple #12
0
def getSummonerByName(region, name):

	name = util.replace(name, " ", "")

	ApiKey = util.getApiKey()
	url = BASE_URL
	url = util.replace(url, "{region}", region)
	url = util.replace(url, "{summoner_name}", name)
	url = util.replace(url, "{api_key}", ApiKey)
	url = util.replace(url, "{version}", util.getSummonerVersion())
	#util.log(url)

	summonerFound = False

	#try:
	response = urllib2.urlopen(url)
	data = response.read()
	summoner = parseJson(data, name)
	summonerFound = True
	return summoner
	#except:
	util.log("Summoner not Found")
def getSummonerByName(region, name):

	name = util.replace(name, " ", "")

	ApiKey = util.getApiKey()
	url = BASE_URL
	url = util.replace(url, "{region}", region)
	url = util.replace(url, "{summoner_name}", name)
	url = util.replace(url, "{api_key}", ApiKey)
	url = util.replace(url, "{version}", util.getSummonerVersion())
	#util.log(url)

	summonerFound = False

	try:
		response = urllib2.urlopen(url)
		data = response.read()
		summoner = parseJson(data, name)
		summonerFound = True
		return summoner
	except:
		util.log("Summoner not Found")
Exemple #14
0
    def OnReplace(self, event=None, autoFind=False):
        if self.searchLine == -1:
            return False

        value = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
        ls = self.ctrl.sp.lines

        sp = self.ctrl.sp
        u = undo.SinglePara(sp, undo.CMD_MISC, self.searchLine)

        ls[self.searchLine].text = util.replace(ls[self.searchLine].text,
                                                value, self.searchColumn,
                                                self.searchWidth)

        sp.rewrapPara(sp.getParaFirstIndexFromLine(self.searchLine))

        self.searchLine = -1

        diff = len(value) - self.searchWidth

        if not self.dirUp:
            sp.column += self.searchWidth + diff
        else:
            sp.column -= 1

            if sp.column < 0:
                sp.line -= 1

                if sp.line < 0:
                    sp.line = 0
                    sp.column = 0

                    self.searchLine = 0
                    self.searchColumn = 0
                    self.searchWidth = 0
                else:
                    sp.column = len(ls[sp.line].text)

        sp.clearMark()
        sp.markChanged()

        u.setAfter(sp)
        sp.addUndo(u)

        self.OnFind(autoFind=autoFind)

        return True
Exemple #15
0
    def OnReplace(self, event=None, autoFind=False):
        if self.searchLine == -1:
            return False

        value = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
        ls = self.ctrl.sp.lines

        sp = self.ctrl.sp
        u = undo.SinglePara(sp, undo.CMD_MISC, self.searchLine)

        ls[self.searchLine].text = util.replace(
            ls[self.searchLine].text, value,
            self.searchColumn, self.searchWidth)

        sp.rewrapPara(sp.getParaFirstIndexFromLine(self.searchLine))

        self.searchLine = -1

        diff = len(value) - self.searchWidth

        if not self.dirUp:
            sp.column += self.searchWidth + diff
        else:
            sp.column -= 1

            if sp.column < 0:
                sp.line -= 1

                if sp.line < 0:
                    sp.line = 0
                    sp.column = 0

                    self.searchLine = 0
                    self.searchColumn = 0
                    self.searchWidth = 0
                else:
                    sp.column = len(ls[sp.line].text)

        sp.clearMark()
        sp.markChanged()

        u.setAfter(sp)
        sp.addUndo(u)

        self.OnFind(autoFind=autoFind)

        return True
Exemple #16
0
    def OnReplace(self, event):
        if not self.sc.word:
            return

        word = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
        ls = self.ctrl.sp.lines

        ls[self.sc.line].text = util.replace(ls[self.sc.line].text, word,
                                             self.sc.col, len(self.sc.word))

        self.ctrl.searchLine = -1

        diff = len(word) - len(self.sc.word)

        self.sc.col += len(self.sc.word) + diff
        self.didReplaces = True
        self.ctrl.sp.markChanged()
        self.gotoNext(False)
Exemple #17
0
    def OnReplace(self, event):
        if not self.sc.word:
            return

        word = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
        ls = self.ctrl.sp.lines

        ls[self.sc.line].text = util.replace(
            ls[self.sc.line].text, word,
            self.sc.col, len(self.sc.word))

        self.ctrl.searchLine = -1

        diff = len(word) - len(self.sc.word)

        self.sc.col += len(self.sc.word) + diff
        self.didReplaces = True
        self.ctrl.sp.markChanged()
        self.gotoNext(False)
Exemple #18
0
    def rescale_image(self, img_num: int) -> np.ndarray:
        """
        scales the colors in all images based on the lowest and highest temperature among all the pictures
        :param img_num: 0, 1, 2, ..., n the image number is used to grab the image file and the temperature data
        :return: the rescaled image
        """
        self.global_color_map: Dict[float,
                                    Color] = self.get_global_temp_color_map()

        img_num_str: str = util.make_double_digit_str(img_num)
        img: np.ndarray = cv2.imread(self.directory_path +
                                     "/ir{0}.png".format(img_num_str))

        # get colors and temperatures separately
        color_map_orig: Dict[float, Color] = self.get_temp_color_map(
            self.lowest[img_num],
            self.highest[img_num])  # gets temperature to color
        local_temps: List[float] = list(color_map_orig.keys())
        adjusted_local_temps: List[float] = self.match_local_with_global_temps(
            local_temps)
        # remakes the color map so that the temperatures now match up with the global temperatures
        color_map: Dict[Color, float] = dict(
            zip(self.palette, adjusted_local_temps))  # color to temperature
        # map local color to the global color
        local_color_to_global: Dict[Color, Color] = {}
        for color in color_map:
            local_color_to_global[color] = self.global_color_map[
                color_map[color]]

        rescaled_image: np.ndarray = np.zeros(img.shape)

        # make sure colors in image match the palette exactly
        image_obj: Image.Image = Image.Image(img)
        image_obj.set_colors_to_palette(self.palette)

        # replace local colors with global colors row by row
        for x in range(img.shape[1]):
            rescaled_image[:, x] = util.replace(
                image_obj.img[:, x].astype(np.float64), local_color_to_global)

        return rescaled_image
Exemple #19
0
    def OnReplace(self, event=None, autoFind=False):
        if self.ctrl.searchLine != -1:
            value = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
            ls = self.ctrl.sp.lines

            ls[self.ctrl.searchLine].text = util.replace(
                ls[self.ctrl.searchLine].text, value, self.ctrl.searchColumn,
                self.ctrl.searchWidth)

            self.ctrl.searchLine = -1

            diff = len(value) - self.ctrl.searchWidth

            if not self.dirUp:
                self.ctrl.sp.column += self.ctrl.searchWidth + diff
            else:
                self.ctrl.sp.column -= 1

                if self.ctrl.sp.column < 0:
                    self.ctrl.sp.line -= 1

                    if self.ctrl.sp.line < 0:
                        self.ctrl.sp.line = 0
                        self.ctrl.sp.column = 0

                        self.ctrl.searchLine = 0
                        self.ctrl.searchColumn = 0
                        self.ctrl.searchWidth = 0
                    else:
                        self.ctrl.sp.column = len(ls[self.ctrl.sp.line].text)

            if diff != 0:
                self.didReplaces = True

            self.ctrl.sp.markChanged()
            self.OnFind(autoFind=autoFind)

            return True
        else:
            return False
Exemple #20
0
    def OnReplace(self, event = None, autoFind = False):
        if self.ctrl.searchLine != -1:
            value = util.toInputStr(misc.fromGUI(self.replaceEntry.GetValue()))
            ls = self.ctrl.sp.lines

            ls[self.ctrl.searchLine].text = util.replace(
                ls[self.ctrl.searchLine].text, value,
                self.ctrl.searchColumn, self.ctrl.searchWidth)

            self.ctrl.searchLine = -1

            diff = len(value) - self.ctrl.searchWidth

            if not self.dirUp:
                self.ctrl.sp.column += self.ctrl.searchWidth + diff
            else:
                self.ctrl.sp.column -= 1

                if self.ctrl.sp.column < 0:
                    self.ctrl.sp.line -= 1

                    if self.ctrl.sp.line < 0:
                        self.ctrl.sp.line = 0
                        self.ctrl.sp.column = 0

                        self.ctrl.searchLine = 0
                        self.ctrl.searchColumn = 0
                        self.ctrl.searchWidth = 0
                    else:
                        self.ctrl.sp.column = len(ls[self.ctrl.sp.line].text)

            if diff != 0:
                self.didReplaces = True

            self.ctrl.sp.markChanged()
            self.OnFind(autoFind = autoFind)

            return True
        else:
            return False
Exemple #21
0
    def change_palette(self, new_palette_name: str) -> None:
        """
        given an image that only contains colors from one palette, change it to the colors of another palette
        :param new_palette_name: the palette you want to new image to follow like "lava.pal"
        :return: an image that follows the new palette
        """

        old_palette: List[Color] = util.palette_to_bgr("palettes/" +
                                                       self.identify_palette())
        new_palette: List[Color] = util.palette_to_bgr("palettes/" +
                                                       new_palette_name)

        # if the sizes don't match up stretch one of them
        if len(new_palette) != len(old_palette):
            if len(new_palette) > len(old_palette):
                old_palette = util.stretch_list(old_palette, len(new_palette))
            else:
                new_palette = util.stretch_list(new_palette, len(old_palette))

        old_to_new: Dict[Color, Color] = dict(zip(old_palette, new_palette))

        for i in range(self.img.shape[0]):
            row: np.ndarray = self.img[i]
            self.img[i] = util.replace(row, old_to_new)
Exemple #22
0
import component, util, os

MY_HOME = os.getenv('MY_HOME')
ini_file = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'pgbouncer.ini'
util.replace('MY_HOME', MY_HOME, ini_file)

component.init_comp('bouncer', 'pgbouncer.pid')

Exemple #23
0
# -*- coding: utf-8 -*-
"""
Created on Thu Apr  7 13:39:53 2016

@author: aanderson
"""

import numpy as np
from util import replace

N = int(raw_input())
for i in xrange(1, N + 1):
    pan = list(raw_input())
    replace(pan, '-', 0)
    replace(pan, '+', 1)
    x = np.sum(np.abs(np.diff(np.array(pan))))
    x = x + 1 - pan[-1]

    print "Case #{}: {}".format(i, x)
Exemple #24
0
    def deal_command(self, socket, data):
        sys.path.append("..")
        import util
        if '0x01' in data:
            #打开摄像头
            util.Logprint(2, data)
            cmd = '/home/nvidia/Horus/opencamera'
            subprocess.Popen(cmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        elif '0x02' in data:
            #自定义命令
            util.Logprint(2, data)
            cus_command = data.split(':')[1]
            if cus_command != '':
                os.system(cus_command)

        elif '0x03' in data:
            util.Logprint(2, data)
            #关闭摄像头
            pids = psutil.pids()
            for pid in pids:
                p = psutil.Process(pid)
                #                if "python" in p.name():
                #                    ss=p.cmdline()
                #                    if len(ss)>0:
                #                        if ss[1]=="/home/nvidia/Horus/opencamera.py":
                #                            util.kill(pid)
                #                    util.Logprint(1,data)
                if "opencamera" in p.name():
                    util.kill(pid)

        elif '0x04' in data:
            #发送日志
            # Communicate().sendFile(socket,config.LOG_PATH)
            pass

        elif '0x05' in data:
            import util  #更新config的level值
            util.Logprint(2, data)
            #设置config
            key = data.split(':')[1]
            value = data.split(':')[2]
            #修改K-V
            with open('/home/nvidia/Horus/config.cnf') as f:
                cnf = json.load(f)
                cnf[key] = value
                jsonstr = json.dumps(cnf, ensure_ascii=False, sort_keys=True)
                util.replace('/home/nvidia/Horus/config.cnf', jsonstr)
        elif '0x06' in data:
            util.Logprint(2, data)
            #打开环境传感器
            global envid
            envid = Communicate().createnvDaemon()

        elif '0x07' in data:
            util.Logprint(2, data)
            #关闭环境传感器
            util.kill(envid)
        elif '0x08' in data:
            util.Logprint(2, data)
            obddata = data[5:]
            if util.is_json(obddata):
                with open('/home/nvidia/Horus/config.cnf') as json_data:
                    cnf = json.load(json_data)
                    db = create_engine(cnf['db'])
                    s = json.loads(obddata)
                    insert_data = "insert into tb_obd(timestamp,longitude,latitude,altitude,speed) values (%s,%s,%s,%s,%s)" % (
                        s["timestamp"], s["longitude"], s["latitude"],
                        s["altitude"], s["speed"])
                    db.execute(insert_data)
        elif '0x09' in data:
            util.Logprint(2, data)
            pids = psutil.pids()
            for pid in pids:
                p = psutil.Process(pid)
                if "python" in p.name():
                    ss = p.cmdline()
                    if len(ss) > 0:
                        if ss[1] == "Horus.py":
                            util.kill(pid)
                    util.Logprint(1, data)
                if "Horus" in p.name():
                    util.kill(pid)

#
        elif 'test' in data:
            util.Logprint(1, data)
            #心跳测试和数据库表的条目查询
            Communicate().dbquery(socket)
            pass

        else:
            util.Logprint(1, data)
            #手机端json数据
            if util.is_json(data):
                with open('/home/nvidia/Horus/config.cnf') as json_data:
                    cnf = json.load(json_data)
                    db = create_engine(cnf['db'])
                    s = json.loads(data)
                    insert_data = "insert into tb_mobile_sensor(timestamp,accx,accy,accz,gpsLongitude,gpsLatitude,gpsAltitude,gpsSpeed,gpsBearing,light,deviceID,frequency) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (
                        s["time"], s["accx"], s["accy"], s["accz"],
                        s["longitude"], s["latitude"], s["altitude"],
                        s["speed"], s["bearing"], s["lightx"], s["deviceID"],
                        s["frequency"])
                    db.execute(insert_data)