示例#1
0
class Drawable(object):
    def __init__(self, options=[]):
        self.__style = Style([], '', [])
        self.__z_order = 0
        self.__options = options
        return

    def options(self):
        return self.__options

    def set_z_order(self, z_order):
        self.__z_order = z_order
        return

    def z_order(self):
        return self.__z_order

    def set_style(self, style):
        self.__style.merge(style)
        return

    def style(self):
        return self.__style

    def min(self):
        raise NotImplementedError

    def max(self):
        raise NotImplementedError
示例#2
0
文件: drawable.py 项目: 251/shaape
class Drawable(object):
    def __init__(self, options = []):
        self.__style = Style([], '', [])
        self.__z_order = 0
        self.__options = options
        return

    def options(self):
        return self.__options

    def set_z_order(self, z_order):
        self.__z_order = z_order
        return

    def z_order(self):
        return self.__z_order

    def set_style(self, style):
        self.__style.merge(style)
        return

    def style(self):
        return self.__style

    def min(self):
        raise NotImplementedError

    def max(self):
        raise NotImplementedError
示例#3
0
def get_style(data_id, style_id, bucket, indexes=None):
    """Load the style from the s3 data store or use id and indexes to generate the style.

    Parameters
    ----------
    data_id : string
        The id representing the data.
    style_id : string
        The id representing the style.
    bucket : string
        The bucket where to search for the style data.
    indexes : list of type 'float'
        Used to generate a new style from the id.
        Only needed if no style not specified in STAC.

    Returns
    -------
    Style object
        The style to use for this implementation.
    """
    s3path = f'tiles/{data_id}/{style_id}.json'
    s3 = boto3.resource('s3')
    try:
        style_config = s3.Object(bucket, s3path).get()
        json_content = json.loads(style_config['Body'].read().decode('utf-8'))
        return Style(**json_content)
    except Exception as e:
        print(e)
        return Style(style_id, indexes)
示例#4
0
def change_style(output):
    # without header, It doesn't work
    res = requests.get(output['file']['url_private_download'],
                       headers={'Authorization': 'Bearer %s' % BOT_API},
                       stream=True)

    # TODO: Now this doesn't use the image on memory.
    # TODO: Explore better resize.
    img_arr = misc.imresize(misc.imread(BytesIO(res.content), mode='RGB'),
                            (200, 200))
    misc.imsave('../imgs/input/temp.jpg', img_arr)
    img = np.expand_dims(
        image_utils.load_np_image(
            os.path.expanduser('../imgs/input/temp.jpg')), 0)

    # download models
    Style.download_checkpoints('check_points')

    style = Style()
    generated_imgs = style.generate_image(img)

    for i, generated_img in enumerate(generated_imgs):
        # TODO: Now this doesn't use the image on memory.
        file_name = '../imgs/output/' + 'generated_' + str(i) + '.jpg'
        misc.imsave(file_name, generated_img)

        slack.files.upload(file_name,
                           filename=file_name,
                           channels=output['channel'])
示例#5
0
 def showCode(self,fileCode):
     print('-'*120)
     print(Style.customHeader('Your Code\n'))
     file = open(fileCode,'r')
     for line,code in enumerate(file):
         print(Style.reset('{}) {}'.format(line+1,code)))
     print(Style.reset('-'*120))
示例#6
0
def get_style():
    style = Style()
    style.h1_template = update_from_cookie_and_post(style.h1_template,
                                                    'h1_template')
    style.h2_template = update_from_cookie_and_post(style.h2_template,
                                                    'h2_template')
    style.footer = update_from_cookie_and_post(style.footer, 'footer')
    return style
示例#7
0
def build_model():

    if os.path.exists(UUID_PRFIX):
        shutil.rmtree(UUID_PRFIX)
    os.makedirs(UUID_PRFIX)
    if os.path.exists(CHECKPOINT_DIR):
        shutil.rmtree(CHECKPOINT_DIR)
    os.makedirs(CHECKPOINT_DIR)
    if os.path.exists(OUTPUT_DIR):
        shutil.rmtree(OUTPUT_DIR)
    os.makedirs(OUTPUT_DIR)
    if os.path.isfile(LOG_PATH):
        os.remove(LOG_PATH)
    with open(LOG_PATH, 'w') as f:
        pass

    # Check directory path
    if not os.path.isdir(CHECKPOINT_DIR):
        raise ValueError(CHECKPOINT_DIR + " doesn't exist.")
    if not os.path.isdir(OUTPUT_DIR):
        raise ValueError(OUTPUT_DIR + " doesn't exist.")
    if not os.path.isdir(DATA_PATH):
        raise ValueError(DATA_PATH + " doesn't exist.")

    # Check file path
    if not os.path.exists(VGG_PATH):
        raise ValueError(VGG_PATH + " doesn't exist.")
    if not os.path.exists(VGG_PATH):
        raise ValueError(STYLE_PATH + " doesn't exist.")
    if not os.path.exists(TEST_PATH):
        raise ValueError(TEST_PATH + " doesn't exist.")

    style_image = load_image(STYLE_PATH)
    test_image = load_image(TEST_PATH, (256, 256))

    # https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
    files = []
    for (dirpath, dirnames, filenames) in os.walk(DATA_PATH):
        files.extend(filenames)
        break
    files = [os.path.join(DATA_PATH, x) for x in files]

    new_style = Style(content_images=files,
                      style_image=style_image,
                      content_weight=7.5,
                      style_weight=100,
                      denoise_weight=100,
                      vgg_path=VGG_PATH,
                      ck_dir=CHECKPOINT_DIR,
                      test_image=test_image,
                      test_out_dir=OUTPUT_DIR,
                      log_path=LOG_PATH,
                      batch_size=32,
                      alpha=1e-3)
    new_style.train()
