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)
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))
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
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'])
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]
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
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)
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 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
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') ]
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)
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)
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])
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
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
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 = []
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)
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
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()
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')
def __init__(self, master=None): self.style = Style() self.cardframe_list = {} self.master = master self.master.configure(bg=self.style.navbar_color) self.navbar_frame = Frame(self.master, bg=self.style.navbar_color) self.navbar_frame.pack(fill=X, pady=10) self.status_frame = Frame( self.master, bg=self.style.status_color) self.status_frame.pack(side=BOTTOM, fill=X) self.content_frame = Frame( self.master, bg=self.style.content_color) self.content_frame.pack(fill=BOTH, expand=True) self.status_label = Label( self.status_frame, bg=self.style.status_color, text='Press Play to Start') self.status_label.pack() self.mouse_button = Button( self.navbar_frame, image=self.style.mouse_icon, relief=FLAT, bg=self.style.navbar_color) self.mouse_button.bind("<ButtonRelease-1>", self.add_cardframe_mouse) self.mouse_button.pack(side=LEFT) self.keyboard_button = Button(self.navbar_frame, image=self.style.keyboard_icon, relief=FLAT, bg=self.style.navbar_color) self.keyboard_button.bind( "<ButtonRelease-1>", self.add_cardframe_keyboard) self.keyboard_button.pack(side=LEFT) self.time_button = Button( self.navbar_frame, image=self.style.time_icon, relief=FLAT, bg=self.style.navbar_color) self.time_button.bind("<ButtonRelease-1>", self.add_cardframe_time) self.time_button.pack(side=LEFT) self.play_button = Button( self.navbar_frame, image=self.style.play_icon, relief=FLAT, bg=self.style.navbar_color) self.play_button.bind("<ButtonRelease-1>", self.play) self.play_button.pack(side=RIGHT) self.stop_button = Button( self.navbar_frame, image=self.style.pause_icon, relief=FLAT, bg=self.style.navbar_color) self.stop_button.bind("<ButtonRelease-1>", self.teste) self.stop_button.pack(side=RIGHT)
def _processAssemblyShapes(self): """ """ try: shapes = self._footprint['layout']['assembly']['shapes'] except: return for shape_dict in shapes: layers = shape_dict.get('layer') or ['top'] for layer in layers: shape = Shape(shape_dict) style = Style(shape_dict, 'assembly') shape.setStyle(style) self._shapes['assembly'][layer].append(shape)
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
def _getOutline(self): """ Process the module's outline shape. Modules don't have to have an outline defined, so in that case return None. """ shape = None outline_dict = self._module_dict.get('outline') if outline_dict != None: shape_dict = outline_dict.get('shape') if shape_dict != None: shape = Shape(shape_dict) style = Style(shape_dict, 'outline') shape.setStyle(style) return shape
def set_style(self, stylesheet): if not stylesheet: return attrs = self.attrs tags = [u'', self.tag] if 'class' in attrs: x = attrs['class'] tags += [ t+'.'+x for t in tags ] if 'id' in attrs: x = attrs['id'] tags += [ t+'#'+x for t in tags ] (style, contexts) = stylesheet.lookup(tags, self.parent['_contexts']) self.attrs['_contexts'] = contexts if 'style' in attrs: style = Style(style) parse_inline(style, attrs['style']) self.attrs['_style'] = style return
def run(self, raw_data, objects): options_start = -1 for i in range(0, len(raw_data)): if raw_data[i].find('options:') == 0: options_start = i break if options_start > -1: raw_data.append('\n') options = yaml.load(''.join(raw_data[options_start+1:-1])) priority = 0 for item in options: names = item.keys()[0] for (target_type, option) in item[names].items(): objects.append(Style(names, target_type, option, priority)) priority = priority + 1 self._parsed_data = raw_data[0:options_start] else: self._parsed_data = raw_data self._objects = objects return
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()
def _processPours(self): """ """ try: shapes = self._footprint['layout']['pours']['shapes'] except: return for shape_dict in shapes: layers = utils.getExtendedLayerList(shape_dict.get('layers') or ['top']) for layer in layers: shape = Shape(shape_dict) style = Style(shape_dict, 'conductor', 'pours') shape.setStyle(style) try: self._shapes['pours'][layer].append(shape) except: self._shapes['pours'][layer] = [] self._shapes['pours'][layer].append(shape)
def loadTheme(path): global default dom = plistlib.readPlist(open(path)) default = dom["settings"][0]["settings"] i=1 while i < len(dom["settings"]): setting = dom["settings"][i] i += 1 if not "scope" in setting: continue scopes = setting["scope"] for scope in scopes.split(","): m = re.search('^([\w\.]+)( -[^ ]+)+$', scope) if m: scope = m.group(1) name = scope.strip().lower() if name in names: name = names[name] fore = None back = None fontStyle = None if "foreground" in setting["settings"]: fore = setting["settings"]["foreground"] if "background" in setting["settings"]: back = setting["settings"]["background"] if "fontStyle" in setting["settings"]: fontStyle = setting["settings"]["fontStyle"] styles[name] = Style(name, fore, back, fontStyle)
def write_xlsx_cell(self, ws, node, row): '''Write cell to excel''' r, c = self.get_origin(node) row = r + row col = c + 1 cell = ws.cell(row=row, column=col) try: value = int(self.get_text(node)) except: value = self.get_text(node) if node.get('class') in CONF.TCCLS_HEAD and '/' in value: value = value.replace('/', '\n/') cell.value = value # Apply style cell_style = Style(self.get_css_td(node)) cell.font = cell_style.font cell.fill = cell_style.fill cell.border = cell_style.border cell.alignment = cell_style.alignment # Merge cells end_row = row + int(node.get('rowspan', 1)) - 1 end_col = col + int(node.get('colspan', 1)) - 1 ws.merge_cells(start_row=row, start_column=col, end_row=end_row, end_column=end_col) # Column width width = node.get('width') if width is not None: width = int(width) * 8.11 / 52 ws.column_dimensions[cell.column_letter].width = width