Thursday, April 28, 2011

AJAX checkbox if statement

I've got a bunch of variables being pulled from form ID's before being sent in a query string to a PHP. However, as one input is a checkbox I'm trying to get AJAX to set the variables value according to whether it's checked or not. i.e..

 if (document.getElementById('bold').checked) { var bold = "true"; 
 }
 else { var bold = "false"; }

But, it doesn't actually send anything to the PHP. I'm guessing syntax a lot of the time, so if anyone can correct I'd be most grateful.

From stackoverflow
  • As long as you've given it a name it should be accessible as "on" or "off" in the backend e.g.

    var $checked = $_POST["checkboxname"] == "on";
    

    So your javascript is redundant.

    WiseDonkey : Ideally, this would the answer but it's being sent in a GET and the string literally just has bold=true or bold= and nothing there. I tried using isset() or empty()... neither would work. I think it needs to be sorted in the JS.
    Rob Stevenson-Leggett : Can't you just do var $isBold = $_GET["bold"] == "true" then?
  • Firstly, instead of: var bold = "true";

    I think you're actually looking for something like: document.getElementById('bold').value = "true";

    Secondly, if the checkbox is not checked nothing will be sent to the PHP script (unchecked checkboxes are not sent as part of a form submission).

    WiseDonkey : Didn't work on that as I have to still declare the var afterwards. Secondly, normally that is the case but this is submitted by an ajaxFunction onChange of anything. So the value does seem to be submitted whatever the cirumstances.
    Narcissus : If that's the case then I agree with chosta... we need to see the sending code.
    DaNieL : Agree, if the checkbox isnt checked, nothing will be send with the form
    WiseDonkey : Thanks very much, I've actually identified the 'ahem' problem... PHP side the variable was typo'd out. The proposed method I used in the question has worked. :/ Sorry to faff you around guys, thanks for the effort.

What is the best way to create a "fully" modular ZF-based application?

For the past time I have been working on a Zend Framework based webshop application that we are building from scratch. The application has been successfully been set up for several clients, but we are stumbling upon more and more problems regarding extensibility and modularity of the application.

A lot of clients require a lot of different approaches on some matters, often requiring customizing default modules or extending them. I have been looking on the web for Zend Framework based code that could guide me to this and so far Magento has been the only example I have come up with. Although Magento seems to do a very good job offering extensibility and modularity, the code is far too complex and extensive for my current needs (or so it seems).

In an ideal situation, it would work as follows:

  • Each client gets the "base" application installed
  • Modules, controllers, models should be easily overridden or extended
  • New modules should be easily created

Are there any other Zend Framework based applications or other pointers that could guide me in the right direction?

Thanks in advance.

From stackoverflow
  • Zend Framework is a... framework. What you're looking for is a full blown system. That's your job as a developer is to build a system on top of a framework (whether Zend or your own).

    People usually tell you not to reinvent the wheel, but in this case you need to develop your own system for your company to easily be able to develop and deploy for new clients.

    Like already stated, it is a very complex answer you are looking for. You will not get that answer.

    Aron Rotteveel : Thanks for the answer, I appreciate it. I do want to make clear however that I am not looking for a "copy / paste" solution that I can use. I am very interested in the solutions others have possibly thought of encountering this problems, since I haven't thought of one so far.
    Matt : Others don't know the full requirements of what you really need. Sure you listed basic requirements, but that's way too vague. Anything more complicated and you're basically asking for a consultation, which people normally get paid really good money for.
  • I think version 1.8 of the Zend Framework is going to address a lot of the issues with building modular applications. Especially with the new (Zend_Application) it should allow for auto loading of module resources, which isn't easy to do at this point.

    I don't know much about it, but this may be something to look into. 1.8 should be out by the end of this month.

RDBMS Key Confusion

I'm trying to sort out the database behind my company's website.

We deal with both Sites and Residents. At the moment the Site Reference is included in the Residents table as a foreign key but, obviously, this is only in 1NF.

Site references are of the form nnnnn (12345, for example). Each resident has their own reference within the Site of the form nnn (starting at 001 and ending at a maximal 999).

The problem is, when I take it to 2NF:

Site(Reference, Name, Charge)

Residency(SiteReference, ResidentReference,)

Resident(Reference, Address, Username, Password)

The Resident Reference will never uniquely identify one Resident as, if there are 2 sites, then there will be 2 001s. I can't use username as this field is only populated once (and if!) they have registered for our web service. I'd simply introduce a new autonumber ID for Residents but there's something niggling at me that there is a more elegant solution. Can anyone suggest what it is?

