Best Python code snippet using molecule_python
base.py
Source:base.py
1import json2import plotly.graph_objects as go3from django.template.loader import render_to_string4from django.utils.safestring import mark_safe5from wagtail.core import blocks6from wagtail_json_widget.blocks import JSONBlock7from ..config import (8 DEFAULT_CONFIG_OPTIONS,9 DEFAULT_LAYOUT_OPTIONS,10 DEFAULT_TRACE_OPTIONS,11 INCLUDE_PLOTLYJS,12)13from ..utils import (14 get_layout, 15 get_config, 16 get_trace, 17 get_layout_choices18)19class BasePlotBlock(blocks.StructBlock):20 title = blocks.CharBlock(required=False)21 xaxis_title = blocks.CharBlock(required=False)22 yaxis_title = blocks.CharBlock(required=False)23 graph_layout = blocks.ChoiceBlock(required=False, choices=get_layout_choices)24 def get_rows(self, plot_data):25 """26 Get the rows from the table removing empty rows27 """28 return [row for row in plot_data if any(row)]29 def get_columns(self, plot_data):30 """31 Get the data from the table, transpose and filter32 """33 columns = list(zip(*plot_data)) if plot_data else []34 # Remove empty columns35 columns = [column for column in columns if any(column)]36 return columns37 def build_figure(self, data, layout, value):38 """39 Buld the figure from the data and layout and set axis labels40 """41 fig = go.Figure(42 data=data,43 layout=layout,44 )45 fig.update_layout(46 title=value.get('title', ''),47 xaxis_title=value.get('xaxis_title', ''),48 yaxis_title=value.get('yaxis_title', ''),49 )50 return fig51 def fig_to_html(self, fig, config_options):52 """53 Generate the markup for the plot54 """55 return mark_safe(56 fig.to_html(57 full_html=False,58 include_plotlyjs=INCLUDE_PLOTLYJS,59 config=config_options,60 )61 )62 def build_data(self, value):63 raise NotImplementedError('To be implemented in child class')64 def update_figure(self, fig, value):65 """66 An opportunity for subclasses to modify the figure after67 all other configurations have been applied.68 """69 return70 def render(self, value, context=None):71 """72 General render method for each plot73 """74 template = getattr(self.meta, 'template', None)75 if not template or not value:76 return self.render_basic(value or '', context=context)77 data = self.build_data(value)78 # Create a layout traces with layout options provided or default79 graph_layout = value.get('graph_layout')80 layout_options = get_layout(graph_layout) or DEFAULT_LAYOUT_OPTIONS81 config_options = get_config(graph_layout) or DEFAULT_CONFIG_OPTIONS82 trace_options = get_trace(graph_layout) or DEFAULT_TRACE_OPTIONS83 layout = go.Layout(**layout_options)84 fig = self.build_figure(data, layout, value)85 fig.update_traces(**trace_options)86 self.update_figure(fig, value)87 plot = self.fig_to_html(fig, config_options)88 ctx = {} if context is None else dict(context)89 ctx.update({'plot': plot})90 return render_to_string(template, ctx)91 class Meta:92 template = 'wagtail_plotly/blocks/plot.html'93 icon = 'table'94class CustomPlotMixin(blocks.StructBlock):95 96 custom = JSONBlock(required=False)97 def update_figure(self, fig, value):98 ob = self.get_custom_data(value)99 fig.update_layout(**ob.get('layout', {}))100 fig.update_traces(**ob.get('trace', {}))101 def get_custom_data(self, value):102 """103 Return a dict of the custom plotly data104 """...
yaml_utils.py
Source:yaml_utils.py
1import generic_processing_config as config_options2import yaml3import copy4DEFAULT_CONFIG_OPTIONS = config_options.CONFIGURATION_OPTIONS5def generate_config_file(fileNames, CONFIG_OPTIONS = None):6 output_json = dict()7 8 if CONFIG_OPTIONS:9 output_json = CONFIG_OPTIONS10 else:11 for file in fileNames:12 if CONFIG_OPTIONS == None:13 output_json[file] = DEFAULT_CONFIG_OPTIONS14 else:15 output_json[file] = CONFIG_OPTIONS16 yaml.Dumper.ignore_aliases = lambda *args : True17 with open(config_options.FILE_PATHS['CONFIG_FILE'], 'w') as outfile:18 yaml.dump(output_json, outfile)19# Know this code is bad, didn't have time to write it properly20def generate_config_options(df):21 config_options = copy.deepcopy(DEFAULT_CONFIG_OPTIONS)22 file_headers = list(df)23 possible_location_names = ["location_name", "country_nane", "country", "location"]24 matching_location_names = [b for b in file_headers if b.lower() in (a.lower() for a in possible_location_names)]25 if len(matching_location_names) > 0:26 config_options["COLUMN_MAPPINGS"]["location"] = matching_location_names[0]27 28 possible_aggregation_columns = ["val", "total", "sum", "value"]29 matching_aggregation_columns = [b for b in file_headers if b.lower() in (a.lower() for a in possible_aggregation_columns)]30 if len(matching_aggregation_columns) > 0:31 config_options["COLUMN_MAPPINGS"]["aggregation_columns"] = matching_aggregation_columns[0]32 if "year" in file_headers:33 config_options["COLUMN_MAPPINGS"]["year"] = str(df.year.max())34 config_options["CITATIONS"]["source_year"] = str(df.year.max())35 return config_options36def read_yaml():37 try:38 with open(config_options.FILE_PATHS["CONFIG_FILE"], 'r') as f:39 yaml_to_json = yaml.safe_load(f)40 return yaml_to_json41 except:...
config.py
Source:config.py
1import os2from pathlib import Path3host = os.getenv("INDICO_HOST", "app.indico.io")4url_protocol = os.getenv("INDICO_PROTOCOL", "https")5serializer = os.getenv("INDICO_SERIALIZER", "msgpack")6api_token_path = os.getenv("INDICO_API_TOKEN_PATH")7def resolve_api_token(path=None):8 path = path or api_token_path9 if path is None:10 path = "."11 if not isinstance(path, Path):12 path = Path(path)13 if not path.exists():14 path = Path.home()15 if not path.is_file():16 path = path / "indico_api_token.txt"17 if not path.exists():18 raise RuntimeError(19 "Expected indico_api_token.txt in current directory, home directory, "20 "or provided as indicoio.config.token_path"21 )22 with path.open("r") as f:23 return f.read().strip()24class RequestConfigMixin(object):25 def __init__(self, config_options=None):26 default_config_options = {27 "host": host,28 "protocol": url_protocol,29 "serializer": serializer,30 "short_lived_access_token": None,31 "request_session": None,32 "token_path": None,33 }34 config_options = config_options or {}35 for option, value in default_config_options.items():36 if option not in config_options:37 config_options[option] = value...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!