示例#1
0
 def _addScriptElements(self):
     if len(self.scripts)==0:
         return
     code="""
         (function(){
             var g,s=document.getElementsByTagName('script')[0];
             function hasScriptElement(script){
                 var scripts = document.getElementsByTagName('script');
                 for (var i=0;i<scripts.length;i++){
                     if(scripts[i].src===script){
                         return true;
                     }
                 }
                 return false;
             }                
     """
     for script in self.scripts:
         code+="""
         if (!hasScriptElement('{0}')){{
             g=document.createElement('script');
             g.type='text/javascript';
             g.defer=false; 
             g.async=false; 
             g.src='{0}';
             s=s.parentNode.insertBefore(g,s).nextSibling;
         }}
         """.format(script)
     code+="})();"
     ipythonDisplay(Javascript(code))
示例#2
0
 def doRenderChart(self):
     payload = self.compute_brunel_magic()
     if not isinstance(payload, tuple):
         payload = (self.getWorkingPandasDataFrame(), payload)
     pandas_df, magic_parts = payload
     ShellAccess['brunel_temp_df'] = pandas_df
     try:
         with capture_output() as buf:
             if self.use_online_js() and not self.is_gateway:
                 ipythonDisplay(
                     HTML("""
                     <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.min.css" type="text/css" />
                     <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
                     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
                     <script src="http://requirejs.org/docs/release/2.2.0/minified/require.js" charset="utf-8"></script>
                 """))
             magic = "data('brunel_temp_df') {}".format(
                 self.complete_magic(magic_parts))
             self.debug("Running brunel with magic {}".format(magic))
             data = get_ipython().run_line_magic('brunel', magic)
             if data is not None:
                 ipythonDisplay(data)
         brunel_html = "\n".join(
             [self.convert_html(output) for output in buf.outputs])
         return brunel_html
     finally:
         del ShellAccess['brunel_temp_df']
示例#3
0
    def render(self):
        self._checkPixieDustJS()
        handlerId = self.options.get("handlerId")
        if handlerId is None or not self.noChrome:
            #get the first menuInfo for this handler and generate a js call
            menuInfo = globalMenuInfos[
                handlerId] if handlerId is not None and handlerId in globalMenuInfos else None
            if menuInfo is None:
                menuInfos = self.handlerMetadata.getMenuInfo(
                    self.entity, self.dataHandler)
                if len(menuInfos) > 0:
                    menuInfo = menuInfos[0]
            if menuInfo is not None:
                self._addHTML("""
                    <script>
                    ({0})();
                    </script>
                """.format(self._getExecutePythonDisplayScript(menuInfo)))
        else:
            start = time.clock()
            self.doRender(handlerId)
            self.executionTime = time.clock() - start

        #generate final HTML
        ipythonDisplay(
            HTML(self._wrapBeforeHtml() + self.html + self._wrapAfterHtml()))
        self._addScriptElements()
示例#4
0
 def render(self):
     self._checkPixieDustJS()
     ipythonDisplay(
         HTML(
             self.renderTemplate("handshake.html",
                                 org_params=','.join(
                                     list(self.options.keys())))))
示例#5
0
 def _addScriptElements(self):
     if len(self.scripts) == 0:
         return
     code = """
         (function(){
             var g,s=document.getElementsByTagName('script')[0];
             function hasScriptElement(script){
                 var scripts = document.getElementsByTagName('script');
                 for (var i=0;i<scripts.length;i++){
                     if(scripts[i].src===script){
                         return true;
                     }
                 }
                 return false;
             }                
     """
     for script in self.scripts:
         code += """
         if (!hasScriptElement('{0}')){{
             g=document.createElement('script');
             g.type='text/javascript';
             g.defer=false; 
             g.async=false; 
             g.src='{0}';
             s=s.parentNode.insertBefore(g,s).nextSibling;
         }}
         """.format(script)
     code += "})();"
     ipythonDisplay(Javascript(code))
