Exemple #1
0
def init_widgets():
    global widgets
    widgets = WrapBokeh(PAGE_URL, app.logger)

    widgets.add(
        "tin_fname",
        TextInput(title="First Name:",
                  placeholder="first name",
                  css_classes=['tin_fname']))
    widgets.add(
        "tin_lname",
        TextInput(title="Last Name:",
                  placeholder="last name",
                  css_classes=['tin_lname']))
    widgets.add("b_submit", Button(label="Submit", css_classes=['b_submit']))

    countries = [('', 'Select Country')] + [(x, x) for x in geo_info.keys()]
    states = [('', 'Select State')] + [(x, x)
                                       for x in geo_info["United States"]]

    widgets.add(
        "sel_country",
        Select(options=countries,
               value=None,
               title="Select Country",
               css_classes=['sel_country']))
    widgets.add(
        "sel_state",
        Select(options=states,
               value=None,
               title="Select State",
               css_classes=['sel_state']))

    widgets.add(
        "sel_nexturl",
        Select(options=[('99', 'Select Next Page'), ('0', 'Home'),
                        ('1', 'Ajax Stream Example'), ('3', 'Page C'),
                        ('4', 'Page D')],
               value=None,
               title="Select URL",
               css_classes=['sel_nexturl']))

    widgets.init()
Exemple #2
0
    def __init__(self, layout):
        self.__layout = layout
        self.__selected = []
        self.__file_list = self.__get_eurostats()

        geojson_data = {'id': [], 'lvl': []}
        for file in self.__file_list:
            if file['geojson']['nuts1']['exists']:
                geojson_data['id'].append(file['id'])
                geojson_data['lvl'].append(1)

            if file['geojson']['nuts2']['exists']:
                geojson_data['id'].append(file['id'])
                geojson_data['lvl'].append(2)

            if file['geojson']['nuts3']['exists']:
                geojson_data['id'].append(file['id'])
                geojson_data['lvl'].append(3)
        self.__geojson_table_source = ColumnDataSource(geojson_data)
        geojson_table_columns = [
            TableColumn(field='lvl', title='NUTS Level'),
            TableColumn(field='id', title='ID')
        ]
        self.geojson_table = DataTable(source=self.__geojson_table_source,
                                       columns=geojson_table_columns,
                                       width=300,
                                       height=500,
                                       selectable=True)

        convert_button = Button(label="Convert to GeoJSON",
                                button_type="success")
        convert_button.on_click(self.transform)
        self.__endpoint_input = TextInput(placeholder="SPARQL Endpoint")
        self.__graph_input = TextInput(placeholder="Graph")
        self.__layout.children[1] = column(self.__endpoint_input,
                                           self.__graph_input, convert_button)
        self.__layout.children[2] = column(self.geojson_table)
def empty_plot():
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        height=FIGURE_HEIGHT,
        responsive=True,
        tags=["clusterPlot"],
        min_border_bottom=MIN_BORDER_BOTTOM,
        min_border_top=MIN_BORDER_TOP,
        min_border_left=MIN_BORDER_LEFT,
        min_border_right=MIN_BORDER_RIGHT,
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False))

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    but_relevant = Button(label="Relevant", type="success")
    but_irrelevant = Button(label="Irrelevant", type="success")
    but_neutral = Button(label="Neutral", type="success")
    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_select = Select(value="Custom tags", options=["Custom tags"])
    but_backward_crawl = Button(label="Backlinks", type="success")
    but_forward_crawl = Button(label="Forwardlinks", type="success")

    tags = hplot(but_relevant,
                 but_irrelevant,
                 but_neutral,
                 custom_tag_input,
                 custom_tag_select,
                 height=40)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vform(p, tags, tags_crawl)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
Exemple #4
0
seed_check_text = ""
all_selected_phrases = []
search_flag = False
max_phrase_length = 40
clear_flag = False
expand_columns = [
    TableColumn(field="res", title="Results"),
    TableColumn(field="score", title="Score"),
]
empty_table = {"res": 15 * [""], "score": 15 * [""]}
checkbox_label = "Show extracted term groups" if grouping else "Show extracted phrases"

# create ui components