示例#8
0
 def match(self, tokenAttributeValue):
     if (self.tokenList.token.attributeValue) == tokenAttributeValue:
         print(
             Style.green('Line({})-Match '.format(
                 self.tokenList.token.line)) + 'token ({} {} {}) '.format(
                     self.tokenList.token, Style.green('with'),
                     tokenAttributeValue))
         self.tokenList.nextToken()
     else:
         print(
             Style.red('Line({})-Syntax Error '.format(
                 self.tokenList.token.line)) +
             Style.reset('{} required.'.format(tokenAttributeValue)))
示例#9
0
    def __init__(self, content=None, parent=None):
        self._parent = parent
        self._id = hex(id(self))
        self._style = Style()
        self._computed_style = Style()

        if isinstance(content, str):
            return

        self._id = content.get('id', self._id)
        self._style.update(content.get("style",None))
        self._computed_style = Style()
        if parent and parent.style:
            self._computed_style = copy.copy(parent.style)
            self._computed_style.update(content.get("style",None))
示例#10
0
def create_style_from_stac(style_data,
                           indexes,
                           bucket=None,
                           dataname=None,
                           default=False):
    """Read the data from the STAC file to create a style.

    Parameters
    ----------
    style_data : dict
        The styling data from the STAC.
    indexes: list of type 'float' or type 'int'
        The indexes for aligning the colours in the style.
    bucket : string
        If set, saves the style to given bucket.
    dataname : string
        The id of the dataset this style applies to.
    default : string
        Flag to identify if this is the default style for this data.
    """
    style_id = style_data['id']
    style_indexes = indexes
    resampling_method = style_data.get('resampling_method', 'bilinear')
    hide_min = style_data.get('hide_min', True)
    hide_max = style_data.get('hide_max', False)
    gradient = style_data.get('gradient', True)
    colours = style_data.get('colours')
    style = Style(style_id,
                  style_indexes,
                  resampling_method=resampling_method,
                  hide_min=hide_min,
                  hide_max=hide_max,
                  colours=colours,
                  gradient=gradient)

    # save the style to s3
    if bucket and dataname:
        s3 = boto3.resource('s3')
        s3filename = f"tiles/{dataname}/{style_id}.json"
        s3object = s3.Object(bucket, s3filename)
        s3object.put(Body=(bytes(style.json().encode('UTF-8'))))
        # save default style as default.
        if default:
            s3filename = f"tiles/{dataname}/default.json"
            s3object = s3.Object(bucket, s3filename)
            s3object.put(Body=(bytes(style.json().encode('UTF-8'))))

    return style
示例#11
0
    def _placeDocs(self):
        """
        Places documentation blocks on the documentation layer
        """
        try:
            docs_dict = config.brd['documentation']
        except:
            return

        for key in docs_dict:

            location = utils.toPoint(docs_dict[key]['location'])
            docs_dict[key]['location'] = [0, 0]

            shape_group = et.SubElement(self._layers['documentation']['layer'],
                                        'g')
            shape_group.set('{' + config.cfg['ns']['pcbmode'] + '}type',
                            'module-shapes')
            shape_group.set('{' + config.cfg['ns']['pcbmode'] + '}doc-key',
                            key)
            shape_group.set(
                'transform', "translate(%s,%s)" %
                (location.x, config.cfg['invert-y'] * location.y))

            location = docs_dict[key]['location']
            docs_dict[key]['location'] = [0, 0]

            shape = Shape(docs_dict[key])
            style = Style(docs_dict[key], 'documentation')
            shape.setStyle(style)
            element = place.placeShape(shape, shape_group)
示例#12
0
文件: layer.py 项目: ncrimier/QGIS
 def _get_alternate_styles(self):
     if 'alternate_styles' in self.dirty:
         return self.dirty['alternate_styles']
     if self.dom is None:
         self.fetch()
     styles = self.dom.findall('styles/style/name')
     return [Style(self.catalog, s.text) for s in styles]
示例#13
0
 def get_style(self, name):
     try:
         style_url = url(self.service_url, ['styles', name + '.xml'])
         dom = self.get_xml(style_url)
         return Style(self, dom.find('name').text)
     except FailedRequestError:
         return None
示例#14
0
    def _processShapes(self):
        """
        """

        sheets = ['conductor', 'silkscreen', 'soldermask']

        for sheet in sheets:

            try:
                shapes = self._footprint['layout'][sheet]['shapes']
            except:
                shapes = []
     
            for shape_dict in shapes:
                layers = utils.getExtendedLayerList(shape_dict.get('layers') or ['top'])
                for layer in layers:
                    # Mirror the shape if it's text and on bottom later,
                    # but let explicit shape setting override
                    if layer == 'bottom':
                        if shape_dict['type'] == 'text':
                            shape_dict['mirror'] = shape_dict.get('mirror') or 'True'
                    shape = Shape(shape_dict)
                    style = Style(shape_dict, sheet)
                    shape.setStyle(style)
                    try:
                        self._shapes[sheet][layer].append(shape)
                    except:
                        self._shapes[sheet][layer] = []
                        self._shapes[sheet][layer].append(shape)
    def __init__(self, fileName, storageFormat):
        self._fileName = fileName
        self._layerName = os.path.splitext(os.path.basename(self._fileName))[0]
        self.storageFormat = storageFormat

        # create point layer (WGS-84, EPSG:4326)
        super(LayerBase, self).__init__('Point?crs=epsg:4326', self._layerName,
                                        "memory")

        self._aliases = []  # list of attribute aliases
        self._provider = self.dataProvider()

        # import errors
        self._errs = {}

        # layer is empty, no data loaded
        self._loaded = False
        self.metadata = None

        # layer type not defined
        self.layerType = None

        # style
        self._style = Style()
        self._renderer = None
