def show_chart(self, **kwargs): "display the chart that was specified in the query" options = {**self.options, **kwargs} window_mode = options is not None and options.get("popup_window") if window_mode and not options.get("botton_text"): options["botton_text"] = 'popup ' + self.visualization + ( (' - ' + self.title) if self.title else '') + ' ' c = self._getChartHtml(window_mode) if c is not None: html = Display.toHtml(**c) Display.show(html, **options) return None else: return self.show_table(**kwargs)
def show_table(self, **kwargs): "display the table" options = {**self.options, **kwargs} if options.get("table_package", "").upper() == "PANDAS": t = self.to_dataframe()._repr_html_() html = Display.toHtml(body=t) else: t = self._getTableHtml() html = Display.toHtml(**t) if options.get("popup_window") and not options.get("botton_text"): options["botton_text"] = 'popup ' + 'table' + ( (' - ' + self.title) if self.title else '') + ' ' Display.show(html, **options) return None
def show_chart(self, **kwargs): "display the chart that was specified in the query" options = {**self.options, **kwargs} window_mode = options is not None and options.get("popup_window") if window_mode and not options.get("button_text"): options["button_text"] = "popup " + self.visualization + ( (" - " + self.title) if self.title else "") + " " c = self._getChartHtml(window_mode) if c.get("body") or c.get("head"): html = Display.toHtml(**c) Display.show(html, **options) elif c.get("fig"): if Display.notebooks_host or options.get( "notebook_app") == "jupyterlab": plotly.offline.init_notebook_mode(connected=True) plotly.offline.iplot(c.get("fig"), filename="plotlychart") else: Display.show(c.get("fig"), **options) else: return self.show_table(**kwargs)
def acquire_token(self): """ A method to acquire tokens from AAD. """ # print("my_aad_helper_acquire_token") token_response = self.adal_context.acquire_token( self.kusto_cluster, self.username, self.client_id) if token_response is not None: expiration_date = dateutil.parser.parse( token_response['expiresOn']) if expiration_date > datetime.utcnow() + timedelta(minutes=5): return token_response['accessToken'] if self.client_secret is not None and self.client_id is not None: token_response = self.adal_context.acquire_token_with_client_credentials( self.kusto_cluster, self.client_id, self.client_secret) elif self.username is not None and self.password is not None: token_response = self.adal_context.acquire_token_with_username_password( self.kusto_cluster, self.username, self.password, self.client_id) else: code = self.adal_context.acquire_user_code(self.kusto_cluster, self.client_id) url = code['verification_url'] device_code = code["user_code"].strip() html_str = """<!DOCTYPE html> <html><body> <!-- h1 id="user_code_p"><b>""" + device_code + """</b><br></h1--> <input id="kqlMagicCodeAuthInput" type="text" readonly style="font-weight: bold; border: none;" size = '""" + str( len(device_code)) + """' value='""" + device_code + """'> <button id='kqlMagicCodeAuth_button', onclick="this.style.visibility='hidden';kqlMagicCodeAuthFunction()">Copy code to clipboard and authenticate</button> <script> var kqlMagicUserCodeAuthWindow = null function kqlMagicCodeAuthFunction() { /* Get the text field */ var copyText = document.getElementById("kqlMagicCodeAuthInput"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ // alert("Copied the text: " + copyText.value); var w = screen.width / 2; var h = screen.height / 2; params = 'width='+w+',height='+h kqlMagicUserCodeAuthWindow = window.open('""" + url + """', 'kqlMagicUserCodeAuthWindow', params); } </script> </body></html>""" Display.show(html_str) # webbrowser.open(code['verification_url']) try: token_response = self.adal_context.acquire_token_with_device_code( self.kusto_cluster, code, self.client_id) finally: html_str = """<!DOCTYPE html> <html><body><script> // close authentication window if (kqlMagicUserCodeAuthWindow && kqlMagicUserCodeAuthWindow.opener != null && !kqlMagicUserCodeAuthWindow.closed) { kqlMagicUserCodeAuthWindow.close() } // clear output cell Jupyter.notebook.clear_output(Jupyter.notebook.get_selected_index()) // move to next cell </script></body></html>""" Display.show(html_str) return token_response['accessToken']
def load_ipython_extension(ip): """Load the extension in Jupyter.""" # this fails in both Firefox and Chrome for OS X. # I get the error: TypeError: IPython.CodeCell.config_defaults is undefined # js = "IPython.CodeCell.config_defaults.highlight_modes['magic_kql'] = {'reg':[/^%%kql/]};" # display_javascript(js, raw=True) kql_magic_load_mode = os.getenv('KQLMAGIC_LOAD_MODE') if kql_magic_load_mode: kql_magic_load_mode = kql_magic_load_mode.strip().lower() if kql_magic_load_mode.startswith( "'") or kql_magic_load_mode.startswith('"'): kql_magic_load_mode = kql_magic_load_mode[1:-1].strip() if kql_magic_load_mode != 'silent': html_str = """<html> <head> <style> .kqlmagic-banner { display: flex; background-color: #d9edf7; } .kqlmagic-banner > div { margin: 10px; padding: 20px; color: #3a87ad; font-size: 13px; } </style> </head> <body> <div class='kqlmagic-banner'> <div><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH8AAAB9CAIAAAFzEBvZAAAABGdBTUEAALGPC/xhBQAAAAZiS0dEAC8ALABpv+tl0gAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAAd0SU1FB+AHBRQ2KY/vn7UAAAk5SURBVHja7V3bbxxXGT/fuc9tdz22MW7t5KFxyANRrUQ8IPFQqQihSLxERBQhVUU0qDZ1xKVJmiCBuTcpVdMkbUFFRQIJRYrUB4r6CHIRpU1DaQl/AH9BFYsGbO/MOTxMPGz2MjuzO7M7sz7f0+zszJzv+32X8507PPjJFZSFMMpI3V945sLX3vzLxa5/0fjq/VsvpSmBJv/d9pXlw6upZFg+vLp8eLWLDNHd+L+26yAIugi9fHi1qzBaq9u3b3d54f1bL7V+NS4EAM/MzPSEte2dnihFzCTjmw1WhBC02tK16+cOHJinlCYwBmMyvgQaF0u//d3pXtq4i+A7Ny8JwTP4Q9enO50hrQytGsSdjhL/3fpcGIY9he4q7ubmptaqv/HFhfi+D4BTOVCSHob1h65v3mNLf3rzQqPhAsCE+0PhHGWlnmp7/OTnP/u5o4uL05bFMcbpI2mfAlLWWn2fjDmgeUERf7GtYJymDmy9zk0Hbax1AtL1vtZ6c3MzDEOtVeT9NH3sSvMAANi2rbWO/RX31eQfNy5kMhvGGOccIegDUSy773vpTasEjtZshghpxujw9tq9gE8dWev15su/PHVg6eO+XyME76VgV3gBBqIS12iddPnFlcWF2YXFacbY4DVaTM8+9/iRIwccV0gpcpPg7XcvMUYIIUVBJCVP+VrKCrlSVtSr3h6fBGPOKnqlGlrrMAwR0v3r5KwpYkTb29t37txRKsCYZdBB+kpfKRWGoUYaIZ1D6tiZLgohCCEYaAxR5qZjMhFChBBRTpc28RpMGRn8YJisK1VmN2QZe6pGS1ZMnz6U2E2aTcU5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EmQTFlzPef//lryQ88d+mkY0vblp5nSYtJyaNF6wCIMRIN9VUC/cnZGYwQjDFBSDWbobH9UVMYqhLuDG3yfYO+IYO+Qd+QQd+gb8igb9A36BsaPf0PJmoM1QL6Q/4AAAAASUVORK5CYII='></div> <div> <p>Kusto is a log analytics cloud platform optimized for ad-hoc big data queries. Read more about it here: http://aka.ms/kdocs</p> <p> • kql language reference: Click on 'Help' tab > and Select 'kql referece'<br> • Kqlmagic configuarion: Run in cell '%config kqlmagic'<br> • Kqlmagic syntax: Run in cell '%kql?'<br> • Kqlmagic upgrate syntax: Run 'pip install git+git://github.com/mbnshtck/jupyter-kql-magic.git --upgrade'<br> </div> </div> </body> </html>""" Display.show(html_str) Display.showInfoMessage( """Kqlmagic version: """ + VERSION + """, source: https://github.com/mbnshtck/jupyter-kql-magic""") #<div><img src='https://az818438.vo.msecnd.net/icons/kusto.png'></div> result = ip.register_magics(Kqlmagic) _override_default_configuration(ip, kql_magic_load_mode) _set_default_connections(ip, kql_magic_load_mode) # add help link Help_html.add_menu_item('kql Reference', 'http://aka.ms/kdocs') root_path = get_ipython().starting_dir folder_name = ip.run_line_magic('config', 'Kqlmagic.showfiles_folder_name') # print('folder_name = ' + folder_name) showfiles_folder_Full_name = root_path + '/' + folder_name if not os.path.exists(showfiles_folder_Full_name): os.makedirs(showfiles_folder_Full_name) # ipython will removed folder at shutdown or by restart ip.tempdirs.append(showfiles_folder_Full_name) Display.showfiles_base_path = showfiles_folder_Full_name + '/' Display.showfiles_folder_name = Help_html.showfiles_folder_name = folder_name Display.notebooks_host = Help_html.notebooks_host = os.getenv( 'AZURE_NOTEBOOKS_HOST') # print(Display.showfiles_base_path) # get notebook location display( Javascript( """IPython.notebook.kernel.execute("NOTEBOOK_URL = '" + window.location + "'");""" )) folder_name = ip.run_line_magic('config', 'Kqlmagic.showfiles_folder_name') time.sleep(5) return result