From stackoverflow
  • You need to "free" the resident reference from the site - e.g. make it a ResidentID and make sure each ResidentID is globally unique within the Resident table. Every Site must also have a globally unique SiteID within the Site table.

    Then and only then will you be able to create a good db schema.

    The Residency table will provide the link between residents (identified uniquely by their ResidentID) and the sites (again - uniquely identified by their SiteID).

    Marc

    Bailz : That's what I was thinking. Thanks for the confirmation.

What's the easiest way to encrypt a file in c#?

Beforehand :

I have read indeed the other topics on SO, but I can't find an answer in them.
(The others are about config-files, or a list of techniques)

My question thus is very simple, though a bit subjective (I'll label it beforehand :-)) what is the easiest way..

tx!

From stackoverflow
  • Data Protection API in C#

  • File.Encrypt is pretty simple - one call (with one parameter).

    Of course, it really depends on what you want the encryption for. File.Encrypt encrypts to the current account, which isn't much use if you're passing the file around. But, given your spec - i.e. easiest way to encrypt a file - it has to be a candidate!

  • Don't believe you have any security just because you encrypt a config file. If someone has access to the encrypted config file, and your executable, containing the password, it's likely to be possible to decrypt your configfile. It's just a little harder.

    And say your config file contains passwords to database connections, it might be possible to get those passwords looking at the network packets.

    Peter : I voted you up, because the downvote may have to do with the fact that you misread my question, and that could have been partly my fault,so I rephrased it.
    Lucas McCoy : I agree with you because it's ok to be 'paranoid' about your security if it matters. If you can encrypt it, it can be decrypted. It just like your answer it makes it a little harder.
  • Encryption is trivial with modern libraries: the hard part is securing the key(s).

    So you need to look at what you're trying to secure, and what threats you are trying to secure against.

    To encrypt a file so only the current user can see it on a client workstation, File.Encrypt is a good choice, or DPAPI with the CurrentUser scope.

    For a configuration file on a single server, DPAPI using the LocalMachine scope is a good choice. You then need to make sure only authorized users are able to log in to the server. Here you're essentially delegating key management to Windows.

    For a configuration file on a server farm, you need to share the key between the servers. RsaProtectedConfigurationProvide is a good choice, but you have more work ensuring that all servers have access to the same key, and that it is protected against unauthorized access (e.g. using a DACL).

  • I recommend the Cryptography Application block in Enterprise Library. Very easy, very flexible.

    MichaelGG : I doubt "easiest" and "Enterprise Library" ever belong together...
    JP Alioto : Really? I find the opposite, but I guess I am just used to using it. Encryption done right by it's very nature is not "easy", but I suppse you're right in that it's part of the question. But, for completeness sake. :)

"50289 Can't perform operation since the project is protected" but why?

I am supplying the correct password

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("H:\M\X\C.xls", 0, , , "password")

'any of these lines cause the error mentioned

Set vbcomp = objWorkbook.VBProject.VBComponents(modname)
objWorkbook.VBProject.VBComponents.Remove vbcomp
objWorkbook.VBProject.VBComponents.Import modpath & modtest

Any ideas what the problem might be? Tools-Macro-Security is set to allow VB project access

From stackoverflow
  • The VBA project itself is protected by a password which is different then the worksheet password. Open the VBA IDE - select Tools-VBA Project Properties and look at the Protection Tab.

    Not sure how or if you can remove the VBA Project password using code.

    adolf garlic : Correct. It does not appear to be possible to removed the password on the VBA project, unless you use a hideous 'sendkeys' type workaround.
  • This may sound extreme, however I managed to get around this by downloading Windows Installer Clean up Utility (look for msicuu2.exe in Google) and removed office 2003. I then reinstalled office 2003 and my problem had disappeared. Hope it solves your probelm too. Alex

PHP: Best Method for Sequential Output?

What is the best approach for setting up sequential output for a PHP installer script? Say I have a page, and want to display incremental output within a DIV provided by a PHP script.

So page.html might contain this:

<div id="output">
    <!-- Script Output Here -->
</div>

And install.php might look like this (for testing purposes):

<?php
// Turn off Output Buffering
ob_end_flush();

// Begin Test Output (5 second intervals)
echo 'Testing incremental output...' . "\n";
sleep(5);
echo 'Step 1...' . "\n";
sleep(5);
echo 'Step 2...' . "\n";
sleep(5);
echo 'Complete!' . "\n";

I was thinking AJAX might be the best approach, but I'm not sure how to approach that. If I load "install.php" via JavaScript, I won't get everything back until the script finishes execution (correct?) - making this entire goal moot. I've seen this done before, but can't find a concrete example of how it was done.

Any help appreciated!

From stackoverflow
  • I doubt Ajax will do what you want - instead you may have to call the ajax fetches more frequently.

    For flushing information out as soon as it's produced you need regular flush()'s after outputting information.

    I've also added into a relevant .htaccess file a line to avoid any buffering due to GZipping the output as well (apache2).

    SetEnvIf Request_URI "/url/dont/buffer/me.php" gzip=0
    

    In the relevant PHP file:

    ini_set('output_buffering', false);
    ini_set('implicit_flush', 'true');
    

    and the appropriate calls to flush(). That pretty much covers all the bases.

  • I would output everything to a text file and updating the DIV via AJAX by just calling the .txt file

    Tony k : Pretty hairy; multiple users? Then you've got multiple text files. Name the text file based on a session? What about multiple tabs? Oh crap I just divided by zero.
    Calvin : Ah, screw it. Just time your install script and create an animated GIF. It's all the same to the user.

How can I set a css ":hover" on a DOM created element in JavaScript?

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created elements on the fly (meaning, no linking to an external CSS, and no providing CSS in the HTML doc itself, because I won't have control of the doc).

I'd like to create a hover effect on some of the elements.

example:

 #myDiv:hover { background:#000000; }

Is there a way to define that in the DOM? Or do I have to use mouseover?

From stackoverflow
  • You can dynamically create and manipulate stylesheets. See here for some of the cross-browser issues with this approach.

    I've got a wrapper function lying around which works around some of them; using it, the code would read

    document.createStyleSheet().addRule('#myDiv:hover', 'background:#000000;');
    
  • you may create element with predefined class:

    .h:hover{color: #c00}
    
    var elem = document.createElement('div');
    elem.className = 'h'
    
    johnnietheblack : good, and yes...however i didn't have the ability to link to a stylesheet

ASP.NET TreeView performance

What would be the advisable thing to do to maximize the performance while using TreeView?

By maximize the performance, i mean minimize the number of trips between client to server, ie postbacks.

Would that mean then, that most of my Business logic will sit in the Javascript? What would be the compromise here?

I am talking about ASP.net TreeView server control

From stackoverflow
  • development overhead - you will have to maintain your business logic in both javascript and code behind.

    reduced client performance would also be a concern if the script is big.

    gnomixa : I guess the separation of Business Login from Presentation layer is impossible then?
    FlyinFish : you could have separate javascript files to handle business logic,think the javascript as a different agent, consisting its own PAC hierarchy. Or alternatively, you could generate javascript validation from the code behind.
  • First, decide where you want to put your programming logic: for speed, it's better to use some other tree view control (that doesn't use table layout) and javascript framework to handle click events. I recommend using plain old ashx handler files for AJAX communication, they have less overhead than aspx and calling page methods. AJAX calls and results must contain only JSON or XML formatted data, not HTML.

    On the oher side, RAD tool like VS and TreeView control offers quick production of web application, but of course with some penalties: you need to go back to server to handle every click/select event, which draws issues with whole page life cycle processing and huge amount of data transfer for ajax calls (ViewState along with HTML are transferred from server to client for every ajax event).

    But if you want to stick with TreeView, i recommend:
    - CSS Friendly Control Adapter: they greatly reduce size of generated html (in my case, from 100kb to 20kb of html) and replace table layout with ul/li elements
    - Wrap TreeView inside ASP.NET AJAX UpdatePanel, but just treeview, and use conditional updates of panel. Don't be afraid to use several updatepanels
    - keep ViewState minimal

    gnomixa : Actually according to this http://www.asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx UpdatePanel is not compatible with TreeView
    Hrvoje : I have Treeview in UpdatePanel, but had to do some tricks. Please let me know if you want me to post here how i did it!
    gnomixa : No its ok, if MS says they don't support it inside UpdatePanel, I am not going to use it there.
    gnomixa : Actually, according to MS, TreeView was implemented with built-in Callback (http://msdn.microsoft.com/en-us/library/e8z5184w.aspx) it says there that if you set certain properties properly, the tree will load nodes inside callback w/o posting back the whole page.
    gnomixa : Then again, i haven't tried it yet. It might not do what I have in mind.
    Hrvoje : There is workaround to get TreeView working inside UpdatePanel!
  • Hrvoje,

    Please provide the tricks as i urgenlty need it..

  • Hello gnomixa,

    Maybe you could take a look at the ASTreeView which has full functionality including drag&drop, ajax loading, context menu, and the performance is great!

    check out the demo:

    http://www.geekees.com

How to know when Big O is Logarithmic?

My question arises from the post "Plain English Explanation of Big O". I don't know the exact meaning for logarithmic complexity. I know that I can make a regression between the time and the number of operations and calculate the X-squared value, and determine so the complexity. However, I want to know a method to determine it quickly on paper.

How do you determine logarithmic complexity? Are there some good benchmarks?

From stackoverflow
  • Master theorem usually works.

    samoz : Somewhat difficult to think about, but very good once you master it.
  • Not rigorous, but it you have an algorithm that is essentially dividing the work needed to be done by half on each iteration, then you have logarithmic complexity. The classic example is binary search.

    kunjaan : not necessarily. I understand what you are trying to imply but just because you divide the work in half doesnt mean you get a logarithmic complexity, you could even have exponential time for that matter. You have to note how the solutions are being recombined too and how the divided problems get solved too. There are lot of cases where recombination step dominates. See Master Theorem or better solve the recurrence without the theorem. There are a lot of surprises underneath a simple recurrence.
    Mitch Wheat : @unjaan: I think you are misunderstanding me. I didn't just say divide the work in half, I said "the work needed to be done by half on each iteration". What I mean is, if at each step there is half the work remaining to be done as compared to the previous step, then you have logarithmic complexity (for work, read computations).
  • If you just want to know about logarithmic Big Oh, be on the lookout for when your data is cut in half each step of the recurrence.

    This is because if you are processing data that is 1/2 as big as the step before it, it is an infinite series.

    Mehrdad Afshari : Not necessarily 1/2. 1/c works, as long as `c` is constant.
    Mitch Wheat : but 1/2 is more 'intuiative'
    samoz : Well usually when talking about Big O, log means log base 2.
    George V. Reilly : @samoz, logarithmic is independent of the base. log_a(x) = log_b(x)/log_b(a) to convert from base a to base b.
    samoz : @George agreed, but it is commonly base 2.
  • Not sure if this is what you mean, but... logarithmic complexity usually arises when you're working with a spread-out data structure like a balanced binary tree, which contains 1 node at the root, 2 children, 4 grandchildren, 8 great-grandchildren, etc. Basically at each level the number of nodes gets multiplied by some factor (2) but still only one of those is involved in the iteration. Or as another example, a loop in which the index doubles at each step:

    for (int i = 1; i < N; i *= 2) { ... }
    

    Things like that are the signatures of logarithmic complexity.

    Masi : +1 very interesting. I am looking for something like your examples more. Is the algorithm logartihmic as: for (int i = BIG_number; i > N; i *= 1/2) { ... }
    David Zaslavsky : 1/2 is zero in integer division, but if you use "i /= 2" instead, yes it is. (If that's the particular algorithm you're wondering about, it might have been a good idea to include it in your question.)
  • Here is another way of saying it.

    Suppose your algorithm is linear in the number of digits in the size of the problem. So, perhaps you have a new algorithm to factor a large number, that you can show to be linear in the number of digits. A 20 digit number thereby takes twice as long to factor as a 10 digit number using your algorithm. This would have log complexity. (And it would be worth something for the inventor.)

    Bisection has the same behavior. It takes roughly 10 bisection steps to cut the interval length by a factor of 1024 = 2^10, but only 20 steps will cut the interval by a factor of 2^20.

    Log complexity does not always mean an algorithm is fast on all problems. The linear factor in front of the O(log(n)) may be large. So your algorithm may be terrible on small problems, not becoming useful until the problem size is appreciably large that other algorithms die an exponential (or polynomial) death.

    Masi : Well explained with the big problem size.

Sorting in linear time?

Given an input set of n integers in the range [0..n^3-1], provide a linear time sorting algorithm.

This is a review for my test on thursday, and I have no idea how to approach this problem.

From stackoverflow
  • Have a look at radix sort.

    Daniel Lew : Just a caveat, radix sort is only linear if you have a fixed max length for your keys... since you have a range of integers, then yes, it can be linear, but this won't always be the case.
    GoatRider : This is also known as "bucket sort".
  • Also take a look at related sorts too: pigeonhole sort or counting sort, as well as radix sort as mentioned by Pukku.

    kunjaan : Dont you think n^3-1 is a little too large to use counting sort? if n=100 you would have 100^3 space just to sort. He needs to change the base of the integers and use Radix sort.
  • A Set of a limited range of numbers can be represented by a bitmap of RANGE bits. In this case, a 500mb bitmap, so for anything but huge lists, you'd be better off with Radix Sort. As you encounter the a number k, bitmap[k] = 1. Single traversal through list, O(N).

    Pukku : Note that n might not equal 2.
  • It's really simple, if n=2 and numbers are unique:

    • Construct an array of bits (2^31-1 bits => ~256MB). Initialize them to zero.
    • Read the input, for each value you see set the respective bit in the array to 1.
    • Scan the array, for each bit set, output the respective value.

    Complexity => O(2n)

    Otherwise, use Radix Sort:

    Complexity => O(kn) (hopefully)

    Daniel Brückner : The question says n^31 and not 2^31. Further you assume that no number appears more than once.
    Ash : I'm assuming n=2. I think that's a typo. After all, we don't typically use other bases than 2. You're right, I'm (probably incorrectly) assuming numbers are not repeated!
    Ash : danbruc, I don't know your background, but my answer is very valid and well balanced (if I may say so).
  • wikipedia shows quite many different sorting algorithms and their complexities. you might want to check them out

  • When people say "sorting algorithm" they often are referring to "comparison sorting algorithm", which is any algorithm that only depends on being able to ask "is this thing bigger or smaller than that". So if you are limited to asking this one question about the data then you will never get more than n*log(n) (this is the result of doing a log(n) search of the n factorial possible orderings of a data set).

    If you can escape the constraints of "comparison sort" and ask a more sophisticated question about a piece of data, for instance "what is the base 10 radix of this data" then you can come up with any number of linear time sorting algorithms, they just take more memory.

    This is a time space trade off. Comparason sort takes little or no ram and runs in N*log(n) time. radix sort (for example) runs in O(n) time AND O(log(radix)) memory.

  • alike algo is possible:
    M;// unsorted array
    lngth; //number items of M
    for(int i=0; i < lngth; i++)sorted[M[i]];
    it's alone possible algo for linear complexity, but it has complexity O(k*N) by ram (N - number array elements, k -- element's len)

Request a 2nd url with the same HttpWebRequest obj

I want to do something like this

{
    HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://google.com");
    WebRequestObject.KeepAlive = true;
    //do stuff
    WebRequestObject.Something("http://www.google.com/intl/en_ALL/images/logo.gif");
    //more here
}

How do i keep the connection alive and go to multiple urls using that same alive connection?

From stackoverflow
  • You simply use another HttpWebRequest object and provided that you set KeepAlive to true in both cases the internal HTTP connection manager in the .NET Framework should handle things for you. See the MSDN documentation for the KeepAlive property for more info on this.

    Noldorin : Also, if you want to confirm this, just use a packet analyser such as Wireshark to monitor your HTTP traffic.

Enterprise Library 4.1 Exception policy

Hello,

I am using Enterprise Library 4.1 and want to implement Exception handling and logging. I am able to setup one policy that handles general Exceptions of the System.Exception type. I call this policy 'Data Access Policy'.

In a general application development rule, how many policies should I create? What are the best practices for catching SqlExceptions? Should a separate policy be defined?

What I am looking for is some suggestions from folks who develop applications using Enterprise Library and how they setup the policies for exception handling and some examples would help.

Thanks

From stackoverflow
  • I am trying to do the same thing in 4.1 to catch generic errors. Can you share any code that you used to create your generic policy. I want true errors to bubble down so I can see the root cause. Any help would be appreciated.

    Picflight : Mike, I put this on side burner for now, I will post some of samples when I get around to it.

Differences Between Rijndael and AES

I'm investigating encryption algorithms - can someone give me a quick rundown of the differences between Rijndael and AES?

From stackoverflow

Calling unknown Python functions

This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.

How do I call a function from a string, i.e.

functions_to_call = ["func_1", "func_2", "func_3"]

for f in functions_to_call:
    call f
From stackoverflow
  • functions_to_call = ["func_1", "func_2", "func_3"]
    
    for f in functions_to_call:
        eval(f+'()')
    

    Edited to add:

    Yes, eval() generally is a bad idea, but this is what the OP was looking for.

    Teifion : This works perfectly, I'm not sure why it has so few upvotes.
    nosklo : -1 for not mentioning that the use of eval is a bad idea overall.
    bobince : indeed. There is no reason to use eval() here; `locals()[f]()` would have done fine. That's still a very questionable way of doing it, but way better than eval().
    gregturn : getattr works better using strings, which is ALSO what the OP was looking for. We shouldn't be spreading eval() when getattr() will do the job just as well.
    tgray : @nosklo, Does every answer really need to mention that eval is bad? It would probably suffice if you just picked apart the atrocity that is the eval function in your own answer.
    nosklo : @tgray: In my opinion, teaching a newbie to use eval like that is a bad thing, and should be downvoted.
    tgray : @nosklo, point taken... see comment on your answer for a follow-up question.
    Teifion : I'm well aware of the evils of eval, I came across it in PHP a few years ago. Thank you though for your concern.
    dF : +1 for ATFQ. Other answers have pointed out the problems with eval and suggested alternatives, but it's still worth knowing about it.
  • how do you not know the name of the function to call? Store the functions instead of the name:

    functions_to_call = [int, str, float]
    
    value = 33.5
    
    for function in functions_to_call:
        print "calling", function
        print "result:", function(value)
    
    Teifion : I could explain all about the exact program but I felt it'd be a waste of space and distract from the specific problem at hand.
    sykora : The functions are stored as strings in the question, not so in your answer, so the answer isn't exactly right...
    Aaron Maenpaa : @sykora ... but it does show a better way if you can twist the requirements of your problem a bit.
    nosklo : @Teifion: I think if you explained your exact problem instead of your failed attempt to solve it, you'd get better suggestions. Storing function names as strings and running them with eval/exec is a bad idea overall. There are always other better options.
    S.Lott : +1: Do not store the function names; store the functions themselves.
    tgray : @nosklo, would you mind going into more detail as to *why* eval is bad? Or link to a resource that explains it...
    nosklo : @tgray: Use of eval is slower, allows arbritary code execution, and shows a bad design. Maybe you should open a new top-level question about the issue.
  • See the eval and compile functions.

    This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the kind argument, eval()‘s return value will be None.

    nosklo : -1 for not mentioning that the use of exec/eval is a bad idea overall.
  • Something like that...when i was looking at function pointers in python..

    def myfunc(x):
        print x
    
    dict = {
        "myfunc": myfunc
    }
    
    dict["myfunc"]("hello")
    
    func = dict.get("myfunc")
    if callable(func):
        func(10)
    
    nosklo : +1 dispatch dicts are a good way to do it if you really need to have a string
    Devin Jeanpierre : "function pointers"? No such thing.
    LB : yep...i know...I was looking for something equivalent...
    RaphaelSP : +1 for the idea (which also allows one to restrict the callable stuff to a specific set), but virtual -1 for calling the dictionary "dict", which will hide the type name in the local scope...
    LB : could you explain it to me a little more ? thanks :-)
    RaphaelSP : Every dictionary is an instance of the type "dict". It can be be build two ways: either using the syntax {}, or by calling the constructor "dict()". Calling a variable (or anything) "dict" prevents you from building a dictionary by calling "dict()", and from testing the type.
    RaphaelSP : Of course, this also applies to any other built-in type, and "dict" by itself is not that important. But still.
  • You can use the python builtin locals() to get local declarations, eg:

    def f():
        print "Hello, world"
    
    def g():
        print "Goodbye, world"
    
    for fname in ["f", "g"]:
        fn = locals()[fname]
        print "Calling %s" % (fname)
        fn()
    

    You can use the "imp" module to load functions from user-specified python files which gives you a bit more flexibility.

    Using locals() makes sure you can't call generic python, whereas with eval, you could end up with the user setting your string to something untoward like:

    f = 'open("/etc/passwd").readlines'
    print eval(f+"()")
    

    or similar and end up with your programming doing things you don't expect to be possible. Using similar tricks with locals() and dicts in general will just give attackers KeyErrors.

    Mark : you're a vicious jerk nosklo. he *did* explain it quite well
    nosklo : @Mark: indeed. I commented the wrong answer, sorry. Removed.
  • Have a look at the getattr function:

    http://docs.python.org/library/functions.html?highlight=getattr#getattr

    import sys
    
    functions_to_call = ["func_1", "func_2", "func_3"]
    
    for f in functions_to_call:
      getattr(sys.modules[__name__], f)()
    
  • Don't use eval! It's almost never required, functions in python are just attributes like everything else, and are accessible either using getattr on a class, or via locals():

    >>> print locals()
    {'__builtins__': <module '__builtin__' (built-in)>,
     '__doc__': None,
     '__name__': '__main__',
     'func_1': <function func_1 at 0x74bf0>,
     'func_2': <function func_2 at 0x74c30>,
     'func_3': <function func_3 at 0x74b70>,
    }
    

    Since that's a dictionary, you can get the functions via the dict-keys func_1, func_2 and func_3:

    >>> f1 = locals()['func_1']
    >>> f1
    <function func_1 at 0x74bf0>
    >>> f1()
    one
    

    So, the solution without resorting to eval:

    >>> def func_1():
    ...     print "one"
    ... 
    >>> def func_2():
    ...     print "two"
    ... 
    >>> def func_3():
    ...     print "three"
    ... 
    >>> functions_to_call = ["func_1", "func_2", "func_3"]
    >>> for fname in functions_to_call:
    ...     cur_func = locals()[fname]
    ...     cur_func()
    ... 
    one
    two
    three
    

How to accept any kind of number into a function as an argument in C#?

c#: How do I accept any kind of number into a function as an argument? Currently my AddDataInt32() asks specifically for Int32, but how I can accept any number, byte, ints signed or unsigned, so I can pass it on to BitConverter.GetBytes()? It's seems silly to write same funct's for each type :(

public void AddDataInt32(Int32 i)
{
    Data = ConcatTwoByteArrays(Data, BitConverter.GetBytes(i));
}
From stackoverflow
  • Well, you could automate it with reflection and generics, but IMO overloads are the better choice - very much like your existing code.

    Reflection / generics example - although I don't really recommend this route:

    static void Main()
    {
        byte[] bytes = GetBytes(123);
    }
    static byte[] GetBytes<T>(T value) {
        return Cache<T>.func(value);
    }
    static class Cache<T> {
        public static readonly Func<T, byte[]> func;
        static Cache() {
            MethodInfo method = typeof(BitConverter)
                .GetMethod("GetBytes", new Type[] { typeof(T) });
            if (method == null) {
                func = delegate { throw new ArgumentException(
                    "No GetBytes implementation for " + typeof(T).Name); };
            } else { 
                func = (Func<T, byte[]>)Delegate.CreateDelegate(
                    typeof(Func<T, byte[]>), method);
            }
        }
    }
    

    You would then mix that with an AddData<T> generic method that calls GetBytes<T> etc.

    Dead account : Nice answer Marc, but you might be overkilling it?
    Marc Gravell : Oh, absolutely ;-p
  • public void AddData(object data )
    {
    }
    

    or

    public void AddData<T>( T data )
    {
    }
    

    Although I think I would prefer overloaded methdos.

  • You can just overload the method...

    public void AddData (Int32 i)
    {...}
    
    public void AddData (Int16 i)
    {...}
    

    etc. One for each number type. When you make the call to the procedure, it will take any form of number that you've coded, with the same procedure name.

    Dead account : +1... you'd have to do this for all 10 overloads... yawn..
    Brian : Hey, that's what MS did for BitConverter, so that's probably your best bet.
    Tom Moseley : I know it's a yawn, but it is, imo, the best way.
    Reed Copsey : This is my preferred approach, as well.

ASP.NET Repeater control or custom implementation?

Hallo,

Recently I have read a couple of posts on varous sites and blogs that ASP.NET Repeater one of the most commonly used and accepted between experienced programmers. Someone actually wrote that he consider the asp.net programmer better if he mentions that he often use this control in a job interview. The fact that I used it rarely maybe makes me a beginner :) This is implementation I have used when I needed some control repeated dynamically.