示例#16
0
文件: main.py 项目: j-kyoda/linemap
    def __init__(self, master=None):
        Tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

        self.style = Style.load('data/style.xml')
        self.filename = 'data/'
示例#17
0
 def get_styles(self):
     styles_url = url(self.service_url, ['styles.xml'])
     description = self.get_xml(styles_url)
     return [
         Style(self,
               s.find('name').text) for s in description.findall('style')
     ]
示例#18
0
def export(packageName, path):
    print("export to path:" + path + "  begin.")

    workbook = xw.Workbook(path)
    # style
    style = Style(workbook)
    worksheet = workbook.add_worksheet("ioHistory")
    # get process by packageName
    processes = get_process_by_package(packageName)

    # init column_max_width_array
    column_max_width_array = [0] * len(AUTOCOLUMN_WIDTH_INDEXS)

    # loop create table group by process
    row = 0
    for process in processes:
        row = create_table(worksheet, style, process, row,
                           get_data_by_process(packageName, process),
                           column_max_width_array)

    # auto fit column width
    auto_fit_column_width(worksheet, column_max_width_array)

    workbook.close()
    print("\nexport successful:" + path)
示例#19
0
 def __init__(self, id=None):
     super(Line, self).__init__()
     self.style = Style(Line.__style__)
     self._id = id
     self.fuzziness = 2
     self._handles[0].connectable = False
     self._handles[-1].connectable = False
示例#20
0
def loadTheme(filename):
    global default
    global styles

    prefix = os.path.dirname(__file__)
    if (hasattr(sys, 'frozen') and sys.frozen == 'macosx_app'):
        prefix = os.environ['RESOURCEPATH']

    theme = json.load(open(os.path.join(prefix, filename)))
    default = theme['defaults']

    for name in theme['styles']:
        style = theme['styles'][name]

        fore = None
        back = None
        fontStyle = None

        if "foreground" in style:
            fore = style["foreground"]

        if "background" in style:
            back = style["background"]

        if "fontStyle" in style:
            fontStyle = style["fontStyle"]

        styles[name] = Style(name, fore, back, fontStyle)
示例#21
0
    def _placePours(self):
        """
        """

        try:
            pours = self._module_dict['shapes']['pours']
        except:
            return

        shape_group = {}
        for pcb_layer in utils.getSurfaceLayers():
            svg_layer = self._layers[pcb_layer]['copper']['pours']['layer']
            shape_group[pcb_layer] = et.SubElement(svg_layer,
                                                   'g',
                                                   mask='url(#mask-%s)' %
                                                   pcb_layer)

        for pour_dict in pours:
            try:
                pour_type = pour_dict['type']
            except:
                msg.error(
                    "Cannot find a 'type' for a pour shape. Pours can be any 'shape', or simply 'type':'layer' to cover the entire layer."
                )

            layers = pour_dict.get('layers') or ['top']

            if pour_type == 'layer':
                # Get the outline shape dict
                new_pour_dict = self._module_dict['outline'].get(
                    'shape').copy()
                new_pour_dict['style'] = 'fill'
                shape = Shape(new_pour_dict)
                # Get the appropriate style from copper->pours
                style = Style(new_pour_dict,
                              layer_name='copper',
                              sub_item='pours')
                shape.setStyle(style)
            else:
                shape = Shape(pour_dict)
                # Get the appropriate style from copper->pours
                style = Style(pour_dict, layer_name='copper', sub_item='pours')
                shape.setStyle(style)

            # Place on all specified layers
            for layer in layers:
                place.placeShape(shape, shape_group[layer])
示例#22
0
    def parse(self, xml_file):
        "Get a list of parsed recipes from BeerXML input"

        recipes = []

        with open(xml_file, "rt") as f:
            tree = ElementTree.parse(f)

        for recipeNode in tree.iter():
            if self.to_lower(recipeNode.tag) != "recipe":
                continue

            recipe = Recipe()
            recipes.append(recipe)

            for recipeProperty in list(recipeNode):
                tag_name = self.to_lower(recipeProperty.tag)

                if tag_name == "fermentables":
                    for fermentable_node in list(recipeProperty):
                        fermentable = Fermentable()
                        self.nodes_to_object(fermentable_node, fermentable)
                        recipe.fermentables.append(fermentable)

                elif tag_name == "yeasts":
                    for yeast_node in list(recipeProperty):
                        yeast = Yeast()
                        self.nodes_to_object(yeast_node, yeast)
                        recipe.yeasts.append(yeast)

                elif tag_name == "hops" or tag_name == "miscs":
                    for hop_node in list(recipeProperty):
                        hop = Hop()
                        self.nodes_to_object(hop_node, hop)
                        recipe.hops.append(hop)

                elif tag_name == "style":
                    style = Style()
                    recipe.style = style
                    self.nodes_to_object(recipeProperty, style)

                elif tag_name == "mash":

                    for mash_node in list(recipeProperty):
                        mash = Mash()
                        recipe.mash = mash

                        if self.to_lower(mash_node.tag) == "mash_steps":
                            for mash_step_node in list(mash_node):
                                mash_step = MashStep()
                                self.nodes_to_object(mash_step_node, mash_step)
                                mash.steps.append(mash_step)
                        else:
                            self.nodes_to_object(mash_node, mash)

                else:
                    self.node_to_object(recipeProperty, recipe)

        return recipes