seed_input_title = "Please enter a comma separated seed list of terms:"
seed_input_box = TextInput(title=seed_input_title, value="", width=450, css_classes=["seed-input"])
annotation_input = TextInput(
    title="Please enter text to annotate:",
    value="",
    width=400,
    height=80,
    css_classes=["annotation-input"],
)
annotation_output = Div(text="", height=30, width=500, style={"padding-left": "35px"})
annotate_button = Button(
    label="Annotate", button_type="success", width=150, css_classes=["annotation-button"]
)
group_info_box = Div(text="", height=30, css_classes=["group-div"])
search_input_box = TextInput(title="Search:", value="", width=300)
expand_button = Button(
    label="Expand", button_type="success", width=150, css_classes=["expand-button"]
Exemple #5
0
def login_recover():

    w = WrapBokeh(PAGE_URL, logger)

    w.add(
        "tin_uname_only",
        TextInput(title="User Name:",
                  placeholder="",
                  css_classes=['tin_uname_only']))
    w.add(
        "tin_email_only",
        TextInput(title="Email:",
                  placeholder="",
                  css_classes=['tin_email_only']))
    w.add("b_submit", Button(label="Submit", css_classes=['b_submit']))
    w.add("b_ok", Button(label="Ok", css_classes=['b_ok']))

    w.init()

    # Create a dominate document, see https://github.com/Knio/dominate
    # this line should go after any "return redirect" statements
    w.dominate_document()
    url_page_css(w.dom_doc, PAGE_URL)

    args, _redirect_page_metrics = w.process_req(request)
    if not args: return _redirect_page_metrics
    logger.info("{} : args {}".format(PAGE_URL, args))
    left_margin = int(int(args.get("windowWidth", 800)) * 0.2)

    if args.get("b_ok", False): return redirect(COMMON_URL_INDEX)

    redir, url = index_menu_redirect(args)
    if redir: return redirect(url)

    failed_credentials_match = False
    recovery_email_sent = False
    error_fields = {}
    submitted = args.get("b_submit", False)
    if submitted:
        validated, error_fields = User.validate(args)
        if validated:
            # uname, email format is valid, now lets see if it exists
            user = User.get_username(args.get("tin_uname_only"))
            if user in [None, []] or user.email != args.get("tin_email_only"):
                logger.error(
                    "Invalid username/pw ({}/{}) for login recovery".format(
                        user.username, args.get("tin_email_only")))
                failed_credentials_match = True

            if not failed_credentials_match:
                logger.info("user validated, sending recovery email")
                temp_pw = "12345"  # FIXME: make a random password

                # TODO: send email

                User.update(original_username=user.username,
                            first=user.fname,
                            last=user.lname,
                            username=user.username,
                            password=temp_pw,
                            email=user.email)
                recovery_email_sent = True

    doc_layout = layout(sizing_mode='scale_width')
    index_toolbar_menu(w, doc_layout, args)

    doc_layout = layout(sizing_mode='scale_width')

    # show error fields... if any
    if submitted and not validated:
        for key, value in error_fields.items():
            error = User.get_form_error_handle_from_err(
                key, value[0])  # process first error only
            w.add_css(key, error["css"])
            w.get(key).title = error.get('msg', "!NO MSG!")

    if recovery_email_sent:
        doc_layout.children.append(
            row([
                Spacer(width=left_margin),
                Div(text="""<h1>An Email has been sent!</h1>""")
            ]))
        doc_layout.children.append(
            row([Spacer(width=left_margin),
                 w.get("b_ok")]))

    elif failed_credentials_match:
        doc_layout.children.append(
            row([
                Spacer(width=left_margin),
                Div(text=
                    """<h1>Those credentials did not match a known user.</h1>""",
                    height=150)
            ]))
        doc_layout.children.append(
            row([Spacer(width=left_margin),
                 w.get("b_ok")]))

    else:
        w.add_css("tin_uname_only", {'input': {'width': '90%'}})
        w.add_css("tin_email_only", {'input': {'width': '90%'}})

        wbox = widgetbox(w.get("tin_uname_only"), w.get("tin_email_only"),
                         w.get("b_submit"))
        doc_layout.children.append(row([Spacer(width=left_margin), wbox]))

    return w.render(doc_layout)
def common__login():

    w = WrapBokeh(PAGE_URL, logger)

    w.add(
        "tin_uname",
        TextInput(title="Login Name:",
                  placeholder="",
                  css_classes=['tin_lname']))
    w.add(
        "tin_lpw",
        PasswordInput(title="Password:"******"",
                      css_classes=['tin_lpw']))
    w.add("b_submit", Button(label="Submit", css_classes=['b_submit']))
    w.add("b_signup", Button(label="Sign Up", css_classes=['b_signup']))
    w.add("b_recover",
          Button(label="Recover Password", css_classes=['b_recover']))

    w.init()

    # Create a dominate document, see https://github.com/Knio/dominate
    # this line should go after any "return redirect" statements
    w.dominate_document(title=session["title"])
    url_page_css(w.dom_doc, PAGE_URL)

    args, _redirect_page_metrics = w.process_req(request)
    if not args: return _redirect_page_metrics
    logger.info("{} : args {}".format(PAGE_URL, args))
    left_margin = int(int(args.get("windowWidth", 800)) * 0.1)

    redir, url = index_menu_redirect(args)
    if redir: return redirect(url)

    if args.get("b_signup", False): return redirect(COMMON_URL_LOGIN_SIGNUP)
    if args.get("b_recover", False): return redirect(COMMON_URL_LOGIN_RECOVER)

    login_failed = False
    if args.get("b_submit", False):
        uname = args.get("tin_uname", None)
        pw = w.get("tin_lpw").value

        if uname is not None and pw is not None:
            user = User.login(uname, pw)
            if user is not None:
                logger.info("{} {}".format(user.username, user.id))
                session['user_id'] = user.id
                login(user.id)
                return redirect(COMMON_URL_LAND)
            else:
                logger.info("Login failed for {}".format(uname))
                login_failed = True

    doc_layout = layout(sizing_mode='scale_width')
    index_toolbar_menu(w, doc_layout, args)

    if login_failed:
        doc_layout.children.append(
            row(
                Spacer(width=left_margin),
                column([
                    Div(text="""<p>Login failed, Recover Password?</p>"""),
                    w.get("b_recover")
                ])))

    w.add_css("b_submit",
              {'button': {
                  'background-color': '#98FB98',
                  'min-width': '60px'
              }})
    w.add_css("b_signup",
              {'button': {
                  'background-color': '#98FB98',
                  'min-width': '60px'
              }})
    w.add_css("tin_uname", {'input': {'width': '90%'}})
    w.add_css("tin_lpw", {'input': {'width': '90%'}})

    if app.config["app"]["user"]["signup_enabled"]:
        wbox = widgetbox(w.get("tin_uname"), w.get("tin_lpw"),
                         w.get("b_submit"), w.get("b_signup"))
    else:
        wbox = widgetbox(w.get("tin_uname"), w.get("tin_lpw"),
                         w.get("b_submit"))

    doc_layout.children.append(row([Spacer(width=left_margin), wbox]))

    return w.render(doc_layout)
Exemple #7
0
context_df = df.groupby(['attr_value']).agg({'id':'count'}).rename(columns={'id':'n'})

# setup attribute table
table_df = df[df.attr_name==selected_attribute].groupby(['attr_value']).agg({'id':'count'})
table_df = table_df.sort_values(by='id', ascending=False).rename(columns={'id':'n'})
joined_df = calculate_ratio(table_df)
table_source = ColumnDataSource(joined_df)
table_source_column = [TableColumn(field="attr_value", title="Attribute Value"),TableColumn(field="n", title="Counts"),TableColumn(field="ratio", title="Ratio"),]
table_data_table = DataTable(source=table_source, columns=table_source_column, width=400, height=800)

# setup dropdowns
main_dropdown = Select(title="Chart Attributes", options=attributes_name, value=selected_attribute)
table_dropdown = Select(title="Histogram Attributes", options=attributes_name, value=selected_attribute)

# setup text input
threshold_input = TextInput(value=str(threshold), title="Threshold:")

# setup layout
layout_left = VBox(main_scatter_plot, main_dropdown)
layout_right = VBox(HBox(table_dropdown,threshold_input), table_data_table)
layout = HBox(layout_left,layout_right)

def update_threshold_callback(attr_name, old, new):
    global threshold
    threshold=int(new)
    update_table()

# update main chart
def update_main_callback(attr_name, old, new):
    filtered_df = df[(df.attr_rank==0) & (df.attr_name==new) & (df.attr_rank==0)]
    for column in filtered_df:
Exemple #8
0
seed_check_text = ''
all_selected_phrases = []
search_flag = False
max_phrase_length = 40
clear_flag = False
expand_columns = [
    TableColumn(field="res", title="Results"),
    TableColumn(field="score", title="Score")
]
empty_table = {'res': 15 * [''], 'score': 15 * ['']}

# create ui components

seed_input_title = 'Please enter a comma separated seed list of terms:'
seed_input_box = TextInput(title=seed_input_title,
                           value="",
                           width=450,
                           css_classes=["seed-input"])
group_info_box = Div(text='', height=30, css_classes=["group-div"])
search_input_box = TextInput(title="Search:", value="", width=300)
expand_button = Button(label="Expand", button_type="success", width=150)
clear_seed_button = Button(label="Clear",
                           button_type="success",
                           css_classes=['clear_button'],
                           width=50)
export_button = Button(label="Export",
                       button_type="success",
                       css_classes=['export_button'],
                       width=100)
expand_table_source = ColumnDataSource(data=empty_table)
expand_table = DataTable(source=expand_table_source,
                         columns=expand_columns,
Exemple #9
0
def common__account_add():

    # TODO: This needs to be a decorator
    if not session.get('user_id', False): return redirect(COMMON_URL_LOGIN)
    user = User.get_by_id(session['user_id'])
    if user is None or not RolesUsers.user_has_role(user,
                                                    ["ADMIN", "ADD-USER"]):
        # this should never happen... logout if it does...
        logger.error("Unable to find user id {}".format(session['user_id']))
        session.pop('user_id', None)
        redirect(COMMON_URL_INDEX)

    w = WrapBokeh(PAGE_URL, logger)

    w.add(
        "tin_fname",
        TextInput(title="First Name:",
                  placeholder="",
                  css_classes=['tin_fname']))
    w.add(
        "tin_lname",
        TextInput(title="Last Name:",
                  placeholder="",
                  css_classes=['tin_lname']))
    w.add(
        "tin_uname",
        TextInput(title="User Name:",
                  placeholder="",
                  css_classes=['tin_uname']))
    w.add(
        "tin_lpw",
        PasswordInput(title="Password:"******"",
                      css_classes=['tin_lpw']))
    w.add(
        "tin_lpw_confirm",
        PasswordInput(title="Confirm Password:"******"",
                      css_classes=['tin_lpw_confirm']))
    w.add("tin_email",
          TextInput(title="Email:", placeholder="", css_classes=['tin_email']))
    w.add("b_submit", Button(label="Submit", css_classes=['b_submit']))

    w.init()

    # Create a dominate document, see https://github.com/Knio/dominate
    # this line should go after any "return redirect" statements
    w.dominate_document()
    url_page_css(w.dom_doc, PAGE_URL)

    args, _redirect_page_metrics = w.process_req(request)
    if not args: return _redirect_page_metrics
    logger.info("{} : args {}".format(PAGE_URL, args))

    redir, url = toolbar_menu_redirect(args)
    if redir: return redirect(url)

    error_fields = {}
    submitted = args.get("b_submit", False)
    if submitted:
        validated, error_fields = User.validate(args)

    # on submit, validate form contents, show errors...
    if submitted and validated:
        logger.info("validated: {}".format(args))
        User.add(first=args["tin_fname"],
                 last=args["tin_lname"],
                 username=args["tin_uname"],
                 password=args["tin_lpw"],
                 email=args["tin_email"])
        return redirect(COMMON_URL_ACCOUNT_ADD)

    doc_layout = layout(sizing_mode='scale_width')
    page_toolbar_menu(w, doc_layout, args, user)

    # show error fields... if any
    if submitted and not validated:
        for key, value in error_fields.items():
            error = User.get_form_error_handle_from_err(
                key, value[0])  # process first error only
            w.add_css(key, error["css"])
            w.get(key).title = error.get('msg', "!NO MSG!")

    w.add_css("tin_fname", {'input': {'width': '90%'}})
    w.add_css("tin_lname", {'input': {'width': '90%'}})
    w.add_css("tin_uname", {'input': {'width': '90%'}})
    w.add_css("tin_lpw", {'input': {'width': '90%'}})
    w.add_css("tin_lpw_confirm", {'input': {'width': '90%'}})
    w.add_css("tin_email", {'input': {'width': '90%'}})

    wbox = widgetbox(w.get("tin_fname"), w.get("tin_lname"),
                     w.get("tin_uname"), w.get("tin_lpw"),
                     w.get("tin_lpw_confirm"), w.get("tin_email"),
                     w.get("b_submit"))
    left_margin = int(int(args.get("windowWidth", 800)) * 0.2)
    doc_layout.children.append(row([Spacer(width=left_margin), wbox]))

    return w.render(doc_layout)
def login_signup():

    w = WrapBokeh(PAGE_URL, logger)

    w.add(
        "tin_fname",
        TextInput(title="First Name:",
                  placeholder="",
                  css_classes=['tin_fname']))
    w.add(
        "tin_lname",
        TextInput(title="Last Name:",
                  placeholder="",
                  css_classes=['tin_lname']))
    w.add(
        "tin_uname",
        TextInput(title="User Name:",
                  placeholder="",
                  css_classes=['tin_uname']))
    w.add(
        "tin_lpw",
        PasswordInput(title="Password:"******"",
                      css_classes=['tin_lpw']))
    w.add(
        "tin_lpw_confirm",
        PasswordInput(title="Confirm Password:"******"",
                      css_classes=['tin_lpw_confirm']))
    w.add("tin_email",
          TextInput(title="Email:", placeholder="", css_classes=['tin_email']))
    w.add("b_submit", Button(label="Submit", css_classes=['b_submit']))

    w.init()

    # Create a dominate document, see https://github.com/Knio/dominate
    # this line should go after any "return redirect" statements
    w.dominate_document()
    url_page_css(w.dom_doc, PAGE_URL)

    args, _redirect_page_metrics = w.process_req(request)
    if not args: return _redirect_page_metrics
    logger.info("{} : args {}".format(PAGE_URL, args))

    redir, url = index_menu_redirect(args)
    if redir: return redirect(url)

    error_fields = {}
    submitted = args.get("b_submit", False)
    if submitted:
        validated, error_fields = User.validate(args)

    # on submit, validate form contents, show errors...
    if submitted and validated:
        logger.info("validated: {}".format(args))
        User.add(first=args["tin_fname"],
                 last=args["tin_lname"],
                 username=args["tin_uname"],
                 password=args["tin_lpw"],
                 email=args["tin_email"])
        return redirect(COMMON_URL_INDEX)

    doc_layout = layout(sizing_mode='scale_width')
    index_toolbar_menu(w, doc_layout, args)

    # show error fields... if any
    if submitted and not validated:
        for key, value in error_fields.items():
            error = User.get_form_error_handle_from_err(
                key, value[0])  # process first error only
            w.add_css(key, error["css"])
            w.get(key).title = error.get('msg', "!NO MSG!")

    w.add_css("tin_fname", {'input': {'width': '90%'}})
    w.add_css("tin_lname", {'input': {'width': '90%'}})
    w.add_css("tin_uname", {'input': {'width': '90%'}})
    w.add_css("tin_lpw", {'input': {'width': '90%'}})
    w.add_css("tin_lpw_confirm", {'input': {'width': '90%'}})
    w.add_css("tin_email", {'input': {'width': '90%'}})

    wbox = widgetbox(w.get("tin_fname"), w.get("tin_lname"),
                     w.get("tin_uname"), w.get("tin_lpw"),
                     w.get("tin_lpw_confirm"), w.get("tin_email"),
                     w.get("b_submit"))
    left_margin = int(int(args.get("windowWidth", 800)) * 0.2)
    doc_layout.children.append(row([Spacer(width=left_margin), wbox]))

    return w.render(doc_layout)
def selection_plot(response):
    # Let's move these into a settings file somewhere?
    # height/width could potentially be driven by the request?


    # Include color data in the ColumnDataSource to allow for changing the color on
    # the client side.
    urls = [x[0] for x in response["pages"]]
    xdata = [x[1] for x in response["pages"]]
    ydata = [x[2] for x in response["pages"]]
    tags = [x[3] for x in response["pages"]]
    color = []
    custom_tags = ["Custom tags"]
    
    for tag in tags:
        custom = False
        if tag:
            for t in tag:
                if t not in ["Relevant", "Irrelevant", ""]:
                    custom = True
                    if t not in custom_tags:
                        custom_tags.append(t)
            if not custom:    
                color.append(colormap(tag[0]))
            else:
                color.append(colormap("Custom"))
        else:
            color.append(colormap(None))

    source = ColumnDataSource(
        data=dict(
            x=xdata,
            y=ydata,
            urls=urls,
            tags=tags,
            color=color,
        )
    )
    # Callback code for CDS.
    source.callback = CustomJS(code="""
        var inds = cb_obj.get('selected')["1d"].indices;
        var data = cb_obj.get('data');
        BokehPlots.showPages(inds);
    """)


    # Create the figure with FIGURE_WIDTH and FIGURE_HEIGHT
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        responsive=True,
        tags=["clusterPlot"],
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(
        LassoSelectTool(select_every_mousemove=False),
    )

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    p.circle("x", "y", size=13, line_width=2, line_alpha=1,
            line_color=None, fill_alpha=1, color='color', source=source,
            name="urls")
    nonselected_circle = Circle(fill_alpha=0.1, line_alpha=0.1, fill_color='color',
            line_color='color')
    renderer = p.select(name="urls")
    renderer.nonselection_glyph = nonselected_circle


    # Create buttons and their callbacks, use button_code string for callbacks.
    button_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        tag = "%s";
        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                selected: true,
                possible: false,
            });
            data["color"][inds[i]] = "%s";
        }
        BokehPlots.updateTags(selected, tag, "Apply");
        source.trigger("change");
    """

    textinput_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        var tag = cb_obj.get("value");

        // Reinitialise to the default value
        cb_obj.set("value", "Add custom tag...")

        if(tag.indexOf("Add custom tag...") < 0) {
        //Update the custom tags selection list 
        var options = custom_tags_select.get("options");
        if(options.indexOf(tag) < 0){
            options.push(tag);
            custom_tags_select.set("options", options);
        }

        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                selected: true,
                possible: false,
            });
            data["color"][inds[i]] = "%s";
        }
        BokehPlots.updateTags(selected, tag, "Apply");
        source.trigger("change");
        }
    """

    selectinput_code = """
    event.preventDefault();
    var inds = source.get('selected')["1d"].indices;
    var data = source.get('data');
    var selected = [];
    var tag = cb_obj.get("value");    

    cb_obj.set("value", "Enter tags...")
    if(tag.indexOf("Add custom tag...") < 0) {
    for(var i = 0; i < inds.length; i++){
         selected.push({
            x: data.x[inds[i]],
            y: data.y[inds[i]],
            url: data.urls[inds[i]],
            tags: data.tags[inds[i]],
            selected: true,
            possible: false,
         });
         data["color"][inds[i]] = "%s";
    }
    BokehPlots.updateTags(selected, tag, "Apply");
    source.trigger("change");
    }
    """

    # Create buttons and their callbacks, use button_code string for callbacks.
    crawl_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        var crawl = '%s';
        for(var i = 0; i < inds.length; i++){
            selected.push(data.urls[inds[i]]);
        }
        BokehPlots.crawlPages(selected, crawl);
        source.trigger("change");
    """

    # Supply color with print formatting.
    but_relevant = Button(label="Relevant", type="success")
    but_relevant.callback = CustomJS(args=dict(source=source),
                    code=button_code % ("Relevant", POSITIVE_COLOR))

    but_irrelevant = Button(label="Irrelevant", type="success")
    but_irrelevant.callback = CustomJS(args=dict(source=source),
                    code=button_code % ("Irrelevant", NEGATIVE_COLOR))

    but_neutral = Button(label="Neutral", type="success")
    but_neutral.callback = CustomJS(args=dict(source=source),
                    code=button_code % ("Neutral", NEUTRAL_COLOR))

    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_input.callback = CustomJS(args=dict(source=source),
                    code=textinput_code % (CUSTOM_COLOR))
    
    custom_tag_select = Select(value="Custom tags", options=custom_tags)
    custom_tag_select.callback = CustomJS(args=dict(source=source),
                    code=selectinput_code % (CUSTOM_COLOR))
    custom_tag_input.callback.args["custom_tags_select"] = custom_tag_select

    but_backward_crawl = Button(label="Backlinks", type="success")
    but_backward_crawl.callback = CustomJS(args=dict(source=source),
                                           code=crawl_code % ("backward"))

    but_forward_crawl = Button(label="Forwardlinks", type="success")
    but_forward_crawl.callback = CustomJS(args=dict(source=source),
                                          code=crawl_code % ("forward"))

    
    # Adjust what attributes are displayed by the HoverTool
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
        ("urls", "@urls"),
    ]
    tags = hplot(custom_tag_input, custom_tag_select,  but_neutral, but_relevant, but_irrelevant)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vplot(p, tags, tags_crawl)
    
    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
Exemple #12
0
    #Should have validation that input from form is valid
    api_url = api_url + txt.value

    req = urllib.request.Request(api_url)
    s = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    response = urllib.request.urlopen(req, context=s)
    data = json.JSONDecoder().decode(response.read().decode('UTF-8'))

    erecord = data['metadata']['electronic_location_and_access'][0]
    #Only looks at first file, no validation
    url = erecord['uniform_resource_identifier']

    rawframe = pandas.read_csv(url, sep=',', header=1)
    new_data = dict(x=rawframe.index.values,\
            y=rawframe[list(rawframe)[0]])

    p.title.text = erecord['electronic_name'][0]
    #Reads only first column, hard coding

    source.data = new_data


# add a button widget and configure with the call back
txt = TextInput(placeholder="Type 208 or 209")
button = Button(label="Press Me")
button.on_click(callback)

# put the button and plot in a layout and add to the document
column = column(p, txt, button)
curdoc().add_root(column)
def selection_plot(response, tag_colors):
    # Let's move these into a settings file somewhere?
    # height/width could potentially be driven by the request?

    # Include color data in the ColumnDataSource to allow for changing the color on
    # the client side.

    urls = [x[0] for x in response["pages"]]
    xdata = [x[1] for x in response["pages"]]
    ydata = [x[2] for x in response["pages"]]
    tags = [x[3] for x in response["pages"]]
    color = []
    custom_tags = ["Custom tags"]

    for tag in tags:
        if tag:
            t = tag[len(tag) - 1]
            if t not in ["Relevant", "Irrelevant", ""]:
                if t not in custom_tags:
                    custom_tags.append(t)
                if ((tag_colors != None) and (t in tag_colors["colors"])):
                    color.append(tag_colors["colors"][t])
                else:
                    color.append(colormap("Custom"))
            else:
                color.append(colormap(t))
        else:
            color.append(colormap(None))

    if tag_colors != None:
        for tag in tag_colors["colors"].keys():
            if tag not in custom_tags:
                custom_tags.append(tag)

    source = ColumnDataSource(data=dict(x=xdata,
                                        y=ydata,
                                        urls=urls,
                                        tags=tags,
                                        color=color,
                                        custom_tags=custom_tags))
    # Callback code for CDS.
    source.callback = CustomJS(code="""
        var inds = cb_obj.get('selected')["1d"].indices;
        var data = cb_obj.get('data');
        BokehPlots.addCustomTags(data['custom_tags']);
        BokehPlots.showPages(inds);
    """)

    # Create the figure with FIGURE_WIDTH and FIGURE_HEIGHT
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        height=FIGURE_HEIGHT,
        responsive=True,
        tags=["clusterPlot"],
        min_border_bottom=MIN_BORDER_BOTTOM,
        min_border_top=MIN_BORDER_TOP,
        min_border_left=MIN_BORDER_LEFT,
        min_border_right=MIN_BORDER_RIGHT,
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False), )

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    p.circle("x",
             "y",
             size=13,
             line_width=2,
             line_alpha=1,
             line_color=None,
             fill_alpha=1,
             color='color',
             source=source,
             name="urls")
    nonselected_circle = Circle(fill_alpha=0.1,
                                line_alpha=0.1,
                                fill_color='color',
                                line_color='color')
    renderer = p.select(name="urls")
    renderer.nonselection_glyph = nonselected_circle

    # Create buttons and their callbacks, use button_code string for callbacks.
    button_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        tag = "%s";
        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                color: data.color[inds[i]],
                selected: true,
                possible: false,
            });
        }
        BokehPlots.updateTags(selected, tag, "Apply");
        source.trigger("change");
    """

    textinput_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        var tag = cb_obj.get("value");

        // Reinitialise to the default value
        cb_obj.set("value", "Add custom tag...")

        if(tag.indexOf("Add custom tag...") < 0) {
        //Update the custom tags selection list
        var options = custom_tags_select.get("options");
        if(options.indexOf(tag) < 0){
            options.push(tag);
            custom_tags_select.set("options", options);
        }

        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                color: data.color[inds[i]],
                selected: true,
                possible: false,
            });
        }
        BokehPlots.updateTags(selected, tag, "Apply");
        source.trigger("change");
        }
    """

    selectinput_code = """
    event.preventDefault();
    var inds = source.get('selected')["1d"].indices;
    var data = source.get('data');
    var selected = [];
    var tag = cb_obj.get("value");

    cb_obj.set("value", "Enter tags...")
    if(tag.indexOf("Add custom tag...") < 0) {
    for(var i = 0; i < inds.length; i++){
         selected.push({
            x: data.x[inds[i]],
            y: data.y[inds[i]],
            url: data.urls[inds[i]],
            tags: data.tags[inds[i]],
            color: data.color[inds[i]],
            selected: true,
            possible: false,
         });
    }
    BokehPlots.updateTags(selected, tag, "Apply");
    source.trigger("change");
    }
    """

    # Create buttons and their callbacks, use button_code string for callbacks.
    crawl_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        var crawl = '%s';
        for(var i = 0; i < inds.length; i++){
            selected.push(data.urls[inds[i]]);
        }
        BokehPlots.crawlPages(selected, crawl);
        source.trigger("change");
    """

    # Supply color with print formatting.
    but_relevant = Button(label="Relevant", type="success")
    but_relevant.callback = CustomJS(args=dict(source=source),
                                     code=button_code % ("Relevant"))

    but_irrelevant = Button(label="Irrelevant", type="success")
    but_irrelevant.callback = CustomJS(args=dict(source=source),
                                       code=button_code % ("Irrelevant"))

    but_neutral = Button(label="Neutral", type="success")
    but_neutral.callback = CustomJS(args=dict(source=source),
                                    code=button_code % ("Neutral"))

    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_input.callback = CustomJS(args=dict(source=source),
                                         code=textinput_code % ())

    custom_tag_select = Select(value="Custom tags", options=custom_tags)
    custom_tag_select.callback = CustomJS(args=dict(source=source),
                                          code=selectinput_code % ())
    custom_tag_input.callback.args["custom_tags_select"] = custom_tag_select

    but_backward_crawl = Button(label="Backlinks", type="success")
    but_backward_crawl.callback = CustomJS(args=dict(source=source),
                                           code=crawl_code % ("backward"))

    but_forward_crawl = Button(label="Forwardlinks", type="success")
    but_forward_crawl.callback = CustomJS(args=dict(source=source),
                                          code=crawl_code % ("forward"))

    # Adjust what attributes are displayed by the HoverTool
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
        ("urls", "@urls"),
    ]
    tags = hplot(but_neutral,
                 but_relevant,
                 but_irrelevant,
                 custom_tag_input,
                 custom_tag_select,
                 height=40)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vplot(p, tags, tags_crawl)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