public class MyUserControl:UserControl
{
    LocalizedCheckBox chb;
    LocalizedLabel lbl;
    TextBox txt;


    public MyUserControl()
    {
        //Instantiate controls
    //do something with them
}

public bool Checked
{
 get{ return chb.Checked;}
}
public string Text
{
 get{ return txt.Text; }
}
}


public partial class MyParentControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //           
    }
protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

    foreach('something')
 {
  MyUserControl ctr = new MyUserControl();
  ctr.Text="some value";
  ctr.Checked= false;
  this.Panel1.Controls.Add(ctr);
 }
    }
protected void btn_Click(object sender, EventArgs e)
    {
        foreach (MyUserControl dControl in this.Panel1.Controls.OfType<MyUserControl>())
        {
            //do something
 string text = dControl.Text;
        }
    }
}

I have never had a problem with this code even when I added the events on MyUserControl. Of course, that it's possible to achieve the same with repeater control, but I would like to know why(or is it) better to use repeater.

What are the benefits if I use repeater instead?

Thanks

From stackoverflow
  • Repeaters are easily binded to datasources.

  • man, you better use repeater or much better use listvew in Net 3.5, why ? -because it is super easy to databind to any datasource, using Eval for controls inside of it. - you get many templates for your like , i use it a lot when the database return no result, you can put a message here to inform the user instead of showing blank screen. - you can control the rendering, whither you want Tables, Div, UL, you just name it.

    i highly recommend to invest in the new listview for repeating stuff.

    hope this helps

    Misha N. : thanks man, this kind of answers wanted to see i'll take a look at the listview. But when I look at examples of repeaters I cant see it that easy if repeated control is complicated with several events, properties...
    : u r welcome man, will everything can get as complex as you want it to be, but usually you can access all controls properties and events inside any databound control by using the Ondatabound, Onitem create, etc events of the listview, Grid, etc.. then from there you use find control and cast it