示例#23
0
文件: sftext.py 项目: LukeMS/sftext
    def parse_text(self):
        self.parsed = []
        scr_w = self.screen_rect.width

        self.default_style = Style.default_style
        self.default_style['font_obj'] = self.fonts.load(
            self.default_style['font'], self.default_style['size'])
        self.default_style['w'], self.default_style['h'] = (
            self.default_style['font_obj'].size(' '))

        y = 0
        for line in self.text.splitlines():
            x = 0
            for style in line.split("{style}"):

                text, styled_txt = Style.split(style)

                self.set_font(styled_txt)
                font = styled_txt['font_obj']

                w, h = styled_txt['w'], styled_txt['h'] = font.size(' ')
                # determine the amount of space needed to render text

                wraps = self.wrap_text(text, scr_w, x, styled_txt)

                for wrap in wraps:
                    rect = pygame.Rect((0, 0), font.size(wrap['text']))

                    if (x + wrap['w1'] + w * 3) > scr_w:
                        x = 0
                        y += wrap['h']

                    if len(wraps) == 1 and wrap['align'] == 'center':
                        rect.midtop = (self.screen_rect.centerx,
                                       self.screen_rect.bottom + y)
                    else:
                        rect.topleft = (x + w * 3, self.screen_rect.bottom + y)
                    wrap['rect'] = rect
                    wrap['x'] = x
                    wrap['y'] = y
                    if False:
                        print("\n{}: {},".format('x', wrap['x']), end='')
                        print("{}: {},".format('y', wrap['y']), end='')
                        print("{}: {},".format('w', wrap['w']), end='')
                        print("{}: {}".format('h', wrap['h']))
                        print(wrap['text'])
                    self.parsed.append(wrap)

                    x += wrap['w1']
            y += wrap['h']
        # exit()
        print('done parsing')

        self.start_y = 0 - self.screen_rect.h + self.default_style['h']

        self.y = int(self.start_y)

        self.end_y = (-sum(p['h'] for p in self.parsed if p['x'] == 0) -
                      self.default_style['h'] * 2)
示例#24
0
    def GetMessageObject(self):
        if self.raw is not None:
            if isinstance(self.raw, basestring):
                return json.loads(self.raw)
            else:
                return self.raw

        message = {}
        message['title'] = self.title
        message['content'] = self.content

        # TODO: check custom
        message['custom_content'] = self.custom

        acceptTimeObj = self.GetAcceptTimeObject()
        if None == acceptTimeObj:
            return None
        elif acceptTimeObj != []:
            message['accept_time'] = acceptTimeObj

        if self.type == MESSAGE_TYPE_ANDROID_NOTIFICATION:
            if None == self.style:
                style = Style()
            else:
                style = self.style

            if isinstance(style, Style):
                message['builder_id'] = style.builderId
                message['ring'] = style.ring
                message['vibrate'] = style.vibrate
                message['clearable'] = style.clearable
                message['n_id'] = style.nId
                message['ring_raw'] = style.ringRaw
                message['lights'] = style.lights
                message['icon_type'] = style.iconType
                message['icon_res'] = style.iconRes
                message['style_id'] = style.styleId
                message['small_icon'] = style.smallIcon
            else:
                # style error
                return None

            if None == self.action:
                action = ClickAction()
            else:
                action = self.action

            if isinstance(action, ClickAction):
                message['action'] = action.GetObject()
            else:
                # action error
                return None
        elif self.type == MESSAGE_TYPE_ANDROID_MESSAGE:
            pass
        else:
            return None

        return message
示例#25
0
def day_data(workbook: xlsxwriter.Workbook, company: str,
             conn: sqlite3.Connection) -> None:
    """
    写入日数据的主函数

    参数:
        workbook: xlsxwriter.Workbook,用于确认数据写入的工作簿
        company: str,机构名称

    返回值:
        无
    """

    logging.info("开始写入日数据统计表")

    # 设置全局变量
    global name
    global wb
    global ws
    global nrow
    global ncol
    global sy
    global idate

    # 对部分全局变量进行初始化
    wb = workbook
    name = company
    sy = Style(wb)
    idate = IDate(2020)

    table_name = f"{name}日数据统计表"
    ws = wb.add_worksheet(table_name)

    # 需要统计的险种信息
    risks = ["整体", "车险", "人身险", "财产险", "非车险"]

    # 记录快捷菜单栏的项目信息
    menu = []

    # 写入数据统计表并记录快捷菜单栏不同快捷菜单的锚信息和现实文本信息
    for risk in risks:
        menu.append((nrow, f"{risk}"))
        # 写入表头
        header_write(risk=risk)
        # 写入表数据
        data_write(risk=risk, conn=conn)

    # 写入快捷菜单栏
    menu_write(table_name=table_name, menu=menu)

    nrow = 1
    ncol = 0
    # 冻结快捷工具条所在行(第一行)
    ws.freeze_panes(row=nrow, col=ncol + 1, top_row=1, left_col=1)

    # 设置列宽
    ws.set_column(first_col=ncol, last_col=ncol, width=10)
    ws.set_column(first_col=ncol + 1, last_col=ncol + 25, width=13)