示例#6
0
 def _checkPixieDustJS(self):
     if self.options.get("nostore_pixiedust", "false") != "true":
         self.options["nostore_pixiedust"] = "true"
         ipythonDisplay(Javascript(self.renderTemplate( "addScriptCode.js", type="css", code = self.renderTemplate("pixiedust.css") )))
         js = self.renderTemplate( "addScriptCode.js", type="javascript", code = self.renderTemplate("pixiedust.js") )
         self.debug("pixiedust code: {}".format(js))
         ipythonDisplay(Javascript(js))
    def doRender(self, handlerId):
        clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true"
        if not clientHasBokeh:
            output_notebook(hide_banner=True)
        data = self.entity.getNextData()
        if data is None:
            return

        x = None
        y = None

        if isinstance(data, (list, np.ndarray)):
            x = list(
                range(self.windowSize)
            ) if self.glyphRenderer is None else self.glyphRenderer.data_source.data[
                'x']
            y = data if self.glyphRenderer is None else self._concatArrays(
                self.glyphRenderer.data_source.data['y'], data)
            if len(y) < self.windowSize:
                y = [0] * (self.windowSize - len(y)) + y
            elif len(y) > self.windowSize:
                y = self._delWindowElements(y)
        elif isinstance(data, pandas.core.frame.DataFrame):
            pd = pd.drop(pd.index[[0]])
            #pd.index = list(range(len(pd.index)))
            pd['x'] = list(range(len(pd.index)))
        else:
            x = data[0]
            y = data[1]

        if self.glyphRenderer is None:
            self.glyphRenderer = self.createGlyphRenderer(self.figure, x, y)
        else:
            self.updateGlyphRenderer(self.figure, self.glyphRenderer)

        if self.glyphRenderer is None:
            print("Error: no glyphRenderer found")
            return

        self.glyphRenderer.data_source.data['x'] = x
        self.glyphRenderer.data_source.data['y'] = y

        if not self.handleId:
            self.handleId = make_id()
            if self.figure not in _state.document.roots:
                _state.document.add_root(self.figure)
            target = notebook_div(self.figure, self.handleId)
            from IPython.display import display as ipythonDisplay, HTML, Javascript
            ipythonDisplay(HTML(target))
            self.comms_handle = _CommsHandle(get_comms(self.handleId),
                                             _state.document,
                                             _state.document.to_json())
        else:
            push_notebook(handle=self.comms_handle)
示例#8
0
 def render(self):
     self._checkPixieDustJS()
     self.debug("In RunInDialog")
     # del self.options['runInDialog']
     ipythonDisplay(Javascript("pixiedust.executeInDialog({0});".format(
         json.dumps({
             "prefix": self.getPrefix(),
             "command": self.callerText.replace(",runInDialog='true'",""),
             "options": self.options
         })
     )))
示例#9
0
 def _addScriptElements(self):
     code="(function(){var g,s=document.getElementsByTagName('script')[0];"
     for script in self.scripts:
         code+="""
         g=document.createElement('script');
         g.type='text/javascript';
         g.defer=false; 
         g.async=false; 
         g.src='{0}';
         s=s.parentNode.insertBefore(g,s).nextSibling;
         """.format(script)
     code+="})();"
     ipythonDisplay(Javascript(code))
示例#10
0
 def render(self):
     self._checkPixieDustJS()
     self.debug("In RunInDialog")
     # del self.options['runInDialog']
     ipythonDisplay(
         Javascript("pixiedust.executeInDialog({0},{1});".format(
             json.dumps(
                 self.get_pd_controls(prefix=self.options.get(
                     "prefix", self.getPrefix()),
                                      black_list=['runInDialog'])),
             json.dumps({
                 "nostoreMedatadata": True,
                 "options": {
                     "runInDialog": ""
                 }
             }))))
示例#11
0
 def render(self):
     handlerId=self.options.get("handlerId")
     if handlerId is None:
         #get the first menuInfo for this handler and generate a js call
         menuInfos = self.handlerMetadata.getMenuInfo(self.entity)
         if len(menuInfos)>0:
             self._addHTML("""
                 <script>
                 ({0})();
                 </script>
             """.format(self._getExecutePythonDisplayScript(menuInfos[0])))
     else:
         self.doRender(handlerId)
         
     #generate final HTML
     ipythonDisplay(HTML(self._wrapBeforeHtml() + self.html + self._wrapAfterHtml()))
     self._addScriptElements()
示例#12
0
 def doRenderChart(self):
     payload = self.compute_brunel_magic()
     if not isinstance(payload, tuple):
         payload = (self.getWorkingPandasDataFrame(), payload)
     pandas_df, magic_parts = payload
     ShellAccess['brunel_temp_df'] = pandas_df
     try:
         with capture_output() as buf:
             if self.use_online_js() and not self.is_gateway:
                 ipythonDisplay(HTML("""
                     <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.min.css" type="text/css" />
                     <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
                     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
                     <script src="http://requirejs.org/docs/release/2.2.0/minified/require.js" charset="utf-8"></script>
                 """))
             magic = "data('brunel_temp_df') {}".format(self.complete_magic(magic_parts))
             self.debug("Running brunel with magic {}".format(magic))
             data = get_ipython().run_line_magic('brunel', magic)
             if data is not None:
                 ipythonDisplay(data)
         brunel_html = "\n".join([self.convert_html(output) for output in buf.outputs])
         return brunel_html
     finally:
         del ShellAccess['brunel_temp_df']