How to Disable Windows TCP/IP Stack in VC++ [Programmatically]

Hi

I wanted to know How to Disable Windows TCP/IP Stack in VC++ [ Programmatically ].

We are doing some raw socket programming using winpcap. So our application does not need Windows TCP/IP Stack and We Want to uninstall it the moment our application starts.

Please help.

Thanks in Advance.

From stackoverflow
  • The TCP/IP stack is an essential part of any modern OS, including recent versions of MS Windows. As explained on MS knowlegebase Q299357 (speaking about Win XP):

    Because TCP/IP is a core component of Windows, you cannot remove it.

    At any rate, even if it were possible, no program that uses TCP/IP (which is most modern softtware, since most contain some kind of net integration, auto update etc.) would work, and most would probably fail in mysterious ways, since no one tested that configuration.

    So the short answer is: Don't do it.

    Maybe you could explain why you feel it necessary to remove TCP/IP networking? Then we might be able to help you.

    Edit:

    Based on your comment below, if you want bypass/disable the ARP handling of the TCP/IP stack, then WinPcap should let you do that. If not, you probably need to write your own Windows network driver. Again, this seems extremely complicated and intrusive. Could you please describe what your application does and why you even need to mess around with low-level networking?

    mahesh : sleske, We are building application where in we have ARP Module that sends and reply quires. So we do not want Windows TCP/IP stack handle this ARP Request/Reply, We want to handle it.
    mahesh : So it would be great full if you could tell us how to do so. As you can uninstall TCP/IP Stack in "Local Area Connection Properties Dialog" in Windows.
    sleske : Please put that information into your question, so others can read & answer it. I don't know enough about Windows internals to help here.
    sleske : And no, as far as I understand you cannot uninstall TCP/IP stack, at least not on XP (see above).
    mahesh : sleske : thanks for your answer. I checked it. It have only Enable/Disable Check Box Button. And i wanted to Disable it thats it. :)
    mahesh : @sleske, Windows Stack Reply ARP request we dont want that, we want to reply it. We dont want windows stack to eat all ARP request/replies, we want the whole ownership of ARP request/reply. Thank you :
  • Disabling TCP/IP is not that uncommon. We tend to disable it on our host machine so that the VMs can have uninterrupted use of the IP stack.

    You can disable it manually by going to the connection properties page for the adapter in question and unchecking the TCP/IP box (there may be more than one if IPv6 is installed).

    After some brief investigation it looks as though WMI does not support changing this property programatically. However, it looks as though HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage\Bind is the key where each adapter with TCP/IP enabled is stored. Removing the adapter from that list (using the win32 registry APIs) may disable TCP/IP.

    Be careful when testing this...

  • You will need to call WSCDeinstallProvider which is documented on MSDN. You will also need to enumerate the providers using WSCEnumProtocols.

    I'm not sure if what you are attempting will work, but I wish you the best of luck. Let us know if you succeed.