示例#26
0
    def __init__(self, wb: xlsxwriter.Workbook, name: str,
                 conn: sqlite3.Connection):
        """
        初始化基础变量

            参数:
                wb:
                    xlsxwriter.Workbook, 需要写入数据的工作簿
                name:
                    str, 机构名称
        """

        # 工作薄对象
        self._wb = wb

        # 工作表对象
        self._ws: xlsxwriter.worksheet = None

        # 机构名称
        self._name = name

        # 数据库连接对象
        self._conn = conn

        # 数据库操作的游标对象
        self._cur = self._conn.cursor()

        # 数据库内数据的最大日期
        self._idate = IDate(year=2020)

        self._style = Style(wb=self.wb)

        # 行计数器
        self.nrow: int = 5

        # 列计数器
        self.ncol: int = 0

        # 操作的工作表名称
        self._table_name: str = None

        # 设置菜单的锚和文本信息
        self._menu: list = []

        # 首列的列名称
        self._first_col_name: str = None

        # 表个第一行表头的信息
        self.set_header_row_1()

        # 表个第二行表头的信息
        self._header_row_2: list = None

        # 当前正在操作的险种名称
        self._risk: str = None

        # 需要统计的险种名称列表
        self._risks: list = []
示例#27
0
    def __ping_peers(self):
        """
        Ping all peers
        Sends 'ping' sys message to all peers, checking for 'pong' response
        """
        # create ping message instance
        message = Message('', 'SYSTEM', msg_body='ping')
        # save time of ping
        ping_time = math.floor(time.time())
        # ping each connected client
        for connection in self.connections:
            # send ping message
            connection.send(message.get_encoded())

        # wait ping timeout seconds
        time.sleep(1)

        # check which peers pong'ed back
        dead_peers = []
        for peer_id, peer_data in self.peer.get_chat_peers().items():
            # get the last successful ping time of loop peer
            last_successful_ping = peer_data['last_successful_ping']
            # if the last successful ping response was earlier than this ping started
            if last_successful_ping < ping_time:
                # they didn't pong back, so they're inactive
                dead_peers.append(peer_id)

        # for each inactive peer
        for peer_id in dead_peers:
            # remove them from the chat peers list
            self.peer.remove_chat_peer(peer_id)

            # broadcast disconnect message (including remaining chat members)
            msg_body = 'output:' + (
                Style.error('- ' + peer_data['username'] + ' disconnected') +
                Style.info(' [Chat Members: ' + self.peer.get_chat_peers_str() + ']')
            )
            disconnect_msg = Message('', 'SYSTEM', msg_body)
            for connection in self.connections:
                # send disconnect message to each connected client
                connection.send(disconnect_msg.get_encoded())

        # send the remaining peers list to each client
        self.__send_peers()
示例#28
0
    def __start(self, ip: str, port: int):
        """
        Start the server.
        Binds the server to the given server address on init.

        :param str ip: server ip to bind too
        :param int port: server port to bind too
        """

        # create a socket for the server as an IPv4 (AF_INET) using byte streams (SOCK_STREAM)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # allow the socket to reuse addresses already in use so that when
        # running program multiple times, the socket address does not need to be changed
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # bind the server to the param server address
        sock.bind((ip, port))
        # start TCP listener for server socket
        sock.listen()

        # tell peer their server is running successfully, and on which address
        print(Style.info(f'Your server is listening for connections on {ip}:{port}.'))

        # continuously waiting for clients to connect to server
        while True:
            # on connect, extract the clients socket and their address
            client_socket, client_addr = sock.accept()

            # print(Style.info(f'A new peer [{client_addr[0]}:{client_addr[1]}] connected via your server'))

            # if servers peer is coordinator, handle connection
            if self.peer.is_coordinator():
                # add client to list of connected clients
                self.connections.append(client_socket)

                # tell peer connection succeeded
                msg_body = 'connected'
                message = Message('', 'SYSTEM', msg_body)
                client_socket.send(message.get_encoded())

                # create dedicated thread to start receiving messages from connecting client
                client_thread = threading.Thread(target=self.receive, args=(client_socket, ))
                # client thread is a daemon as it shouldn't prevent program from exiting
                client_thread.daemon = True
                # start the thread
                client_thread.start()

                # create thread to ping all peers and send updated list to connected clients
                ping_thread = threading.Thread(target=self.__ping_peers)
                ping_thread.daemon = True
                ping_thread.start()
            else:
                # this server isn't coordinator, so tell peer coordinator address to connect too
                msg_body = 'coordinator:' + json.dumps(self.peer.get_chat_coord())
                message = Message('', 'SYSTEM', msg_body)
                client_socket.send(message.get_encoded())
示例#29
0
def test():
    """open file
    """
    style = Style.load('data/style.xml')
    infos = LineInfo.load('data/0001.xml')

    line_map = LineMap()
    line_map.draw(infos, style, Span(-1, 0, -1))
    #line_map.draw(infos, style, Span(0, -1))
    line_map.mainloop()
示例#30
0
def Serve_Can():

    os.system('clear')

    Message.config_apply('config_data.json', 'r')

    channel = 'can0'
    bitrate = '125000'
    canbus = CAN(channel, bitrate).bus

    buffer = {}
    style = Style()

    timeout = 30

    try:
        while True:

            #moves cursor in position X:0 ,Y:0
            os.system(" printf '\033[0;0H ' ")
            print("\033[31m CHANNEL --> {}  Bitrate --> {} bit/sec ".format(
                channel, bitrate))
            #Receives Can bus messages (blocking function )
            msg = canbus.recv(timeout)

            #timeout seconds passed without a message
            if msg is None:
                print('No message was received')

        #Message recieved and exists inside our buffer
            elif msg.arbitration_id in buffer:

                buffer[msg.arbitration_id].msg = msg

                buffer[msg.arbitration_id].incr()

                buffer[msg.arbitration_id].get_timestamp()

                buffer[msg.arbitration_id].cycle_timer()

                id = str(hex(msg.arbitration_id))

                buffer[msg.arbitration_id].data_handle(id)

        #New message received create new Message class
            else:
                buffer[msg.arbitration_id] = Message(msg)

        #Print content
            for message in buffer:
                buffer[message].dynamic_Print()
    except:
        os.system('clear')
        print("Error in main loop or signal for stop   ")
        os.system('sudo ifconfig can0 down')