Exemple #14
0
mod_fname = os.path.split(mod_fpath)[1]
mod_fbase = os.path.splitext(mod_fname)[0]

def close_session():
    global session
    session.close()
    TheDoc.clear()
    #TheDoc.delete_modules()
    print ("Done")

MakeScatterPlot = Toggle(label="MakeScatter")

MessageBox = Paragraph(text="Go")
CloseButton = Button(label="Close")
CloseButton.on_click(close_session)
RowFilter = TextInput(value="")
ColumnChooser = CheckboxButtonGroup()

TheDoc = Document(title="NewDoc")
TheDoc.name = "TheDoc"


def setup(fpath=None):
    global session
    global FilePath
    FilePath = fpath
    TheDoc.title = str(fpath)
    session = push_session(TheDoc)

    layout = setup_chosen(fpath=fpath)
    TheDoc.add_root(layout)
Exemple #15
0
def text_box(text=None):
    tbox = TextInput(title='StockSTUFF', value=text)
    return tbox
Exemple #16
0
from bokeh.models.widgets import Slider, Select, DataTable, TableColumn, NumberFormatter

from bokeh.models.widgets.inputs import TextInput
from bokeh.models.widgets import Button
from bokeh.client import push_session
import bokeh.io as bio
from bokeh.document import Document
from os.path import expanduser
import bokeh_utils as bu

