def build_legned(slider_val, dim): # ''' # Description: Creates the legend that displays the words that correspond to each topic. # Color coded to match the cluster color in the graph. # Params: Threshold slider value and the dimension of 2d or 3d. # Returns: List of words that correspond to each cluster. # ''' global cluster_obj leg = cluster_obj.make_legend() list_of_lis = [] for item, value in leg.items(): list_of_lis.append(html.Li(item, style={'color': value})) return list_of_lis
def Chapter(name, href=None, caption=None): linkComponent = html.A if href.startswith('http') else dcc.Link return html.Div([ html.Li( linkComponent( name, href=href, style={'paddingLeft': 0}, id=href ) ), html.Small(dcc.Markdown(s(caption or '')), style={ 'display': 'block', 'marginTop': '-10px' if caption else '' }) if caption else None ])
def __unwrap_section_and_points(self, section, points): layout = html.Div([ html.Div( html.H5( self.__format_string(section, self.data), style={"color": self.colors["subtitle"]}, )), html.Div( html.Ul([ html.Li(html.P(self.__format_string(item, self.data))) for item in points ]), style={"color": self.colors["text"]}, ), ]) return layout
def Chapter(name, href=None, caption=None): linkComponent = html.A if href.startswith('http') else dcc.Link return html.Div(className='toc--chapter', children=[ html.Li( linkComponent(name, href=relpath(href), id=href, className='toc--chapter-link'), ), html.Small(className='toc--chapter-content', children=Markdown(s(caption or '')), style={ 'display': 'block', 'marginTop': '-10px' if caption else '' }) if caption else None ])
def stats(solve_time: float, solution, cities: list, mean_time: float, input_time: int = 0, new: bool = True): """ Reusable component for solution statistics. Parameters ---------- solve_time: time of solving solution: Output object cities: list of Cities input_time: time provided in time.csv new: True if for a new solution (requires time.csv) Returns ------- html div """ if new: worked_time = input_time - solution.time_left time_left = solution.time_left else: worked_time = solution.time_left time_left = '?' return [ html.Div([ html.Li(html.P(f'Solving time: {solve_time:.4f}')), html.Li( html.P(f"Path: {', '.join([c.name for c in solution.path])}")), html.Li(html.P(f'Time worked: {worked_time}')), html.Li(html.P(f'Time left: {time_left}')), html.Li(html.P(f'Earned / total: {solution.total}')), html.Li( html. P(f'Mean quantity: {float(np.mean([c.value for c in cities])):.2f}' )), html.Li(html.P(f'Mean time: {mean_time:.2f}')), html.A('Download', href="/tmp/solution", target='blank', style={ 'font-size': '16pt', 'text-transform': 'uppercase' }) ]) ]
def build_layout(): return html.Div( [ nav.LAYOUT, dbc.Row(html.Hr(), style={'height': '3%'}), html.H2(children='Downloads', style={"text-align": "center"}), dbc.Row(html.Hr(), style={'height': '3%'}), html.Div(['Download tumor datasets as tab-separated files.']), dbc.Row(html.Hr(), style={'height': '3%'}), html.Ul( id="file-list", children=[html.Li(file_download_link(filename)) for filename in get_files()] ), footer.LAYOUT ], style={"padding-left": "10%", "padding-right": "10%", "width": "100%"} )
def get_fire_header(selected_fires): # TODO: handle multiple fires ? if len(selected_fires) >= 1: return [ dbc.Alert(children=[ html.Div("Fire{} represented in the graphs below:".format( "s" if len(selected_fires) > 1 else "")), html.Ul(children=[ html.Li(children=[html.Span(sf['flat_summary']['id'])]) for sf in selected_fires ]) ], color="secondary" ) ] return []
def upload_file(uploaded_filenames, uploaded_file_contents): upload_directory = 'static/upload/' if uploaded_filenames is not None and uploaded_file_contents is not None: for name, data in zip(uploaded_filenames, uploaded_file_contents): data = data.encode("utf8").split(b";base64,")[1] with open(os.path.join(upload_directory, name), "wb") as fp: fp.write(base64.decodebytes(data)) app.compass_module = Module.read_from_file( os.path.join(upload_directory, name)) bf = len(app.compass_module.biological_features) ss = len(app.compass_module.sample_sets) return [ html.Li("File uploaded!"), html. Li("The size is {bf} biological features and {ss} sample sets. Check the other Tabs!" .format(bf=bf, ss=ss)) ]
def serve_layout(_, user_key, __): builder = AnnotationBuilder(local=True) my_annotations = builder.get_annotations(user=user_key) children = [] for annotation in my_annotations: children.append(html.Li([ html.Span([token["text"] + " " for token in annotation.tokens[0]], style={"fontWeight": "bold"}), html.Br(), html.Span(annotation.doi), html.Span(" "), serve_ann_options(quote(annotation.doi, safe="")), html.Br(), html.Span(str(annotation.labels)) ])) return html.Div([html.H5("My Annotated Abstracts"), html.Ol(children)])
def fine_class_table(value, dropdown): datasets = json.loads(value) df_fine = pd.read_json(datasets['df_fine_class'], orient='split') df_fine = df_fine[df_fine['Variable'] == dropdown].drop( 'Variable', axis=1).reset_index() df_fine = df_fine.rename(columns={'index': 'Group'}) df_coarse = pd.read_json(datasets['df_coarse'], orient='split') df_coarse = df_coarse[df_coarse['Variable_name'] == dropdown].drop( 'Variable_name', axis=1).reset_index() df_coarse = df_coarse.drop( ['WoE_lag', 'var_lag', 'index', 'group_pct', 'WoE_diff', 'yes'], axis=1) return html.Div([ html.Li(), # ============================================================================= # dbc.Row([ # dbc.Col(dash_table.DataTable( # id='fine_table', # columns=[{"name": i, "id": i} for i in df_fine.columns], # data=df_fine.to_dict('records'), # ),md=6), # dbc.Col(dcc.Graph(id='fine_graph', # figure={"data": [{'x':df_fine['From/To'].values, # 'y':df_fine['WoE'].values, # 'type': 'bar', # 'name':'Coarse Classing'}]} # ),md=6), # ],align="center", justify="center"), # html.Li(), # dbc.Row([ # dbc.Col(dash_table.DataTable( # id='coarse_table', # columns=[{"name": i, "id": i} for i in df_coarse.columns], # data=df_coarse.to_dict('records'), # ),md=6), # dbc.Col(dcc.Graph(id='coarse_graph', # figure={"data": [{'x':df_coarse['From/To'].values, # 'y':df_coarse['WoE'].values, # 'type': 'bar', # 'name':'Coarse Classing'}]} # ),md=6), # ],align="center", justify="center"), # ============================================================================= ])
def set_vizier_list(n_clicks, radius, oid, dr): if n_clicks == 0: return '' if radius is None: return html.P('No radius is specified') radius = float(radius) ra, dec = find_ztf_oid.get_coord(oid, dr) table_list = find_vizier.find(ra, dec, radius) if len(table_list) == 0: return html.P( f'No vizier catalogs found within {radius} arcsec from {ra:.5f}, {dec:.5f}' ) records = [] lengths = [] for catalog, table in zip(table_list.keys(), table_list.values()): try: description = vizier_catalog_details.description(catalog) except NotFound: description = catalog n = len(table) n_objects = str(n) if n < find_vizier.row_limit else f'≥{n}' n_objects = f' ({n_objects} objects)' if n > LIST_MAXSHOW else '' r = sorted(table['_r']) if n > LIST_MAXSHOW: r = r[:LIST_MAXSHOW - 1] sep = ', '.join(f'{x}″' for x in r) if n > LIST_MAXSHOW: sep += ', …' url = find_vizier.get_catalog_url(catalog, ra, dec, radius) records.append(f'[{description}]({url}){n_objects}: {sep}') lengths.append(len(description) + len(n_objects) + 2 + len(sep)) ul_column_width = max(lengths) + 2 # for bullet symbol div = html.Div([ html.Ul([html.Li(dcc.Markdown(record)) for record in records], style={ 'columns': f'{ul_column_width}ch', 'list-style-type': 'none' }), ]) return div
def make_sidebar_children(data, top_item, inherited_class="", child_class=""): """ Recursively generate a hierarchical list defined by data, starting at top_item, using Ul and Li objects Ul and Li objects ids are defined by Dash id dicts so they can be subscribed to by a callback as a group For each node, we generate: * An Li object with children=item_name * (If node is a middle node with additional children) a Ul object with children=[child_nodes, built recursively] Args: data (dict): Dict of lists of relationships within the nested list. For example: { "Item-1": ["Item-1-1", "Item-1-2", ...], "Item-2": ["Item-2-1", "Item-2-2", ...], "Item-1-1": ["Item-1-1-1", "Item-1-1-2", ...], ... } Note that this does not handle repeated names (eg: Item-1-1 cannot have the same name as Item-2) top_item (str): The key in data that denotes the head of the hierarchy to generate inherited_class (str): HTML class name to apply once to all levels of the list child_class (str): HTML class name to apply once per step in the list (so Item 1-1 would have it once, Item 1-1-1 would have it twice, etc.). Useful for incrementing tab behaviour Returns: (list): List of html elements for use as the children attribute of a html.Ul """ this_className = f"{inherited_class} {child_class}" content = [] for name in data[top_item]: content.append(html.Li( children=name, id=generate_checklist_li_id(name), className=this_className, )) if name in data: nested_children = make_sidebar_children(data, name, inherited_class=this_className, child_class=child_class) content.append(html.Ul( id=generate_checklist_ul_id(name), children=nested_children, )) return content
def generate_carousel(): logger.debug("generate carousel") headline_services = app_controller.get_club_headline_service(CLUB_NAME) if not headline_services: print("no headline") return html.Div() service_count = len(headline_services) logger.debug("generate carouse al") logger.debug("service count " + str(service_count)) carousel = html.Div(**{"data-ride": "carousel"}, id="carouselExampleIndicators", className="carousel slide", children=[ html.Ol(className="carousel-indicators", children=[ html.Li(**{"data-target":"#carouselExampleIndicators", "data-slide-to":str(i)}, className="active" if i ==0 else "") for i in range(service_count) ]), html.Div(className="carousel-inner", children=[ html.Div(className="carousel-item active" if i ==0 else "carousel-item", children=[ html.Div(className="d-flex", children=[ dcc.Link(className="col",href="/service/book/{}".format(service.id), children=[ html.Img(className="img-fluid", src=filestore.get_service_img_link(service.id, MAJOR_IMG), alt="Second slide") ]), dcc.Link(className="col",href="/service/book/{}".format(service.id), children=[ html.Img(className="img-fluid", src=filestore.get_service_img_link_alt(service.id), alt="Second slide") ]) ]) ]) for i, service in enumerate(headline_services) ]), html.A(**{"data-slide":"prev"}, className="carousel-control-prev", href="#carouselExampleIndicators", role="button", children=[ html.Span(**{"aria-hidden":"true"}, className="carousel-control-prev-icon"), html.Span("Previous", className="sr-only") ]), html.A(**{"data-slide":"next"}, className="carousel-control-next", href="#carouselExampleIndicators", role="button", children=[ html.Span(**{"aria-hidden":"true"}, className="carousel-control-next-icon"), html.Span("Next", className="sr-only") ]), ]) logger.debug("return carousel") return carousel
def _largest_companies(self, c): largest_companies = {} count = 0 limit_largest = 10 for k in self.size_order[::-1]: top = [i for i in self.data if i["EmployerSize"] == k] if not top: continue largest_companies[k] = top count += len(largest_companies[k]) if count > limit_largest: break list_items = [] total_len = 0 for k, v in largest_companies.items(): original_len = len(v) len_left = limit_largest - total_len if len_left < 3: continue list_items.append( html.H4(className='f5', children='{} employees ({:,.0f})'.format( k, original_len))) if original_len > len_left: v = random.sample(v, len_left) v = sorted(v, key=lambda x: x["EmployerName"]) list_items.append( html.P('* showing a random sample of {} companies'.format( len_left))) list_items.append( html.Ul(className='list pl0', children=[ html.Li(className='f6 mv1 lh-copy', children=[ correct_titlecase(i["EmployerName"]) ]) for i in v ])) total_len += original_len return self.show_figure(html.Div(list_items), "Largest Companies")
def update_map(data): """ Callback mettant à jour la map après un click sur un département ou une ville """ global selected_dept, selected_city links = [ html.Li("Carte de France", className="selected", id="cdf-button"), ] city_locations = [] if data is not None and len(data["points"][0]["customdata"][0]) == 2: selected_dept = data["points"][0]["customdata"][0] # On update les graphs vote_histogram_dept.update(vote_dataset_dept, current_dept=selected_dept) vote_pie_dept.update(vote_dataset_dept, current_dept=selected_dept) # On Update la map locations = base_locations.copy() city_locations = load_dept(selected_dept) locations["features"] = list( filter(lambda x: not x["properties"]["code"] == selected_dept, locations["features"])) chloropeth_map.update(vote_dataset_dept, vote_dataset_city, locations, city_locations) chloropeth_map.generate_map() elif data is not None: selected_city = data["points"][0]["customdata"][0] # On update l'histogramme vote_histogram_city.update(vote_dataset_city, current_city=selected_city) vote_pie_city.update(vote_dataset_city, current_city=selected_city) # On met à jour les liens if selected_dept != "-1": links.append(html.Li("Info du département", id="idd-button")) else: links.append( html.Li("Info du département", id="idd-button", className="hide")) if selected_city != "-1": links.append(html.Li("Info de la ville", id="idv-button")) else: links.append( html.Li("Info de la ville", id="idv-button", className="hide")) links.append(html.Li("Synthèse de l'analyse", id="synth-button")) return (chloropeth_map.map_panel, links)
def build_loc_mode_hover_children(loc_mode): if loc_mode is None: return None loc_mode_cfg = LOC_MODE_INFO[loc_mode] return [ html.I(className='ico-help-outline', style=dict(color='white')), html.Div( [ html.Div([html.Span('View', className='mr-3'), loc_mode_cfg['url']]), html.Ul( [html.Li(e, style={'listStyleType': 'disc'}, className='mb-3') for e in loc_mode_cfg['examples']], className='pt-3 mb-0' ) ], className='hoverable__content build-code', style=dict(width='auto', whiteSpace='nowrap', left='-2em', top='auto') ) ]
def get_color_legend(): """ color legend beneath the table to identify meaning of highlights :return: unordered list with color information """ return html.Ul(children=[ html.Li("No data sent for 2 days", className='red'), html.Li("Sensor was not chosen", className='not-clean'), html.Li("Left study too early", className='blue'), html.Li("Study duration reached, not left", className='light-green'), html.Li("Study duration reached, left", className='dark-green'), html.Li("Multiple QR Codes of one user active", className='orange') ])
def get_breadcrumb(parts): if not parts: return html.Div() breadcrumbs = html.Nav( html.Ul( [ html.Li( dcc.Link(name, href=link), className=(None if idx != len(parts) - 1 else "is-active"), ) for idx, (name, link) in enumerate(parts.items()) ] ), className="breadcrumb", ) return breadcrumbs
def createCard( name="Placeholder", imageLink="https://via.placeholder.com/69", contList=["Placeholder", "Placeholder", "Placeholder"], ): contListHTML = [] for i in contList: contListHTML.append(html.Li(i)) card = dbc.Card(children=[ dbc.CardHeader(html.H4(name)), dbc.CardImg(src=imageLink), dbc.CardBody(children=[ html.H5("Contribution:"), html.Ul(children=contListHTML, className="card-text") ]) ], style={"width": "15rem"}) return card
def gen_navbar(brand, items, barClass='navbar-dark bg-dark p-1', brandClass='col-sm-3 col-md-2 mr-0', listClass='px-3', itemLiClass='text-nowrap', itemAClass=''): item_list = [] for key in items: item_list.append( html.Li(html.A(key, href=items[key], className=f"nav-link {itemAClass}"), className=f"nav-item {itemLiClass}")) return html.Nav([ html.A(brand, className=f"navbar-brand {brandClass}"), html.Ul(item_list, className=f"navbar-nav {listClass}") ], className=f"navbar {barClass}")
def update_output(n_clicks, value): indexer = Indexer() results = indexer.search(value) li_children = [] for no, result in enumerate(results, 1): url, title, snippet = result if title: li = html.Li(children=[ html.A(title, href=url), dcc.Markdown(children=snippet), ]) li_children.append(li) ol = html.Ol(children=li_children) return ol
def set_features_list(oid, dr, min_mjd, max_mjd): try: features = light_curve_features(oid, dr, min_mjd=min_mjd, max_mjd=max_mjd) except NotFound: return 'Not available' items = [ f'**{k}**: {v:.4g}' for k, v in sorted(features.items(), key=lambda item: item[0]) ] column_width = max(map(len, items)) - 2 div = html.Div( html.Ul([html.Li(dcc.Markdown(text)) for text in items], style={'list-style-type': 'none'}), style={'columns': f'{column_width}ch'}, ) return div
def get_wordcloud(hoverData): pers = hoverData["points"][0]["theta"] msg = df[df.Author == pers].reset_index(drop=True)["Message"] photo = df[df.Author == pers].reset_index(drop=True)["Photo"][0] X = vectorizer.fit_transform(msg) words = vectorizer.get_feature_names() #plt.figure(figsize=[7,7]) #wordcloud_ke = WordCloud( background_color="white", mode="RGBA", max_words=30, mask=mask).generate(" ".join(list(msg))) #fig=plt.imshow(wordcloud_ke .recolor(color_func=image_colors), interpolation="bilinear") #fig = mpl_to_plotly(fig) child = html.Div([ html.H3(children=pers), html.Img(src=photo, style={ 'height': '20%', 'width': '20%' }), html.Ul([html.Li(x) for x in words]) ]) return child
def _candidates_list(self): return self.show_figure( html.Ul( className='list pl0', children=[ html.Li(className= 'f6 mv1 lh-copy cf pa2 bg-light-gray near-black', children=[ html.Img(className='w3 fr person-photo', src=c["image_url"]) if c["image_url"] else None, html.Span(className='f5 b', children=c["name"]), html.Br(), html.Span(className='f6', children=c["party_name"]), ]) for c in self.data.get("candidates", []) ]), 'Candidates for 2019 Election')
def burn_into_video_button(n_clicks, store_s, selection, video_file_name): if store_s is None or n_clicks == 0: raise PreventUpdate video_file = Path(f"{APP_DATA_DIR}/{video_file_name}") video_subs_file_name = ( f"{Path(video_file_name).stem}_{'_'.join(selection)}_subs.mp4") def select(sb: SubtitleBlock, selection): sb.name_texts = [(n, t) for n, t in sb.name_texts if n in selection] return sb subtitle_blocks = [ select(SubtitleBlock(**d), selection) for d in json.loads(store_s) ] with NamedTemporaryFile(suffix=".ass") as f: create_ass_file( subtitle_blocks, f.name, styles={name: StyleConfig(fontsize=10.0) for name in selection}, ) subprocess.check_output( f"/usr/bin/ffmpeg -y -i '{video_file}' -vf ass={f.name} '{APP_DATA_DIR}/{video_subs_file_name}'", shell=True, ) return [ html.H5(f"{video_subs_file_name}"), html.Video( controls=True, id="movie_player", src=f"/files/{video_subs_file_name}", autoPlay=False, style={"width": "100%"}, ), html.Li( html.A( "download video-file", href=f"/download/{urlquote(video_subs_file_name)}", )), ]
def get_layout(nav_items=[]): # create navigation layout return html.Nav(children=[ html.Button('×', className='close-nav bg-transparent border-0 col-white'), html.A(html.Img( src='/assets/images/logo_1.png', height=50, ), href='/', className='d-block text-center my-2'), html.Ul(children=[ html.Li(html.A(children=nav_item['label'], href=nav_item['target'])) for nav_item in nav_items ]), html.Form( children=[ html.Button( children=[ dbc.Row(children=[ dbc.Col(children=[ html.B(current_user.get_username()), html.Span('Logout') ], className='d-flex flex-column p-0'), dbc.Col(children=[ html.Span(html.I(className='fa fa-user-circle', **{'aria-hidden': True}), className='m-auto') ], className='d-flex flex-column pr-0') ], className='m-auto') ], type='submit', className='bg-black col-white border-0 logout-button px-0') ], action='/logout', method='post', ) ], id='sidebar')
def most_sales_prod(): most_sales = df.groupby(['product', 'year'])['quantity'].sum().reset_index() most_sales_top = most_sales.sort_values(by=['quantity'], ascending=False).iloc[0:10] return html.Div([ html.H4('Most Selling Products', style={ 'text-align': 'center', 'color': 'white' }), html.Ul(children=[html.Li(i) for i in most_sales_top['product']], style={ 'textAlign': 'left', 'color': '#839496', 'fontSize': 18, 'height': '333px', 'padding-top': '15px' }) ])
def change_card_content(value): html_key = df_work.iloc[value - 1, :]["location_key"] src = './assets/{}.html'.format(html_key) return [ dbc.CardHeader(df_work.iloc[value - 1, :]["time"]), dbc.CardBody([ html.H4(df_work.iloc[value - 1, :]["company"], className="card-title"), html.P(df_work.iloc[value - 1, :]["Role"], className="card-title", style={"fontSize": "1.171875rem"}), html.P( df_work.iloc[value - 1, :]["location"], className="card-text", ), ]), ], [ html.Li([string], className="ul") for string in df_work.iloc[value - 1, :]["Experience"].split("\n") ], src
def render_article_links(pathname): response = requests.get( 'https://www.cnblogs.com/feffery/tag/Dash/', headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36' }) tree = etree.HTML(response.text) posts = [(href, title.strip()) for href, title in zip( tree.xpath("//div[@class='postTitl2']/a/@href"), tree.xpath("//div[@class='postTitl2']/a/span/text()"))] return [ html.Li( dcc.Link(title, href=f'/article-{href.split("/")[-1]}', target='_blank')) for href, title in posts ]
def getFooter(app): return dbc.Row( [ dbc.Col( [ html.B('Business Problem:'), html.P('Nowadays industry and government have a need of selecting and' + \ ' knowing the skills and potential of their future collaborators.'), html.B('Data:'), html.P('Pruebas Saber Pro from the Colombian Institute for Tertiary Education' + \ ' Fomentation (ICFES).' ), html.H5('DS4A advisors:'), html.P('German Prieto - [email protected], Jimmy Jing ' + \ ' - [email protected] ') ], md=6 ), # fin de dbc.Col dbc.Col( [ html.B('Participants'), html.Ul( [ html.Li('Alfonso Cervantes Barragán ([email protected])'), html.Li('Rafael García ([email protected])'), html.Li('Luis Guzmán ([email protected])'), html.Li('Julián Rincón ([email protected])'), html.Li('Jorge Vélez ([email protected])'), html.Li('Ricardo Villanueva ([email protected])'), html.Li('Eduardo Zurek ([email protected])') ] ) ## fin de html.UL ], md=6 ) # fin de dbc.Col ], style={'padding': '10px', 'color': 'white', 'background-color': 'black'} ) # fin de dbc.Row