示例#31
0
    def test1():
        from image import Image
        from painter import Painter
        from geo import Vect, Rect
        from style import Style, Frame
        from sdl_painter import SdlPainter

        im = Image('frame.png')
        f = Frame(im)
        style = Style()
        style.background = f

        p = Painter(SdlPainter())

        l = Label(None, 'hello', style=style)
        l.rect = Rect((0, 0), (1, 1))
        l.draw(p)

        p.flip()

        raw_input()
示例#32
0
 def __init__(self,fileCode):
     file = FileScroller(fileCode)
     generateTokenCsvFile()
     self.lexicalObject = LexicalAnalysis(file)
     self.lexicalObject.switchState(0)
     self.tokenListObject = TokenList(self.lexicalObject.tokens)
     self.showCode(fileCode=fileCode)
     self.tokenListCompile()
     self.deleteDelimToken()
     print(Style.customHeader('Error and Pass Tokens during compile'))
     print('\n')
     SyntaxAnalysis(self.tokenListObject)
示例#33
0
文件: sftext.py 项目: LukeMS/sftext
    def __init__(self, text, font_path='.', style=None):

        if isinstance(text, bytes):
            # print('text is', bytes)
            self.text = text.decode('utf-8')
        elif isinstance(text, str):
            # print('text is', str)
            self.text = text

        self.fonts = resources.Fonts(path=font_path)

        if style:
            Style.set_default(style)

        self.screen = pygame.display.get_surface()
        self.screen_rect = self.screen.get_rect()
        self.bg = self.screen.copy()

        print('parsing text')
        self.parse_text()
        print('done parsing')
示例#34
0
文件: sftext.py 项目: LukeMS/sftext
    def __init__(self, text, font_path='.', style=None):

        if isinstance(text, bytes):
            # print('text is', bytes)
            self.text = text.decode('utf-8')
        elif isinstance(text, str):
            # print('text is', str)
            self.text = text

        self.fonts = resources.Fonts(path=font_path)

        if style:
            Style.set_default(style)

        self.screen = pygame.display.get_surface()
        self.screen_rect = self.screen.get_rect()
        self.bg = self.screen.copy()

        print('parsing text')
        self.parse_text()
        print('done parsing')
示例#35
0
class Element(object):
    """ Generic SVG element """
    def __init__(self, content=None, parent=None):
        self._parent = parent
        self._id = hex(id(self))
        self._style = Style()
        self._computed_style = Style()

        if isinstance(content, str):
            return

        self._id = content.get('id', self._id)
        self._style.update(content.get("style",None))
        self._computed_style = Style()
        if parent and parent.style:
            self._computed_style = copy.copy(parent.style)
            self._computed_style.update(content.get("style",None))


    @property
    def root(self):
        if self._parent:
            return self._parent.root
        return self

    @property
    def parent(self):
        if self._parent:
            return self._parent
        return None

    @property
    def style(self):
        return self._computed_style

    @property
    def viewport(self):
        if self._parent:
            return self._parent.viewport
        return None
示例#36
0
class Element(object):
    """ Generic SVG element """
    def __init__(self, content=None, parent=None):
        self._parent = parent
        self._id = hex(id(self))
        self._style = Style()
        self._computed_style = Style()

        if isinstance(content, str):
            return

        self._id = content.get('id', self._id)
        self._style.update(content.get("style", None))
        self._computed_style = Style()
        if parent and parent.style:
            self._computed_style = copy.copy(parent.style)
            self._computed_style.update(content.get("style", None))

    @property
    def root(self):
        if self._parent:
            return self._parent.root
        return self

    @property
    def parent(self):
        if self._parent:
            return self._parent
        return None

    @property
    def style(self):
        return self._computed_style

    @property
    def viewport(self):
        if self._parent:
            return self._parent.viewport
        return None
示例#37
0
文件: example.py 项目: LukeMS/sftext
from style import Style

mystyle = {
    # At the momment only font filenames are supported. That means the font
    # must be in the same directory as the main script.
    # Or you could (should?) use a resource manager such as
    'font': 'Fontin.ttf',
    'size': 20,
    'indent': 0,
    'bold': False,
    'italic': False,
    'underline': False,
    'color': (128, 144, 160),  # RGB values
    'align': 'left',
    # if a separate file should be used for italic/bold, speciy it;
    # if not, use None
    'separate_italic': 'Fontin-Italic.ttf',
    'separate_bold': 'Fontin-Bold.ttf'
}

Style.set_default(mystyle)
bold_specific_font_text = Style.stylize("{bold True}Boldy!")
print('\n"{}"'.format(bold_specific_font_text))
示例#38
0
文件: test.py 项目: LukeMS/sftext
    # if a separate file should be used for italic/bold, speciy it;
    # if not, use None
    'separate_italic': 'Fontin-Italic.ttf',
    'separate_bold': 'Fontin-Bold.ttf'
}

mystring = ("Hello World!")

# you can start with an already formatted string
print()
print("This is our test text:")
print('"{}"'.format(mystring))

# you can format plain text with a given style or the default one
print("\nThis is our text with style:")
newstring = Style.stylize(mystring, old_style)
print('"{}"'.format(newstring))

# Style.split returns a string without its style and a separate style dict
text, newstyle = Style.split(newstring)
print("\nThe style format is a dictionary like this one:")
pprint(newstyle)
print("\nThis is formatted text with its style removed.")
print("It shoul be equal to the text we started with.")
print('"{}"'.format(text))
assert(text == mystring)
assert(newstyle == old_style)

newstyle['color'] = (255, 255, 255)
newstyle['size'] = 18
# you can set a default style from a dict
示例#39
0
def addOOoStandardStyles(styles):
    style = Style(name="Standard", family="paragraph", attributes={'class':"text"})
    styles.addElement(style)

    style = Style(name="Text_20_body", displayname="Text body", family="paragraph", parentstylename="Standard", attributes={'class':"text"})
    p = ParagraphProperties(margintop="0cm", marginbottom="0.212cm")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Text_20_body_20_indent", displayname="Text body indent", family="paragraph", parentstylename="Text_20_body", attributes={'class':"text"})
    p = ParagraphProperties(marginleft="0.499cm", marginright="0cm", textindent="0cm", autotextindent="false")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Salutation", family="paragraph", parentstylename="Standard", attributes={'class':"text"})
    p = ParagraphProperties(numberlines="false", linenumber=0)
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Signature", family="paragraph", parentstylename="Standard", attributes={'class':"text"})
    p = ParagraphProperties(numberlines="false", linenumber=0)
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Heading", family="paragraph", parentstylename="Standard", nextstylename="Text_20_body", attributes={'class':"text"})
    p = ParagraphProperties(margintop="0.423cm", marginbottom="0.212cm", keepwithnext="always")
    style.addElement(p)
    p = TextProperties(fontname="Nimbus Sans L", fontsize="14pt", fontnameasian="DejaVu LGC Sans", fontsizeasian="14pt", fontnamecomplex="DejaVu LGC Sans", fontsizecomplex="14pt")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Heading_20_1", displayname="Heading 1", family="paragraph", parentstylename="Heading", nextstylename="Text_20_body", attributes={'class':"text"}, defaultoutlinelevel=1)
    p = TextProperties(fontsize="115%", fontweight="bold", fontsizeasian="115%", fontweightasian="bold", fontsizecomplex="115%", fontweightcomplex="bold")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Heading_20_2", displayname="Heading 2", family="paragraph", parentstylename="Heading", nextstylename="Text_20_body", attributes={'class':"text"}, defaultoutlinelevel=2)
    p = TextProperties(fontsize="14pt", fontstyle="italic", fontweight="bold", fontsizeasian="14pt", fontstyleasian="italic", fontweightasian="bold", fontsizecomplex="14pt", fontstylecomplex="italic", fontweightcomplex="bold")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Heading_20_3", displayname="Heading 3", family="paragraph", parentstylename="Heading", nextstylename="Text_20_body", attributes={'class':"text"}, defaultoutlinelevel=3)
    p = TextProperties(fontsize="14pt", fontweight="bold", fontsizeasian="14pt", fontweightasian="bold", fontsizecomplex="14pt", fontweightcomplex="bold")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="List", family="paragraph", parentstylename="Text_20_body", attributes={'class':"list"})
    styles.addElement(style)

    style = Style(name="Caption", family="paragraph", parentstylename="Standard", attributes={'class':"extra"})
    p = ParagraphProperties(margintop="0.212cm", marginbottom="0.212cm", numberlines="false", linenumber="0")
    style.addElement(p)
    p = TextProperties(fontsize="12pt", fontstyle="italic", fontsizeasian="12pt", fontstyleasian="italic", fontsizecomplex="12pt", fontstylecomplex="italic")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Index", family="paragraph", parentstylename="Standard", attributes={'class':"index"})
    p = ParagraphProperties(numberlines="false", linenumber=0)
    styles.addElement(style)

    style = Style(name="Source_20_Text", displayname="Source Text", family="text")
    p = TextProperties(fontname="Courier", fontnameasian="Courier", fontnamecomplex="Courier")
    style.addElement(p)
    styles.addElement(style)

    style = Style(name="Variable", family="text")
    p = TextProperties(fontstyle="italic", fontstyleasian="italic", fontstylecomplex="italic")
    style.addElement(p)
    styles.addElement(style)
示例#40
0
文件: dml.py 项目: nnog/dml
            exec s
            setattr(transformer, name, types.MethodType(_userfunc, transformer))

    if len(pyheaders) >= 1:
        for s in pysections:
            exec s
            if preparse != preparse_funcs[-1]:
                preparse_funcs.append(preparse)
            if postparse != postparse_funcs[-1]:
                postparse_funcs.append(postparse)

    #Construct grammar from combined grammar source
    grammar = Grammar(grammarsrc);
    
    #Process styles from combined style source
    styles = Style(stylesrc)
    tikzpicture_env_options = styles.get(elem='tikzpicture', override=tikzpicture_env_options)
    
    #Apply sequence of preparse functions
    for prefunc in preparse_funcs:
        source = prefunc(source)

    #Make substitutions
    docpreamble = docpreamble.replace('%_document_class_%', document_class)
    docpreamble = docpreamble.replace('%_document_class_options_%', document_class_options)
    docpreamble = docpreamble.replace('%_tikz_package_options_%', tikz_package_options)
    docpreamble = docpreamble.replace('%_tikz_libraries_%', ','.join(tikz_libraries))
    docpreamble = docpreamble.replace('%_additional_preamble_%', additional_preamble)
    tikzheader = tikzheader.replace('%_tikzpicture_env_options_%', tikzpicture_env_options)

    if arg.lex:
示例#41
0
def get_style():
    style = Style()
    style.h1_template = update_from_cookie_and_post(style.h1_template, 'h1_template')
    style.h2_template = update_from_cookie_and_post(style.h2_template, 'h2_template')
    style.footer      = update_from_cookie_and_post(style.footer, 'footer')
    return style
