using heapy's memory profile browser with twisted.web

  • Last Update :
  • Techknowledgy :

After looking over the guppy website and not finding any information about how to launch the profile browser there, I started looking around the guppy source and eventually found guppy/heapy/Prof.py, at the end of which I saw a docstring containing this line:

[0] heapy_Use.html #heapykinds.Use.pb

It seems the simplest way to make this information available would be to make a resource in your web server that invokes Use.pb as part of its rendering process. There are other approaches, such as embedding a manhole in your application, or using a signal handler to trigger it, but I like the resource idea. So, for example:

class ProfileBrowser(Resource):
   def render_GET(self, request):
   h.pb()
return "You saw it, right?"

   ...
   root = RootResource(mq)
root.putChild("profile-browser", ProfileBrowser())
   ...

Suggestion : 2

I am trying to profile twisted python code anycodings_heapy with Heapy. For example (pseudo code):,What do I need to do to view Heapy profile anycodings_heapy results in the profile browser?,Load a .csv-file in a dictionary and search for a specific entry in column using Python,After looking over the guppy website and anycodings_heap-memory not finding any information about how to anycodings_heap-memory launch the profile browser there, I anycodings_heap-memory started looking around the guppy source anycodings_heap-memory and eventually found anycodings_heap-memory guppy/heapy/Prof.py, at the end of which anycodings_heap-memory I saw a docstring containing this line:

I am trying to profile twisted python code anycodings_heapy with Heapy. For example (pseudo code):

from twisted.web
import resource, server
from twisted.internet
import reactor
from guppy
import hpy

class RootResource(resource.Resource):
   render_GET(self, path, request):
   return "Hello World"

if __name__ == '__main__':
   h = hpy()
port = 8080
site = server.Site(RootResource(mq))
reactor.listenTCP(port, site)
reactor.run()

After looking over the guppy website and anycodings_heap-memory not finding any information about how to anycodings_heap-memory launch the profile browser there, I anycodings_heap-memory started looking around the guppy source anycodings_heap-memory and eventually found anycodings_heap-memory guppy/heapy/Prof.py, at the end of which anycodings_heap-memory I saw a docstring containing this line:

[0] heapy_Use.html #heapykinds.Use.pb

It seems the simplest way to make this anycodings_heap-memory information available would be to make a anycodings_heap-memory resource in your web server that invokes anycodings_heap-memory Use.pb as part of its rendering process. anycodings_heap-memory There are other approaches, such as anycodings_heap-memory embedding a manhole in your application, anycodings_heap-memory or using a signal handler to trigger it, anycodings_heap-memory but I like the resource idea. So, for anycodings_heap-memory example:

class ProfileBrowser(Resource):
   def render_GET(self, request):
   h.pb()
return "You saw it, right?"

   ...
   root = RootResource(mq)
root.putChild("profile-browser", ProfileBrowser())
   ...

Suggestion : 3

After looking over the guppy website and not finding any information about how to launch the profile browser there, I started looking around the guppy source and eventually found guppy/heapy/Prof.py, at the end of which I saw a docstring containing this line:,Answer(s) may contain affiliate links. By clicking such link, you will be redirected to third party website. If you make any purchase then the answer publisher or we may earn little amount of commission.,Phone number or email id included in the answer(s) are not verified by us. Before calling on the mentioned number or sending an email do your own research and be confirm you calling or sending mail to right person or company.,odd_integers_up_to_length(el).next() will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything.

After looking over the guppy website and not finding any information about how to launch the profile browser there, I started looking around the guppy source and eventually found guppy/heapy/Prof.py, at the end of which I saw a docstring containing this line:

[0] heapy_Use.html #heapykinds.Use.pb

It seems the simplest way to make this information available would be to make a resource in your web server that invokes Use.pb as part of its rendering process. There are other approaches, such as embedding a manhole in your application, or using a signal handler to trigger it, but I like the resource idea. So, for example:

class ProfileBrowser(Resource): "    def render_GET(self, request):"
h.pb()
"        return "
You saw it, right ? ""
"..."
root = RootResource(mq)
"root.putChild("
profile - browser ", ProfileBrowser())"...

You can use the HTMLParser class to extract the elements you're interested in. Something like this will work:

from HTMLParser
import HTMLParser "import urllib"
"class AnchorParser(HTMLParser):"
def handle_starttag(self, tag, attrs): "            if tag =='a':"
for key, value in attrs.iteritems()): "                            if key == 'href':"
print value ""
parser = AnchorParser()
"data = urllib.urlopen('http://somewhere').read()"
parser.feed(data)
np.set_printoptions(precision = 4)
new_dataset = dataset[['A', 'D']]

You could use a class decorator (Python 2.6 and up) if you just want to add a common function to several classes (instead of using inheritance).

def addF(y): "    def f(self, x):"
return "Hello", x, "and", y ""
def decorate(cls): "        cls.f = f"
return cls ""
return decorate ""
"@addF(1)"
class X(object): "    pass"
"@addF(2)"
class Y(object): "    pass"
"print X().f("
X ")"
print Y().f("Y")
"" >>> "Hello X and 1"
Hello Y and 2

You can extend the path at runtime like this:

sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))

Suggestion : 4

Using Heapy's Memory Profile Browser with Twisted.web,The example on asp.net of a model binder is:,You can create a <div> (or any plain HTML element) in code behind with the HtmlGenericControl class, and use that to wrap your ImageButton any way you want. For example:,First you'll need server code to access the file system. This is can go inside a code behind file or in the aspx page itself - just delete everything else.

ProfileBase pb = ProfileBase.Create(Page.User.Identity.Name);
m_PreferredName = pb.GetPropertyValue("WebName") as string;
public class GeoPointModelBinder : IModelBinder
{
    // List of known locations.
    private static ConcurrentDictionary<string, GeoPoint> _locations
        = new ConcurrentDictionary<string, GeoPoint>(StringComparer.OrdinalIgnoreCase);

    static GeoPointModelBinder()
    {
        _locations["redmond"] = new GeoPoint() { Latitude = 47.67856, Longitude = -122.131 };
        _locations["paris"] = new GeoPoint() { Latitude = 48.856930, Longitude = 2.3412 };
        _locations["tokyo"] = new GeoPoint() { Latitude = 35.683208, Longitude = 139.80894 };
    }

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(GeoPoint))
        {
            return false;
        }

        ValueProviderResult val = bindingContext.ValueProvider.GetValue(
            bindingContext.ModelName);
        if (val == null)
        {
            return false;
        }

        string key = val.RawValue as string;
        if (key == null)
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName, "Wrong value type");
            return false;
        }

        GeoPoint result;
        if (_locations.TryGetValue(key, out result) || GeoPoint.TryParse(key, out result))
        {
            bindingContext.Model = result;
            return true;
        }

        bindingContext.ModelState.AddModelError(
            bindingContext.ModelName, "Cannot convert value to Location");
        return false;
    }
}
    static void Main(string[] args) {
       REngine.SetEnvironmentVariables();
       REngine engine = REngine.GetInstance();
       engine.Initialize();
       engine.Evaluate("x <- 40 + 2");
       engine.Evaluate("s <- paste('hello', letters[5])");
       var x = engine.GetSymbol("x").AsNumeric().First();
       var s = engine.GetSymbol("s").AsCharacter().First();
       Console.WriteLine(x);
       Console.WriteLine(s);
    }
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function displayDiv() {
            if ($("#<%= comNewStatus.ClientID %>").val() == "2") {
                $("#divFirst").show();
            }
            else {
                $("#divFirst").hide();
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div class="form-element">
            <label>
                New status (required)</label>
            <select id="comNewStatus" runat="server" datavaluefield="id" datatextfield="name"
                class="nFee" onchange="displayDiv()">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Opotion 3</option>
            </select>
        </div>
    </div>
    <div id="divFirst" class="form-element" style="display:none;">
        <label>
            Offered salary (numeric only!!)</label>
        <input type="text" id="txtOfferedSalary" class="txtOfferedSalary" runat="server"
            data-bind="value:offeredSalary, valueUpdate: 'afterkeydown'" />
    </div>
    <div id="divSecond" class="form-element" style="display:none;">
        <label>
            Final salary (numeric only!!)</label>
        <input type="text" id="txtFinalSalary" class="txtFinalSalary" runat="server" data-bind="value:finalSalary, valueUpdate: 'afterkeydown'" />
    </div>
    </form>
</body>
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 Dim dir As String
 If Request.Form("dir") Is Nothing Or Request.Form("dir").Length <= 0 Then dir="/" Else dir=Request.Form("dir") End If Dim di As New System.IO.DirectoryInfo(Server.MapPath(dir)) Dim sb As New StringBuilder sb.Append("<ul class="" jqueryFileTree"" style="" display: none;"">" & ControlChars.Lf)
    Dim di_child As System.IO.DirectoryInfo
    For Each di_child In di.GetDirectories()
    sb.Append((ControlChars.Tab & "<li class="" directory collapsed""><a href="" #"" rel=""" & dir & di_child.Name & " /"">" & di_child.Name & "</a></li>" & ControlChars.Lf))
    Next di_child
    Dim fi As System.IO.FileInfo
    For Each fi In di.GetFiles()
    Dim ext As String = ""
    If fi.Extension.Length > 1 Then
    ext = fi.Extension.Substring(1).ToLower()
    End If

    sb.Append((ControlChars.Tab & "<li class="" file ext_" & ext & """><a href=""#"" rel=""" & dir & fi.Name & """>" & fi.Name & "</a></li>" & ControlChars.Lf)) Next fi sb.Append("</ul>")
       Response.Write(sb.ToString)
       End Sub
private void OpenImage() {
   foreach(string strFileName in Directory.GetFiles(Server.MapPath("~/img/"))) {
      ImageButton imageButton = new ImageButton();
      ...
      HtmlGenericControl div = new HtmlGenericControl("div");
      div.Attributes["class"] = "my-class"; // or div.Attributes.Add("class", "my-class"); 
      div.Controls.Add(imageButton);
      Panel1.Controls.Add(div);
   }
}