Hibernate/NHibernate mapping file editor

I'm looking for an editor that has the help from

http://www.hibernate.org/hib_docs/nhibernate/html/mapping.html

built in, and allows simple editing of the XML files in a GUI fashion. I realise there's CodeSmith and MyGeneration, but from what I remember these only go one way, and don't allow editing existing HBM files.

From stackoverflow
  • I don't believe there is an editor for Hibernate/NHibernate mapping files that has context-sensitive help. If you are a .NET developer (using NHibernate and Visual Studio .NET) you can edit the mappings with IntelliSense by registering a schema document: see Using NHibernate with Visual Studio .NET for instructions.

    Another option to consider is using the NHibernate's Fluent API. This replaces mapping files with strongly-typed C# code.

    Sebastian Sedlak : +1 for Fluent Nhibernate
  • There is another option with Visual Studio. If you have Resharper you can download the plug-in for NHibernate mapping files. This solution has worked out perfectly for me. You can read more about the plug in here: http://nhplugin.lieser-online.de/. Hope this works for you.

    fordan : This one doesn't work with Resharper 4.5
  • Probably worth taking a look at the NHibernate Query Analyzer by Oren Eini. Primarily used to analyze HQL queries it also has a fairly useful HBM editor:

    NHibernate Query Analyzer Screenshot

    Old Project Page (with flash demo): http://ayende.com/projects/nhibernate-query-analyzer.aspx

    New Project Page: http://www.assembla.com/wiki/show/NHibernateQueryAnalyzer

    This will allow editing for HBM files and will show all of the available attributes for each mapping node.

    Given that you can download the source code it wouldn't be that trivial to add the inline help.

    Chris S : This looks the most promising, except it gets an exception when loading "Could not load file or assembly 'System.Data.SQLite, Version=1.0.35.1, Culture=neutral, PublicKeyToken=db937bc2d44ff139' or one of its dependencies. An attempt was made to load a program with an incorrect format"
    Codebrain : Try downloading and installing the correct version from here:http://sourceforge.net/project/showfiles.php?group_id=132486&package_id=145568
    Chris S : I downloaded + recompiled and go it working. I think this is probably the closest to the answer I'll get so I'll give you the tick :)
    Codebrain : thanking you sir!
  • Why not use ActiveWriter to generate the mappings? You can always edit them afterwards. AW generates the model / mapping for both NHibernate and ActiveRecord. The editor runs WITHIN Visual Studio.NET and you can do drag-drop via server explorer.

  • The best option I've come across is is IDEA's Hibernate/JPA editor. IDEA is not free, however.

  • Have you tried Hibernate's own Eclipse plug-in named Hibernate Tools for Eclipse and Ant?

    http://www.hibernate.org/255.html

    Even if you dont have expirience with Eclipse and its add-ons it should be fairly straightforward to install and use their addon:

    Just download it, unzip it into the eclipse directory, and fire up the IDE. What you need to do next is to open up the Hibernate perspective.

  • I'm using VisualStudio and the schema (nhibernate-mapping.xsd) to activate the intellisense. The plug-in for R# is useful to check the mapping with the class.