示例#42
0
文件: theme.py 项目: obspy/branches
#
# glydget is  distributed in the hope that  it will be useful,  but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy  of the GNU General Public License along with
# glydget. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
''' Graphic style '''
from style import Style
import state

none = [0,0,0,0]

# --- Debug ---
debug = Style()
debug.font_size = 12
debug.halign = 0.5
debug.colors[state.default]              = [255,255,255,255]
debug.foreground_colors[state.default]   = [255,255,255,50]*8
debug.background_colors[state.default]   = [255,255,255,50]*4
debug.colors[state.focused]              = [255,255,255,255]
debug.foreground_colors[state.focused]   = [255,255,255,100]*8
debug.background_colors[state.focused]   = [255,255,255,100]*4
debug.colors[state.activated]            = [255,255,255,255]
debug.foreground_colors[state.activated] = [255,255,255,150]*8
debug.background_colors[state.activated] = [255,255,255,150]*4


# --- Default ---
default = Style()
示例#43
0
文件: drawable.py 项目: 251/shaape
 def __init__(self, options = []):
     self.__style = Style([], '', [])
     self.__z_order = 0
     self.__options = options
     return
示例#44
0
文件: sftext.py 项目: LukeMS/sftext
    def parse_text(self):
        self.parsed = []
        scr_w = self.screen_rect.width

        self.default_style = Style.default_style
        self.default_style['font_obj'] = self.fonts.load(
            self.default_style['font'], self.default_style['size'])
        self.default_style['w'], self.default_style['h'] = (
            self.default_style['font_obj'].size(' '))

        y = 0
        for line in self.text.splitlines():
            x = 0
            for style in line.split("{style}"):

                text, styled_txt = Style.split(style)

                self.set_font(styled_txt)
                font = styled_txt['font_obj']

                w, h = styled_txt['w'], styled_txt['h'] = font.size(' ')
                # determine the amount of space needed to render text

                wraps = self.wrap_text(text, scr_w, x, styled_txt)

                for wrap in wraps:
                    rect = pygame.Rect((0, 0), font.size(wrap['text']))

                    if (x + wrap['w1'] + w * 3) > scr_w:
                        x = 0
                        y += wrap['h']

                    if len(wraps) == 1 and wrap['align'] == 'center':
                        rect.midtop = (
                            self.screen_rect.centerx,
                            self.screen_rect.bottom + y)
                    else:
                        rect.topleft = (
                            x + w * 3,
                            self.screen_rect.bottom + y)
                    wrap['rect'] = rect
                    wrap['x'] = x
                    wrap['y'] = y
                    if False:
                        print("\n{}: {},".format('x', wrap['x']), end='')
                        print("{}: {},".format('y', wrap['y']), end='')
                        print("{}: {},".format('w', wrap['w']), end='')
                        print("{}: {}".format('h', wrap['h']))
                        print(wrap['text'])
                    self.parsed.append(wrap)

                    x += wrap['w1']
            y += wrap['h']
        # exit()
        print('done parsing')

        self.start_y = 0 - self.screen_rect.h + self.default_style['h']

        self.y = int(self.start_y)

        self.end_y = (
            -sum(p['h'] for p in self.parsed if p['x'] == 0)
            - self.default_style['h'] * 2)
示例#45
0
 def paint(self,painter): # this is what should be re-implemented if custom painting is wanted
     Style.paintWidget(painter, self)
示例#46
0
 def __init__(self):
     self.__style = Style([], '', [])
     self.__z_order = 0
     return
示例#47
0
    def createTableAnalysisOfDetailedQuotation(self, conn, series, dateList, colNum, rowNum):
        colHeight = {'title': 13.5, 'thead': 13.5, 'content': 13.5}

        fieldnameList = settings.fieldList
        style = Style()
        style.setFont('宋体', 11, True, 'FFFFFF')
        style.setPatternFill('5B9BD5')
        self.setRow(colNum, rowNum, fieldnameList, style, colHeight['title'])

        fieldnameStr = ''
        for i in range(len(fieldnameList)):
            if len(fieldnameStr) > 0:
                fieldnameStr += ' , '
            fieldnameStr += fieldnameList[i]
        cursor = conn.cursor()
        values = [series]
        wheresql = ' where carseries_name = :1 '
        values.append(dateList[len(dateList)-1].strftime('%Y-%m-%d'))
        wheresql += ' and crawl_date = :1 '
        sql = 'select ' + fieldnameStr + ' from price_report ' + wheresql
        cursor.execute(sql, values)
        result = cursor.fetchall()
        cursor.close()
        if len(result) <= 0:
            print ('    没有' + dateList[len(dateList)-1].strftime('%Y-%m-%d') + '的数据').encode('gbk')
            return -1
        print '    写入'.encode('gbk')+str(len(result))+'行数据'.encode('gbk')
        odd_style = Style()
        odd_style.setFont('宋体', 11, False, '000000')
        even_style = Style()
        even_style.setFont('宋体', 11, False, '000000')
        even_style.setPatternFill('DDEBF7')

        rowNum += 1
        for row in result:
            if rowNum % 2 == 1:
                self.setRow(colNum, rowNum, row, odd_style, colHeight['content'])
                if rowNum%100 == 0 :
                    print '      第'.encode('gbk')+str(rowNum-1)+'数据'.encode('gbk')
            else:
                self.setRow(colNum, rowNum, row, even_style, colHeight['content'])
                if rowNum%100 == 0:
                    print '      第'.encode('gbk')+str(rowNum-1)+'数据'.encode('gbk')
            rowNum += 1
        return rowNum