示例#13
0
        def processAlerts():
            self.enrichedAlerts = pandas.DataFrame(
                columns=self.alerts.columns.values.tolist() +
                ['class', 'confidence'])
            self.enrichedTweets = None
            for index, row in self.alerts.iterrows():
                if not self.doEnrichment:
                    break
                self.enrichedAlerts.loc[len(
                    self.enrichedAlerts.index
                )] = row.values.tolist() + ["Not Yet Computed", 0.0]
                ipythonDisplay(
                    Javascript("""
                    var n = $("#enrichmentProgress{0}");
                    n.attr("value", parseInt( n.attr("value")) + 1);
                """.format(self.prefix)))

                tweetsPDF = self.getAlert(row['key'])
                self.tweetsPDF = tweetsPDF
                if self.enrichedTweets is None:
                    self.enrichedTweets = pandas.DataFrame(
                        columns=['alertKey'] +
                        tweetsPDF.columns.values.tolist() +
                        ["class", "confidence"])

                for index2, row2 in tweetsPDF.iterrows():
                    if not self.doEnrichment:
                        break
                    ipythonDisplay(
                        Javascript("""
                        $("#enrichmentStatus{0}").text("Processing alert with key: {1} and Tweet {2}");
                """.format(self.prefix, row['key'], row2['key'])))
                    self.enrichedTweets.loc[ len(self.enrichedTweets.index)] = [row['key']] + row2.values.tolist() \
                        + self.classify(row2['url'] )

            self.doEnrichment = False
            viewResultsFragment = """
                <button type="submit" class="btn btn-primary" style="width:80%;height:50px;margin-bottom:20px;">
                    <pd_script>self.viewResults=True</pd_script>
                    View Results
                </button>
            """.strip().replace("\n", "")
            ipythonDisplay(
                Javascript("""
                    $("#results{0}").html('{1}');
                """.format(self.prefix, viewResultsFragment)))
示例#14
0
 def render(self, handlerId):
     self.doRender(handlerId)
     #generate final HTML
     ipythonDisplay(
         HTML(self._wrapBeforeHtml() + self.html + self._wrapAfterHtml()))
     self._addScriptElements()
示例#15
0
 def render(self):
     ipythonDisplay(HTML(self.renderTemplate("unknownEntity.html")))
示例#16
0
 def _addScriptElements(self):
     if len(self.scripts) == 0:
         return
     ipythonDisplay(Javascript(self.renderTemplate('addScriptElements.js')))
示例#17
0
 def _addJavascript(self, javascript):
     ipythonDisplay(Javascript(javascript))
示例#18
0
 def render(self):
     ipythonDisplay(HTML(self.renderTemplate("handshake.html")))
示例#19
0
 def render(self):
     ipythonDisplay(self.entity)
示例#20
0
    def doRender(self, handlerId):
        clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true"
        if not clientHasBokeh:
            output_notebook(hide_banner=True)
        data = self.entity.getNextData()
        if data is None:
            return

        x = None
        y = None

        if isinstance(data, (list, np.ndarray)):
            x = list(
                range(self.windowSize)
            ) if self.glyphRenderer is None else self.glyphRenderer.data_source.data[
                'x']
            y = data if self.glyphRenderer is None else self._concatArrays(
                self.glyphRenderer.data_source.data['y'], data)
            if len(y) < self.windowSize:
                y = [0] * (self.windowSize - len(y)) + y
            elif len(y) > self.windowSize:
                y = self._delWindowElements(y)
        elif isinstance(data, pandas.core.frame.DataFrame):
            pd = pd.drop(pd.index[[0]])
            #pd.index = list(range(len(pd.index)))
            pd['x'] = list(range(len(pd.index)))
        else:
            x = data[0]
            y = data[1]

        if self.glyphRenderer is None:
            self.glyphRenderer = self.createGlyphRenderer(self.figure, x, y)
        else:
            self.updateGlyphRenderer(self.figure, self.glyphRenderer)

        if self.glyphRenderer is None:
            print("Error: no glyphRenderer found")
            return

        self.glyphRenderer.data_source.data['x'] = x
        self.glyphRenderer.data_source.data['y'] = y

        if not self.handleId:
            self.handleId = make_id()
            if self.figure not in _state.document.roots:
                _state.document.add_root(self.figure)
            activesStreamingEntities[self.getPrefix()] = self
            target = """
<div pd_refresh_rate="2000">
    <pd_script>
from pixiedust.display.streamingDisplay import *
displayHandler = activesStreamingEntities["{prefix}"]
displayHandler.render()
    </pd_script>
</div>
            <div id="target{prefix}">
            {chart}
            </div>            
            """.format(chart=notebook_div(self.figure, self.handleId),
                       prefix=self.getPrefix())
            from IPython.display import display as ipythonDisplay, HTML
            ipythonDisplay(HTML(target))
            self.comms_handle = _CommsHandle(get_comms(self.handleId),
                                             _state.document,
                                             _state.document.to_json())
        else:
            push_notebook(handle=self.comms_handle)
示例#21
0
 def render(self, handlerId):
     self.doRender(handlerId)
     #generate final HTML
     ipythonDisplay(HTML(self._wrapBeforeHtml() + self.html + self._wrapAfterHtml()))
     self._addScriptElements()
示例#22
0
 def render(self):
     ipythonDisplay(HTML(
         self.renderTemplate("handshake.html")
     ))
示例#23
0
 def _addScriptElements(self):
     if len(self.scripts)==0:
         return
     ipythonDisplay(Javascript(self.renderTemplate('addScriptElements.js')))