mod_fpath = os.path.abspath(__file__)
mod_fname = os.path.split(mod_fpath)[1]
mod_fbase = os.path.splitext(mod_fname)[0]

CloseButton = Button(label="Close")
TextBox = TextInput()
MessageBox = Paragraph(text='hello')


def close_session():
    global session
    session.close()
    TheDoc.clear()
    #TheDoc.delete_modules()
    print("Done")


close_browser_js = CustomJS(code="""
        var w = window ;
        console.log(w);
        alert("Stop") ;
plot.line(x='line_limits', y='provision_neu_28', line_color=COLORMAP[-3], source=data_source)
plot.line(x='line_limits', y='provision_neu_30', line_color=COLORMAP[-2], source=data_source)
plot.line(x='line_limits', y='provision_neu_32', line_color=COLORMAP[-1], source=data_source)
plot.xgrid.grid_line_color = None
plot.legend.orientation = 'horizontal'
plot.legend.location='top_center'

#set initial data
UMSATZ=6000
ANTEIL_HAUSMARKE=int(100*2/3)
set_data(UMSATZ, ANTEIL_HAUSMARKE)

#add gui elements and callbacks
anteil_slider = Slider(start=0, end=100, step=1, value=ANTEIL_HAUSMARKE, title='Anteil Eigenmarkeprodukte in %')
umsatz_slider = Slider(start=0, end=7500, step=1, value=UMSATZ, title='Umsatz pro Monat in € (Brutto)')
anteil_textinput = TextInput(value=str(ANTEIL_HAUSMARKE))
umsatz_textinput = TextInput(value=str(UMSATZ))
bonus_label = Button(label='SET ME')
provision_label = Button(label='ME TOO')

def set_label_data(umsatz, anteil):
    # set label button info. call this after setting data.
    if umsatz >= 1750:
        bonus_label.label = "Umsatz >= 1750 € : +3% Provision"
        bonus_label.button_type = 'success'
    else:
        bonus_label.label = "Umsatz < 1750 €  : Kein Bonus"
        bonus_label.button_type = 'default'

    provision_kombiniert = data_source.data['provision'][2]
    if provision_kombiniert > data_source.data['provision_neu_32'][0]: