Monday, March 7, 2011

Figure out the focused control

I'm trying to add a CSS class to the Control that will get the focus, once a page is rendered. While the SetFocus() method of the Page class lets me set the Control, there is no corresponding GetFocus() method.

According to the .Net sources, the information is stored in the private member _focusedControl of the Page class. The property FocusedControl is marked internal.

Is there a way to get the value of the private member or internal property by using Reflection?

Any help would be greatly appreciated.

Clarification: Here is why I want to add a CssClass server side: I'm trying to apply the following JQuery script, that changes the background of the focused element:

$(document).ready(function() {
  var elements = jQuery("textarea, select, multi-select, :text, :password, :file");

  elements.bind
  (
    'focus',
    function() {
      jQuery(this).addClass('highlightinput');
    }
  );

  elements.bind
  (
    'blur',
    function() {
      jQuery(this).removeClass('highlightinput');
    }
  );
})

This works fine as long as I don't specifically set a focused control in my aspx.vb. If I do set a focused control (I think due to a timing issue), the focus is set before my handlers are attached to the input fields and thus, the input is not highlighted. So my approach would be to add the highlightinput class to the focused control before rendering the page.

From stackoverflow
  • The control with focus may have changed between post-backs, which is why I don't think you can find it easily. It is probably too expensive to keep the entire state of each control in ViewState.

    Maybe you can track which control has focus in a hidden field on the client using javascript, and read it on the server.

    : That is correct. However, I don't need the information to survive a postback. I just need to know the last control, that was passed to the SetFocus method.
  • If you are looking for a css solution for highlighting the focused element I believe you can use the ':focus' selector. I haven't tried this, but I believe this is a valid selector. You would use it like so in your css file:

    :focus{ background-color: yellow;}
    : Thanks Yobi21, this works fine in Firefox but it's not supported by IE
  • Why not just do it all via JavaScript? Something like:

    body.onLoad = function() { document.activeElement.style.color = '#ff0000'}

    That may be buggy but I think it's a good start.

    : Thanks Shawn, I tried it but I couldn't get it to work. I would rather know server side which control will receive the focus.
  • I don't know if i understood correctly your question...

    Couldn't you just add a cssclass to the control your setting focus to on the serverside?

    controlObj).CssClass = "highlightinput"
    Page.SetFocus(controlObj)
    
    : The problem is, that the Page.SetFocus is called by a component I have no control over. So I would like to figure out, what control will be focused, once the page is rendered so I can set the additional CssClass. Also, I would like to have a generic approach, that I could add to a base-class

Reuse/cache datatable in a web service

I have a web application that pulls a datatable and displays results. Due to the nature of the business all of the business rules are incorporated in dlls that the web app must pull from. Because there are multiple site and we don't want to include the core dll's in all of the many apps that are deployed we consolidate any calls to the core dll's into a webservice. This helps when the core dll's are updated that only one new app (i.e. the web service) needs to be pushed.

With this architecutre I have found that anyone logging into any web app is causing multiple calls to the database in order to get a datatable that is then parsed. The datatable in question changes slowly and I only need to refresh it maybe once every 4-6 hours.

I am familiar with storing things like this in session when a user wants to see different views of the same datatable. However with the webservice session doesn't really apply. What is a good method for caching a datatable in the webservice so that we are not making repeated expensive trips to the database.

The webservice and the apps are all in C# and ASP.NET 2.0, and we are using VS2005.

From stackoverflow
  • You could store any data in memory for as long as you want with memcached. It runs on Linux and Windows and they also have several api implementations with C#.

  • Cheap option #1: create the datatable as a local static variable to your web service class. Populate the datatable object in a static constructor to the class. The datatable object will be available to your webmethod when the service is queried for the first time as well as any app worker process recycles.

    //pseudo-code

    class MyWebMethods {

    private static DataTable localDataTable; static MyWebMethods() { localDataTable = new DataTable(); //Do whatever else is needed here to populate the table }

    [WebMethod] public string GetSomeData(int id) { //Query localDataTable using parameter info //return result } }

    Cheap option #2: similar approach, consider ASP.Net Cache (System.Web.Caching.Cache). Same loading process as above, but different storage.

  • As a really cheap way (but it exists), you can use the CacheDuration property of the WebMethod arribute, which will cache the results of the web method call. More info at:

    http://msdn.microsoft.com/en-us/library/byxd99hx(VS.71).aspx#vbtskusingwebmethodattributecacheduration

    That might help, just a thought...

When is the proper time to use the SQL statement "SELECT [results] FROM [tables] WHERE [conditions] FETCH FIRST [n] ROWS ONLY"

I'm not quite sure when selecting only a certain number of rows would be better than simply making a more specific select statement. I have a feeling I'm missing something pretty straight forward but I can't figure it out. I have less than 6 months experience with any SQL and it's been cursory at that so I'm sorry if this is a really simple question but I couldn't find a clear answer.

From stackoverflow
  • Custom paging, typically.

  • When you want to display the values to a user, you are only likely to need N rows. Generally the database server can fetch the first N rows, faster than it can fetch all of the rows, so your screen redraw can go a little bit faster.

    Oracle even has a hint, called FIRST_ROWS that suggests that getting data back quick, is more important that getting it all back efficiently.

  • We're using the statement for the following reasons:

    1. Show only the most relevant results (say the top 100) without having to transfer all rows from the DB to the client. In this case, we also use ORDER BY.

    2. We just want to know if there are matching rows and have a few examples. In this case, we don't order the results and again, FETCH FIRST is much more cheap than having the DB prepare to transfer lots of rows and then throw them away at the client. This is usually during software development when need to get a feeling if a certain SQL is right.

  • The designers of SQL agree with you, which is why standard SQL doesn't included top/limit/fetch first, etc.

  • Think google search results and the number of pages there are typically for results.

    Though obviously, there's much more to it in their case but that's the idea.

  • I know of two common uses:

    Paging : be sure to specify an ordering. If an ordering isn't specified, many db implementations use whatever is convenient for executing the query. This "optimal" ordering behavior could give very unpredictable results.

    SELECT top 10 CustomerName
    FROM Customer
    WHERE CustomerID > 200 --start of page
    ORDER BY CustomerID
    

    Subqueries : many places that a subquery can be issued require that the result is a single value. top 1 is just faster than max in many cases.

    --give me some customer that ordered today
    SELECT CustomerName
    FROM Customer
    WHERE CustomerID =
    (
      SELECT top 1 CustomerID
      FROM Orders
      WHERE OrderDate = @Today
    )
    
  • Aside from paging, any time you want the most or least [insert metric here] row from a table, ordering on [whatever metric] and limiting to 1 row is, IME, better than doing a subquery using MIN/MAX. Could vary by engine.

how to check if a jquery plugin is loaded

Is there any way to check if a particular plugin is available?

Imagine that you are developing a plugin that depends on another plugin being loaded.

For example i want the jQuery Validation plugin to use the dateJS library to check if a given date is valid. What would be the best way to detect, in the jQuery Valdation plugin if the dateJS was available?

From stackoverflow
  • This sort of approach should work.

    var plugin_exists = true;
    
    try {
      // some code that requires that plugin here
    } catch(err) {
      plugin_exists = false;
    }
    
  • Generally speaking, jQuery plugins are namespaces on the jQuery scope. You could run a simple check to see if the namespace exists:

     if(jQuery.pluginName) {
         //run plugin dependent code
     }
    

    dateJs however is not a jQuery plugin. It modifies/extends the javascript date object, and is not added as a jQuery namespace. You could check if the method you need exists, for example:

     if(Date.today) {
          //Use the dateJS today() method
     }
    

    But you might run into problems where the API overlaps the native Date API.

    Dennis : I had to use jQuery().pluginName not jQuery.pluginName
    Nagyman : if(jQuery.fn.pluginName) {...} is another option
  • I would strongly recommend that you bundle the DateJS library with your plugin and document the fact that you've done it. Nothing is more frustrating than having to hunt down dependencies.

    That said, for legal reasons, you may not always be able to bundle everything. It also never hurts to be cautious and check for the existence of the plugin using Eran Galperin's answer.

  • For those who came here through Google searching for "How to check if jquery plugin is loaded or not" I suggest reading this article. The idea behind it is the same as Eran's answer, but it explains it in more details. Good for jQuery newbies...

  • To detect jQuery plugins I found more accurate to use the brackets:

    if(jQuery().pluginName) {
        //run plugin dependent code
    }
    

Rounded CSS tabs

Hello,

I have created some rounded navigation tabs using CSS and am having trouble when implementing:

hover

Firstly here is a link to the site Tabs as it is quite difficult to explain. Please, hover over the left side of the tabs to understand my problem. I have explained below.

I have a background image set on #navigation li items this contains the left side corner and i then have a second background image (the right corner) this is set using #navigation a.

However when i hover over the left side of the tab, only a small piece of background is shown, i presume this is because only the li area is being hovered over. Obviously i would like the entire tab to highlight as it does when you hover over the rest of it.

This was quite hard to explain so if you need to question me further to understand the problem please do.

From stackoverflow
  • Couple of things:

    Fix the problem by taking the padding off the <li> and putting it back on the child <a> - the space they occupy needs to be the same to get the hovers to align.

    Now you have a different problem, the left corner doesn't show. Fix this by making the background colour for the a and a:hover equal to transparent instead of the colours - now the <li> can show through.

    Finally, I suggest you change the behaviour from being another image entirely, to the same image with a different background-position, so the rollover loads invisibly.

    edit: css rollover without image swap described here

    annakata : ithankyou - it's easy enough to see your way through these things if you imagine building the page as bits of physical paper, I just made one of those bits acetate :)
  • With jQuery it's super easy! but you can even try scalable box:

    http://www.usabilitypost.com/2008/11/27/scalable-content-box-using-only-one-background-image/

    and then change the background image on hover.

  • Or you can replace your li:hover and a:hover with these:

    #navigation li:hover {
         background: #009BDA url(images/tab_left_on.gif) no-repeat top left;
         cursor : pointer;
         }
    
    #navigation li:hover a {
         background: #009BDA url(images/tab_right_on.gif) no-repeat top right;
         color: #FFF;
    }
    

    Note that it may not work IE6.

    annakata : definitely won't work in IE6 (li:hover not supported) but that's not always a problem
    annakata : (not that the original solution works in IE6 either...)
    Ronnie : When you say the solutions will not work in IE6. Are you saying that the problem will simply be what i have currently, or after implementing your methods will it look horribly wrong in IE6?
    Mg : Neither your page, or my solution will work since li:hover is not supported on IE6.
    Ronnie : Ok, i understand. Thank you for your help.
    annakata : but this is impossible to fix for IE6 you'd have to go with a JS solution or a different design -the market share for that browser is so poor now I wouldn't care unless you have to
  • There is also another eye catching tab named boxy tab. Thanks.

Can dynamically pluggable modules be done in VHDL?

In c (embedded) a plugin can be implemented by defining a function pointer table and an address range that the module can be loaded into.

This requires linker directive to allocate the space and define the location of the function table.

Is there a similar mechanism in HDL / VHDL or Verilog.

I guess what I am thinking is to define a block of gates in an FPGA to be for my extension feature, define the ports it will interface to and later be able to load into this block the logic to perform a certain operation.

This would have to be at runtime as the FPGA is part of the communications system that the plugin will be delivered by.

From stackoverflow
  • If you are using Xilinx FPGA's, this can be supported in some of their chips.

    See: Benefits of Partial Reconfiguration with Xilinx

    --jeffk++

    Brian Carlton : What jeffk describes isn't a Verilog or VHDL feature, but a chip feature.
  • The feature you're looking for is orthogonal to the domain of VHDL. VHDL allows modules (entities, implemented by architectures), so in theory, yes, this can work. But in practice, it really depends on your running system.

    What do you expect to gain by this? Save reconfiguration time?

    If you have a sufficiently complex board with some software running, you can easily download a fresh configuration for the FPGA from some comm channel. You can also gain small performance benefits on Xilinx, by using partial reconfiguration.

    Or maybe you can just create a configurable VHDL module that the software will configure in runtime to behave as required.

    JeffV : Hoping to get field programability with out bricking the device. The comms channel would need part of the FPGA to remain operational through out the programming phase. If something goes wrong and it gets "bricked" the actual FPGA is impossible to reach physically.
    Eli Bendersky : There are solutions for this. For example, read about Altera's Remote Upgrade theme. There is a "loader" image that's never changed, and it loads several "application" images into memory, and can update them.

Visual Studio: How to view "Advanced" properties in the Properties window?

i need to see the ClientRectangle of a form as i'm designing it. This particular property is tagged as "Advanced", and by default is hidden from the Properties window:

[EditorBrowsable(EditorBrowsableState.Advanced), ...]
public Rectangle ClientRectangle

If the ClientRectangle property i want to look at is out, then i guess i can settle for the advanced ClientSize property:

[..., EditorBrowsable(EditorBrowsableState.Advanced)]
public Size ClientSize

The documentation for the EditorBrowsable attribute leads to an enumeration with 3 values:

Always The property or method is always browsable from within an editor.

Never The property or method is never browsable from within an editor.

Advanced The property or method is a feature that only advanced users should see. An editor can either show or hide such properties.

Apparently i am an "advanced user", so how do tell Visual Studio that i am an advanced user so i can see the advanced properties?


Update One

The linked page talks about being able to enable Intellisense and the Properties Window to show advanced memebers:

In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced.

Unfortunatly this option seems to, in reality, only apply to Intellisense. Having it unchecked does not make advanced properties visible in the Properties Window

Note: the option is unchecked by default.

From stackoverflow
  • The answer is in the link you provided:

    In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced.

    Ian Boyd : i have it unchecked and the items do not appear in the Properties Window.

reading and writing files ...

Hi guys as a homework i have to write a program that read from a file that contain the folowing:

toto, M, 50

fifi, F, 60

soso, F, 70

lolo, M, 60

fifi, F, 60


and then find the following: Which mark is most repeated and how many times is it repeated

avgerage all students

avgerage all male

avgerage all female

how many are below avgerage mark

how many more than avgerage mark

and reverse

how many students' names start with T and end with T in a file

(all results should be placed in an out file)


I've done it all with no errors but its not writing on the file can any one tell me why and please i dont want to use any new methods as (LINQ and other advance stuff)

    using System;
using System.Collections.Generic;

using System.Text;
using System.IO;

namespace Exam_Ex
{
    class Program
    {
        public static int[] ReadFile(string FileName, out string[] Name, out char[] Gender)
        {
            Name = new string[1];
            int[] Mark = new int[1];
            Gender = new char[1];
            if (File.Exists(FileName))
            {
                FileStream Input = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                StreamReader SR = new StreamReader(Input);
                string[] Current;
                int Counter = 0;
                string Str = SR.ReadLine();
                while (Str != null)
                {
                    Current = Str.Split(',');
                    Name[Counter] = Current[0];
                    Mark[Counter] = int.Parse(Current[2]);
                    Gender[Counter] = char.Parse(Current[1].ToUpper());
                    Counter++;
                    Array.Resize(ref Name, Counter + 1);
                    Array.Resize(ref Mark, Counter + 1);
                    Array.Resize(ref Gender, Counter + 1);
                    Str = SR.ReadLine();
                }
            }
            return Mark;
        }

        public static int MostFreq(int[] M, out int Frequency)
        {
            int Counter = 0;
            int Frequent = 0;
            Frequency = 0;
            for (int i = 0; i < M.Length; i++)
            {
                Counter = 0;
                for (int j = 0; j < M.Length; j++)
                    if (M[i] == M[j])
                        Counter++;
                if (Counter > Frequency)
                {
                    Frequency = Counter;
                    Frequent = M[i];
                }
            }
            return Frequent;
        }

        public static int Avg(int[] M)
        {
            int total = 0;
            for (int i = 0; i < M.Length; i++)
                total += M[i];
            return total / M.Length;
        }

        public static int AvgCond(char[] G, int[] M, char S)
        {
            int total = 0;
            int counter = 0;
            for (int i = 0; i < G.Length; i++)
                if (G[i] == S)
                {
                    total += M[i];
                    counter++;
                }
            return total / counter;
        }

        public static int BelowAvg(int[] M, out int AboveAvg)
        {
            int Bcounter = 0;
            AboveAvg = 0;
            for (int i = 0; i < M.Length; i++)
            {
                if (M[i] < Avg(M))
                    Bcounter++;
                else
                    AboveAvg++;
            }
            return Bcounter;
        }

        public static int CheckNames(string[] Name, char C)
        {
            C = char.Parse(C.ToString().ToLower());
            int counter = 0;
            string Str;
            for (int i = 0; i < Name.Length - 1; i++)
            {
                Str = Name[i].ToLower();
                if (Str[0] == C || Str[Str.Length - 1] == C)
                    counter++;
            }
            return counter;
        }

        public static void WriteFile(string FileName, string[] Output)
        {
            FileStream FS = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter SW = new StreamWriter(FS);
            for (int i = 0; i < Output.Length; i++)
                SW.WriteLine(Output[i]);
        }

        static void Main(string[] args)
        {
            int[] Mark;
            char[] Gender;
            string[] Name;
            string[] Output = new string[8];
            int Frequent, Frequency, AvgAll, MaleAvg, FemaleAvg, BelowAverage, AboveAverage, NamesCheck;
            Mark = ReadFile("c:\\IUST1.txt", out Name, out Gender);
            Frequent = MostFreq(Mark, out Frequency);
            AvgAll = Avg(Mark);
            MaleAvg = AvgCond(Gender, Mark, 'M');
            FemaleAvg = AvgCond(Gender, Mark, 'F');
            BelowAverage = BelowAvg(Mark, out AboveAverage);
            NamesCheck = CheckNames(Name, 'T');
            Output[0] = "Frequent Mark = " + Frequent.ToString();
            Output[1] = "Frequency = " + Frequency.ToString();
            Output[2] = "Average Of All = " + AvgAll.ToString();
            Output[3] = "Average Of Males = " + MaleAvg.ToString();
            Output[4] = "Average Of Females = " + FemaleAvg.ToString();
            Output[5] = "Below Average = " + BelowAverage.ToString();
            Output[6] = "Above Average = " + AboveAverage.ToString();
            Output[7] = "Names With \"T\" = " + NamesCheck.ToString();
            WriteFile("d:\\output.txt", Output);
        }
    }
}

Thanx in advance

From stackoverflow
  • I haven't test it. But you should call SW.close() after finished writing stuffs.

  • In the WriteFile method, after SW.WriteLine(Output[i]);, execute SW.Close();
    I believe the buffer isn't emptied until you call Close();

  • The other answers talk about calling Close explicitly - I would suggest that instead of doing that, you wrap the use of the StreamWriter (and StreamReader and streams) in a using statement, e.g.

    using (StreamWriter SW = new StreamWriter(FS))
    {
        for (int i = 0; i < Output.Length; i++)
        {
            SW.WriteLine(Output[i]);
        }
    }
    

    This will call Dispose automatically, which will close the appropriate resource. Manually calling Close just at the end of the method is vulnerable to exceptions - you'd normally want to put it in a finally block, but that's what the using statement does automatically.

How to make a call to my WCF service asynchronous?

Hi,

I have a WCF service that I call from a windows service.

The WCF service runs a SSIS package, and that package can take a while to complete and I don't want my windows service to have to wait around for it to finish.

How can I make my WCF service call asynchronous? (or is it asynchronous by default?)

From stackoverflow
  • All your needs will be satisfied in the following articles from MSDN:

    Implementing an Async Service Operation

    Calling WCF Service Async

    Designing Service Contracts

  • the WCF Proxy inside of your client (Windows Service?) needs to be specified at creation that you wish to have Asynchronous operations available.

    You can modify an existing WCF Proxy by right clicking on it and choosing 'Configure Service Reference' From here you just need to check the tick box next to 'Generate asynchronous operations'

    Ok so that is the WCF Proxy side of things taken care of. Now you need to use APM (Asynchronous Programming Model) with the Proxy inside of your client.

  • Try this video..helped me to start quickly

What are the major differences between Rails 1.X and 2.X

Most dead-tree books and web tutorials address Rails 1.X. I'm wondering if they are worth using to learn Rails 2.X. If so, what sections and concepts should should I avoid and what have pretty much stayed the same?

From stackoverflow

Paned components in GSP

So it looks like Grails' GSP does not have an include tag (correct me if I'm wrong). The closest thing to "include" is to use the render tag. There is also the include plugin.

In my case, I have a classic top-left-middle-right-bottom paned page. The top header or left side would include navigation. The middle would be the content. The right side might include ads. In the JSP version of my app, each pane except for the middle would be in their own JSP. I'd then include (using <jsp:include/>) the various panels into my page. Is this the right approach in GSP?

What is the preferred pattern of accomplishing this in GSP?

From stackoverflow
  • You are correct that the render tag can accomplish what you want to do. Try it with templates, the key is to name them with an initial underscore. This blog post should be helpful.

  • Instead of importing or rendering your panes per-view, you probably want to use the layout functionality that grails provides (with SiteMesh). If you want to apply the same layout to all of your pages (i.e. menu/content/ads), you can just modify grails-app/views/layouts/main.gsp to have the page elements you need and then the <g:layoutBody/> tag will be filled in by your regular views rendered by your controllers. The main.gsp layout is provided by default and is the default layout for all (scaffolded and generated) views.

    If you need some pages to have the ads and others to not have them, you'll want to create a new layout in grails-app/views/layouts (e.g. main-ads.gsp). Then, in the views that you wish to have the ads, in the <head></head>, you'll set the layout using <meta name="layout" content="main-ads.gsp"/>.

    http://docs.codehaus.org/display/GRAILS/Views+and+Layouts

  • Starting with Grails 1.1 there's now an <g:include> tag which pretty much exactly does what you want.

    It still makes sense to look into the above options re layout / templates since they will be more efficient in most cases.

Javascript (jQuery) performance measurement and best practices (not load time)

I'll say right off the bat that this question is NOT about load times; I know about YSlow, the Firebug profiler, and whatever best practices and tools googlage reveals about page component load times.

I am asking what good profiling tools or libraries or add-ons there are for measuring actual execution of Javascript (specifically jQuery), insofar as improving actual user experience goes. For example, measuring the time from click to visible result on-screen, or helping to determine why a jQuery-based hover effect has slow responsiveness.

We are noticing that when the page/DOM grows relatively large (say, 70kb to 150kb worth of HTML, excluding external CSS, JS and images), and/or has very deep nesting (14-25 levels from <body> to deepest tag), jQuery events fire more slowly, or the whole JS user experience gets sluggish.

I also have googled and learned about best practices for selectors (e.g. selecting by id is much faster than selecting with classes), I will be implementing these practices. However, once all jQuery is fully loaded, and all events hooked, we still need to improve the actual event firing and execution.

I have implemented some event delegation already, and I do get the sense that having fewer hooked DOM elements makes things slightly better, but the overall experience still needs improvement with large pages. I should mention that, since the site is AJAX heavy (lots is loaded via AJAX as opposed to initial HTTP hit), we are making heavy use of livequery instead of the plain jQuery event hooks. I should also mention that we are slightly more focused on IE(7+) performance, but also require good Firefox performance.

As I develop and make changes, I figure I need a way to measure speeds pre- and post-change, so I can have concrete numbers on whether or not a change improves anything.

Any tips, tools, libs, blog posts, URLs?

From stackoverflow
  • jQuery - 25 Excellent Tips

    Pistos : Seen that already. While the tips themselves are helpful to improve things, there's nothing in there to help me measure the improvement.
  • JSLitmus looks like something I might try out.

    Pistos : I have actually implemented a little test with JSLitmus, and it is great for what it does. I am still open to anyone else's answers to this SOF question, though.

What does * mean in Python?

Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook:

def get(self, *a, **kw)

Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).

Thank you very much.

From stackoverflow
  • See Function Definitions in the Language Reference.

    If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

    Also, see Function Calls.

  • A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.

    Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.

    def f0(a)
    def f1(*a)
    def f2(**a)
    def f3(*a, **b)
    etc...
    
    Jason Baker : Not to nit-pick, but if you use a single star, the argument is stored as a tuple, not a list.
  • I only have one thing to add that wasn't clear from the other answers (for completeness's sake).

    You may also use the stars when calling the function. For example, say you have code like this:

    >>> def foo(*args):
    ...     print(args)
    ...
    >>> l = [1,2,3,4,5]
    

    You can pass the list l into foo like so...

    >>> foo(*l)
    (1, 2, 3, 4, 5)
    

    You can do the same for dictionaries...

    >>> def foo(**argd):
    ...     print(argd)
    ...
    >>> d = {'a' : 'b', 'c' : 'd'}
    >>> foo(**d)
    {'a': 'b', 'c': 'd'}
    
  • I find * useful when writing a function that takes another callback function as a parameter:

    def some_function(parm1, parm2, callback, *callback_args):
        a = 1
        b = 2
        ...
        callback(a, b, *callback_args)
        ...
    

    That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:

    def my_callback_function(a, b, x, y, z):
        ...
    
    x = 5
    y = 6
    z = 7
    
    some_function('parm1', 'parm2', my_callback_function, x, y, z)
    

    Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().

  • All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C.

    They are called the argument-unpacking and keyword-argument-unpacking operators.

Applying for an internship while not meeting all the requirements?

I'd like to apply for an internship this summer but one of the requirements is working on obtaining a computer science degree, I'm currently getting a telecommunications degree. When I talked to someone from the company at our schools career fair they said not being a cs major was not a problem. How do I address the fact that I'm not a cs major in my cover letter? The internship description is below.

The Role As a Software Development Intern at Bloomberg you will explore exciting aspects of the intersection of finance and technology. You'll join a team that owns all phases of the development life-cycle for some of Bloomberg's premier products where you will be given real world assignments. Interns are given the chance to learn more about Bloomberg while taking part in our software development efforts. All interns receive classroom and on-the-job training to help enhance their programming skills and to instill a working familiarity with Bloomberg's systems. Let this be the summer you experience Bloomberg!

Qualifications - Working towards a Computer Science BS, MS or PhD - Object Oriented Design and Development - Familiarity with UNIX, C/C++

From stackoverflow
  • I don't know if you even should address it - if it's a telecoms engineering degree (as opposed to a media studies degree) you should be auto-included with all the maths, engineering and physics students as well and you already have assurance it's not a problem.

    Not sure how the US .edu system works but in most of Europe an enginnering telecoms degree would probably be issued by the University's schools of CS (or Physics or Engineering in the older ones) anyway.

    Jared : It's issued by the college of cummunications at my school and doesn't have a strong engineering backround. It's more networking and higher level language type stuff. I've taken several CS classes though and have several years of internships working on everything from classic ASP to C/C++ on Z/OS.
    annakata : how is networking and high level languages not a strong engineering background? :) the point remains the same, I don't think you have to mention it
  • What's the difference between telecommunications and CS at your school? Does your school offer a CS degree or is this what they call their CS degree? As long as you can prove in your cover letter/resume that you have class experience with Object Oriented Design and Development, UNIX, and C/C++, the company probably won't care what the title of your degree is.

  • I don't know that I'd worry about it too much. They're not really looking for someone getting a computer science degree -- they're looking for someone who has a particular set of skills, and it just so happens that people pursuing computer science degrees will be more likely to have those skills. All you have to do is convince them that you are capable. (I'll give you the benefit of the doubt and assume you are. ;))

    In your cover letter and resume, get across as many things as you can that will show them that you can meet their needs. Mention things you've done involving OOP, Linux/UNIX, and C/C++.

    You should have a much easier time addressing the question face to face if it comes up in an interview.

  • In your cover letter (or just call up the recruiter directly), make sure you let them know your passion for software development. We've hired a student who majored in Physics that had a background in programming and others who majored in Electrical Engineering because their coursework had programming involved.

    Don't let the requirements discourage you if you really have a passion for the software development position. Just keep in mind the basic requirements you'll need to bring with you for the interview and be prepared to write some pseudocode.

    My Background: I volunteered to help interview and recruit college hires/interns from my alma mater, the University of Houston. Positions at the company were for software developers and business analysts. Students who majored in non-CS degrees for a position that 'required' CS had to show us an interest in software development.

    Good Luck!

  • How do I address the fact that I'm not a cs major in my cover letter?

    Dear XXXXXXXX

    I am very interested in the Software Developer Position internship you recently listed in xxxxxx. Please see the attached resume for a summary of my experience and qualifications.

    During my work as a Telecommunications Major I have taken XX credit hours in computer science. However my passion for software development goes beyond the classroom. I began writing software even before taking any formal classes. Last year I started a popular local blog called xxxxxx.

    yada yada yada

  • Simple answer is to mention your degree subject, don't make a big deal of it and carry on with your letter. That way you know you've made them aware of the degree subject and it is then up to them to decide if it's a big deal or not. Trying to justify why a particular degree is suitable would (IMHO) be counter-productive, especially if they have already said it isn't a problem.

How to fetch HTML in C/C++

How to fetch HTML in C or C++? with Sockets. Can you give me a Example code pls?

NOTE - I originally closed this, but reopened. To the poster - Please see:

http://stackoverflow.com/questions/400688/fetch-web-page-in-c

and

http://stackoverflow.com/questions/389069/programmatically-reading-a-web-page#389074

From stackoverflow

PHP function to build query string from array

Hi,

I'm looking for the name of the PHP function to build a query string from an array of key value pairs. Please note, I am looking for the built in PHP function to do this, not a homebrew one (thats all a google search seems to return). There is one I just can't remeber it's name or find it on php.net. IIRC it's name isn't that intuitive.

Robin

From stackoverflow
  • I'm not aware of a builtin function, but there is the PECL class http://uk.php.net/manual/en/class.httpquerystring.php

  • Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

    : Tried that but it won't work. I'm trying to build an http query string which requires both the keys and the values from the array, implode can't do this.
    Click Upvote : I see, wasn't sure if you meant an SQL query string or a http query string.
  • Your looking for http_build_query().

    : Yeah, that's the one.
    ceejayoz : Wish I'd known about that function a long time ago. Heh.
    Rimian : I can never remember it either.

C# Create OU in Active Directory

I'm struggling to create an OU for Active Directory using the code below.

strPath = "OU=TestOU,DC=Internal,DC=Com"

DirectoryEntry objOU; 
objOU = ADentry.Children.Add(strPath, "OrganizationalUnit");
objOU.CommitChanges();

The problem is strPath contains the full path 'OU=TestOU,DC=Internal,DC=net' so using .Children.Add is making the ldap path 'OU=TestOU,DC=Internal,DC=net,DC=Internal,DC=net' which results in an error as the domain obviously doesn't exist.

My question is can I create an OU using strPath without .Children.Add?

I'm not familiar with AD and this is something I inherited from the guy before me.

From stackoverflow
  • try this using System; using System.DirectoryServices;

    namespace ADAM_Examples
    {
        class CreateOU
        {
            /// <summary>
            /// Create AD LDS Organizational Unit.
            /// </summary>
            [STAThread]
            static void Main()
            {
                DirectoryEntry objADAM;  // Binding object.
                DirectoryEntry objOU;    // Organizational unit.
                string strDescription;   // Description of OU.
                string strOU;            // Organiztional unit.
                string strPath;          // Binding path.
            // Construct the binding string.
            strPath = "LDAP://localhost:389/O=Fabrikam,C=US";
    
            Console.WriteLine("Bind to: {0}", strPath);
    
            // Get AD LDS object.
            try
            {
                objADAM = new DirectoryEntry(strPath);
                objADAM.RefreshCache();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:   Bind failed.");
                Console.WriteLine("         {0}", e.Message);
                return;
            }
    
            // Specify Organizational Unit.
            strOU = "OU=TestOU";
            strDescription = "AD LDS Test Organizational Unit";
            Console.WriteLine("Create:  {0}", strOU);
    
            // Create Organizational Unit.
            try
            {
                objOU = objADAM.Children.Add(strOU,
                    "OrganizationalUnit");
                objOU.Properties["description"].Add(strDescription);
                objOU.CommitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:   Create failed.");
                Console.WriteLine("         {0}", e.Message);
                return;
            }
    
            // Output Organizational Unit attributes.
            Console.WriteLine("Success: Create succeeded.");
            Console.WriteLine("Name:    {0}", objOU.Name);
            Console.WriteLine("         {0}",
                objOU.Properties["description"].Value);
            return;
        }
    }
    }
    
  • The only way to create an object with System.DirectoryServices is to create a DirectoryEntry object to the parent and use DirectoryEntry.Children.Add.

    I think your best move at this point is to use the path you have and extract the part you need ("OU=something").

  • I think your best move at this point is to use the path you have and extract the part you need ("OU=something").

    Thanks Steve

How do you do Cygwin passwordless rlogin or rsh to Solaris 5.7

I am trying to login in to my works Solaris box from cygwin on windows. SSH is not supported. I have tried different combination in the .rhosts with no luck

I do not have root privileges.

From stackoverflow
  • I found the answer. When I put in the password the way it percieved my login was on top of the screen(whic was not what you would expect) . I put that in the .rhosts and it worked.

  • While you found the answer to your question with rlogin/rsh, my recommendation is to discontinue use of these insecure programs. Both are known to have buffer overflow exploits, and they both send passwords in clear text.

    There's really no excuse for not using SSH these days. Tell whoever owns/manages the system to enable it. That's really in their best interest anyway. It comes installed by default on most Unix varieties, and is available from most vendors as a package.

    Anyone who is running a Unix/Linux system and doesn't use SSH is just being irresponsible.

Circular References Cause Memory Leak?

I'm trying to run down a memory leak in a windows forms application. I'm looking now at a form which contains several embedded forms. What worries me is that the child forms, in their constructor, take a reference to the parent form, and keep it in a private member field. So it seems to me that come garbage-collection time:

Parent has a reference to the child form, via the controls collection (child form is embedded there). Child form is not GC'd.

Child form has a reference to the parent form, via the private member field. Parent form is not GC'd.

Is this an accurate understanding of how the garbage collector will evaluate the situation? Any way to 'prove' it for testing purposes?

From stackoverflow
  • Great question!

    No, Both forms will be (can be) GC'd because the GC does not directly look for references in other references. It only looks for what are called "Root" references ... This includes reference variables on the stack, (Variable is on the stack, actual object is of course on the heap), references variables in CPU registers, and reference variables that are static fields in classes...

    All other reference variables are only accessed (and GC'd) if they are referenced in a property of one of the "root" reference objects found by the above process... (or in an object referenced by a reference in a root object, etc...)

    So only if one of the forms is referenced somewhere else in a "root" reference - Then both forms will be safe from the GC.

    only way I can think of to "prove" it, (without using memory trace utilities) would be to create couple hundred thousand of these forms, in a loop inside a method, then, while in the method, look at the app's memory footprint, then exit from the method, call the GC, and look at the footprint again.

  • If both the parent and child are not referenced, but they only reference eachother, they do get GCed.

    Get a memory profiler to really check your application and answer all your questions. I can recommend http://memprofiler.com/

  • The GC can deal correctly with circular references and if these references were the only things keeping the form alive then they would be collected.
    I have had lots of trouble with .net not reclaiming memory from forms. In 1.1 there were some bugs aroung menuitem's (I think) which meant that they didn't get disposed and could leak memory. In this case, adding an explicit call to dispose and clearing the member variable in the form's Dispose method sorted the problem. We found that this also helped reclaim memory for some of the other control types.
    I also spent a long time with CLR profiler looking at why forms were not being collected. As far as I could tell, references were being kept by the framework. One per form type. So if you create 100 instances of Form1, then close them all, only 99 would be reclaimed properly. I didn't find any way to cure this.
    Our application has since moved to .net 2 and this seems to be much better. Our application memory still increases when we open the first form and doesn't go back down when it is closed but I believe this is becuase of JIT'ed code and extra control libraries that are loaded.
    I have also found that although the GC can deal with circular references, it seems to have problems (sometimes) with circular event handler references. IE object1 references object2 and object1 has a method that handles and event from object2. I found circumstances where this didn't release the objects when I expected but I was never able to re-produce it in a test case.

  • As others have already said, GC has no problems with circular references. I'd just like to add, that a common place to leak memory in .NET are event handlers. If one of your forms has an attached event handler to another object which is "alive", then there is a reference to your form and the form will not get GC'd.

  • Garbage collection works by tracking application roots. Application roots are storage locations that contain references to objects on the managed heap (or to null). In .NET, roots are

    1. References to global objects
    2. References to static objects
    3. References to static fields
    4. References on the stack to local objects
    5. References on the stack to object parameters passed to methods
    6. References to objects waiting to be finalized
    7. References in CPU registers to objects on the managed heap

    The list of active roots is maintained by the CLR. The garbage collector works by looking at the objects on the managed heap and seeing which are still accessible by the application, that is, accessible via an application root. Such an object is considered to be rooted.

    Now suppose that you have a parent form that contains references to child forms and these child forms contain references to the parent form. Further, suppose that the application no longer contains a references to the parent for or any of the child forms. Then, for the purposes of the garbage collector, these managed objects are no longer rooted and will be garbage collected the next time a garbage collection occurs.

    Charles Bretana : @Jason, what do you mean by an "object parameter" ? And I believe the location of the reference is the critical determinant... If on the stack, or a static member of a class, or in a CPU register, then it's a root reference. ... otherwise not. (except for freachable queue, - another topic)