source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
70,528 | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod() . How, then, can one explain this >>>> class MyClass:... def myPublicMethod(self):... print 'public method'... def __myPrivateMethod(self):... print 'this is private!!'...>>> obj = MyClass()>>> obj.myPublicMethod()public method>>> obj.__myPrivateMethod()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: MyClass instance has no attribute '__myPrivateMethod'>>> dir(obj)['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']>>> obj._MyClass__myPrivateMethod()this is private!! What's the deal?! I'll explain this a little for those who didn't quite get that. >>> class MyClass:... def myPublicMethod(self):... print 'public method'... def __myPrivateMethod(self):... print 'this is private!!'...>>> obj = MyClass() I create a class with a public method and a private method and instantiate it. Next, I call its public method. >>> obj.myPublicMethod()public method Next, I try and call its private method. >>> obj.__myPrivateMethod()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: MyClass instance has no attribute '__myPrivateMethod' Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running dir() on the object reveals a new magical method that Python creates magically for all of your 'private' methods. >>> dir(obj)['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] This new method's name is always an underscore, followed by the class name, followed by the method name. >>> obj._MyClass__myPrivateMethod()this is private!! So much for encapsulation, eh? In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside. For example: >>> class Foo(object):... def __init__(self):... self.__baz = 42... def foo(self):... print self.__baz... >>> class Bar(Foo):... def __init__(self):... super(Bar, self).__init__()... self.__baz = 21... def bar(self):... print self.__baz...>>> x = Bar()>>> x.foo()42>>> x.bar()21>>> print x.__dict__{'_Bar__baz': 21, '_Foo__baz': 42} Of course, it breaks down if two different classes have the same name. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/70528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1943957/"
]
} |
70,529 | In order to know how many times a pattern exists in current buffer, I do: :%s/pattern-here/pattern-here/g It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status. Is there a more elegant way to count? | To avoid the substitution, leave the second pattern empty, and add the “n” flag: :%s/pattern-here//gn This is described as an official tip . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/70529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6984/"
]
} |
70,537 | I have heard there is a way to cheat single inheritance and implement multiple inheritance in Java. Does anyone know how to implement this(with out using interface)? Just out of curiosity ;-) | Sure you can, but it's tricky and you should really consider if that's the way you want to go. The idea is to use scope-based inheritance coupled with type-based one. Which is type-talk for saying that for internal purposes, inner classes "inherit" methods and fields of the outer class. It's a bit like mixins, where the outer class is mixed-in to the inner class, but not as safe, as you can change the state of the outer class as well as use its methods. Gilad Bracha (one of the main java language designers) wrote a paper discussing that.So, suppose you want to share some methods for internal use between some unrelated classes (e.g, for string manipulation), you can create sub classes of them as inner classes of a class that has all the needed methods, and the sub classes could use methods both from their super classes and from the outer class. Anyway, it's tricky for complex classes, and you could get most of the functionality using static imports (from java 5 on). Great question for job interviews and pub quizzes, though ;-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
} |
70,560 | When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that. The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results. Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... - a "search engine", and then we can sell ads, and then ... No, seriously, what are the common ways to solve this problem? | One approach is the so called bag-of-words model. As you guessed, first you count how many times words appear in the text (usually called document in the NLP-lingo). Then you throw out the so called stop words, such as "the", "a", "or" and so on. You're left with words and word counts. Do this for a while and you get a comprehensive set of words that appear in your documents. You can then create an index for these words:"aardvark" is 1, "apple" is 2, ..., "z-index" is 70092. Now you can take your word bags and turn them into vectors. For example, if your document contains two references for aardvarks and nothing else, it would look like this: [2 0 0 ... 70k zeroes ... 0]. After this you can count the "angle" between the two vectors with a dot product . The smaller the angle, the closer the documents are. This is a simple version and there other more advanced techniques. May the Wikipedia be with you . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
70,573 | I am new to any scripting language. But, still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, what is the best online resource to learn Perl? | If you already know a bit of perl, PerlMonks is a great online resource. You can ask questions in their Seekers of Perl Wisdom section and the answers are often of very high quality. Many people who keep up with the latest developments in Perl hang out there. As an added bonus, if you ask a clear question, many times the people there take the time to look at the underlying problem and will point out alternate approaches rather than simply taking your question at face value. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/70573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11372/"
]
} |
70,577 | I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python? [Response Summary:] Some Online Resources: http://docs.python.org/tut/tut.html - Beginners http://diveintopython3.ep.io/ - Intermediate http://www.pythonchallenge.com/ - Expert Skills http://docs.python.org/ - collection of all knowledge Some more: A Byte of Python. Python 2.5 Quick Reference Python Side bar A Nice blog for beginners Think Python: An Introduction to Software Design | If you need to learn python from scratch - you can start here: http://docs.python.org/tut/tut.html - good begginers guide If you need to extend your knowledge - continue here http://diveintopython3.ep.io/ - good intermediate level book If you need perfect skills - complete this http://www.pythonchallenge.com/ - outstanding and interesting challenge And the perfect source of knowledge is http://docs.python.org/ - collection of all knowledge | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/70577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11372/"
]
} |
70,579 | When creating the id attributes for HTML elements, what rules are there for the value? | For HTML 4 , the answer is technically: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters. The id attribute is case sensitive in XHTML . As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery . Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids. For example, the HTML declaration <div id="first.name"></div> is valid. You can select that element in CSS as #first\.name and in jQuery like so: $('#first\\.name'). But if you forget the backslash, $('#first.name') , you will have a perfectly valid selector looking for an element with id first and also having class name . This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead. You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName ?" because you will always know that you should type first_name . Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them. A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive . That meant that if you had typed id="firstName" in your HTML (lower-case 'f') and #FirstName { color: red } in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/70579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6093/"
]
} |
70,602 | I have successfully connected to an Oracle database (10g) from C# (Visual Studio 2008) by downloading and installing the client administration tools and Visual Studio 2008 on my laptop. The installation footprint for Oracle Client tools was over 200Mb, and quite long winded. Does anyone know what the minimum workable footprint is? I am hoping that it's a single DLL and a register command, but I have the feeling I need to install an oracle home, and set various environment variables. I am using Oracle.DataAccess in my code. | You need an Oracle Client to connect to an Oracle database. The easiest way is to install the Oracle Data Access Components . To minimize the footprint, I suggest the following : Use the Microsoft provider for Oracle (System.Data.OracleClient), which ships with the framework. Download the Oracle Instant Client Package - Basic Lite : this is a zip file with (almost) the bare minimum. I recommend version 10.2.0.4, which is much smaller than version 11.1.0.6.0. Unzip the following files in a specific folder : v10 : oci.dll orannzsbb10.dll oraociicus10.dll v11 : oci.dll orannzsbb11.dll oraociei11.dll On a x86 platform, add the CRT DLL for Visual Studio 2003 (msvcr71.dll) to this folder, as Oracle guys forgot to read this ... Add this folder to the PATH environment variable. Use the Easy Connect Naming method in your application to get rid of the infamous TNSNAMES.ORA configuration file. It looks like this : sales-server:1521/sales.us.acme.com . This amounts to about 19Mb (v10). If you do not care about sharing this folder between several applications, an alternative would be to ship the above mentioned DLLs along with your application binaries, and skip the PATH setting step. If you absolutely need to use the Oracle provider (Oracle.DataAccess), you will need : ODP .NET 11.1.0.6.20 (the first version which allegedly works with Instant Client). Instant Client 11.1.0.6.0, obviously. Note that I haven't tested this latest configuration... | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6910/"
]
} |
70,614 | I've just introduced a friend to GNU Screen and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent Screen utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.? It would be awesome. | I've been using Screen for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are: ^A ^W - window list, where am I^A ^C - create new window^A space - next window^A p - previous window^A ^A - switch to previous screen (toggle)^A [0-9] - go to window [0-9]^A esc - copy mode, which I use for scrollback I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both ^Q and ^A ^Q to try to unlock it. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/70614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6414/"
]
} |
70,689 | What is an efficient way to implement a singleton design pattern in Java? | Use an enum: public enum Foo { INSTANCE;} Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video . Also see slides 30-32 of his presentation ( effective_java_reloaded.pdf ): The Right Way to Implement a Serializable Singleton public enum Elvis { INSTANCE; private final String[] favoriteSongs = { "Hound Dog", "Heartbreak Hotel" }; public void printFavorites() { System.out.println(Arrays.toString(favoriteSongs)); }} Edit: An online portion of "Effective Java" says: "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton ." | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/70689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11581/"
]
} |
70,694 | I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage. I created a task to run under my admin user, and to start the program, cmd with the arguments /c net start mssqlserver . When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped: action "C:\Windows\system32\cmd.EXE" with return code 2 . Any suggestions? | Use an enum: public enum Foo { INSTANCE;} Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video . Also see slides 30-32 of his presentation ( effective_java_reloaded.pdf ): The Right Way to Implement a Serializable Singleton public enum Elvis { INSTANCE; private final String[] favoriteSongs = { "Hound Dog", "Heartbreak Hotel" }; public void printFavorites() { System.out.println(Arrays.toString(favoriteSongs)); }} Edit: An online portion of "Effective Java" says: "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton ." | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/70694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
]
} |
70,705 | In my day job I, and others on my team write a lot of hardware models in Verilog-AMS, a language supported primarily by commercial vendors and a few opensource simulator projects. One thing that would make supporting each others code more helpful would be a LINTER that would check our code for common problems and assist with enforcing a shared code formatting style. I of course want to be able to add my own rules and, after I prove their utility to myself, promote them to the rest of the team.. I don't mind doing the work that has to be done, but of course also want to leverage the work of other existing projects. Does having the allowed language syntax in a yacc or bison format give me a leg up? or should I just suck each language statement into a perl string, and use pattern matching to find the things I don't like? (most syntax and compilation errors are easily caught by the commercial tools.. but we have some of our own extentions.) | lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone. There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-) Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6314/"
]
} |
70,721 | Last Friday where I work, an oracle client was upgarded and our IIS server from version 9 to version 10. Now that its on version 10, we are seeing a lot of connections being open up to the database. It is opening up so many connections that we cannot log onto the database using tools like PlSQL developer or Toad. We never had an issue like this when the oracle client was at version 9. Because of the number of clients that exists on this particular box, i dont think it will be possible to revert back to the Oracle 9 client.Is anyone aware of this problem or know of any possible work arounds? Any help is greatly appreciated | lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone. There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-) Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
]
} |
70,724 | In my job we have to deploy an application on various environments. It's a standard WAR file which needs a bit of configuration, deployed on Tomcat 6. Is there any way of creating a 'deployment package' with Tomcat so that you just extract it and it sets up Tomcat as well as your application? I'm not sure that creating a .zip file with the Tomcat folder would work! It certainly wouldn't install the service. Suggestions welcome! I should note that - at the moment - all apps are deployed on Windows servers. Thanks,Phill | lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone. There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-) Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
70,758 | I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there.You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem.Does anyone know of a better way? | Here's another solution that I just did, seeing that I understand what you want to do: Here's your ASCX / ASPX <asp:ListView ID="ListView1" runat="server" DataSourceID="MyDataSource" ItemPlaceholderID="itemPlaceHolder" OnDataBound="ListView1_DataBound"> <LayoutTemplate> <table border="1"> <tr> <td>Name</td> <td>Age</td> <td runat="server" id="tdIsSuperCool">IsSuperCool</td> </tr> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </table> </LayoutTemplate> <ItemTemplate> <tr> <td><%# Eval("Name") %></td> <td><%# Eval("Age") %></td> <td runat="server" id="myCol" visible='<%# (bool)Eval("IsSuperCool") %>'>true</td> </tr> </ItemTemplate> </asp:ListView> <asp:ObjectDataSource ID="MyDataSource" runat="server" DataObjectTypeName="BusinessLogicLayer.Thing" SelectMethod="SelectThings" TypeName="BusinessLogicLayer.MyObjectDataSource" /> Here's the code behind /// <summary>/// Handles the DataBound event of the ListView1 control./// </summary>/// <param name="sender">The source of the event.</param>/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>protected void ListView1_DataBound(object sender, EventArgs e){ ListView1.FindControl("tdIsSuperCool").Visible = false;} Do whatever you want in the databound. Because the column is now runat server, and you're handling the DataBound of the control, when you do ListView1.FindControl("tdIsSuperCool") you're in the Layout template so that works like a champ. Put whatever business logic that you want to control the visibility of the td and you're good. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10186/"
]
} |
70,773 | What are the pros / cons of using pthread_cond_wait or using a semaphore ?I am waiting for a state change like this : pthread_mutex_lock(&cam->video_lock);while(cam->status == WAIT_DISPLAY) { pthread_cond_wait(&cam->video_cond, &cam->video_lock);}pthread_mutex_unlock(&cam->video_lock); Using a properly initialised semaphore, I think I could do it like this : while(cam->status == WAIT_DISPLAY) { sem_wait(&some_semaphore);} What are the pros and cons of each method ? | A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore. A condition variable is a bit more forgiving in some respects. You can for example use cond_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never). So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again. It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions. Condition variables escape this problem, because calling cond_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond_wait returns. IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11589/"
]
} |
70,797 | How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line? | To read user input you can try the cmd module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input ( input for Python 3+) for reading a line of text from the user. text = raw_input("prompt") # Python 2text = input("prompt") # Python 3 Command line inputs are in sys.argv . Try this in your script: import sysprint (sys.argv) There are two modules for parsing command line options: optparse (deprecated since Python 2.7, use argparse instead) and getopt . If you just want to input files to your script, behold the power of fileinput . The Python library reference is your friend. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/70797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
70,842 | How should I run another program from within my C program? I need to be able to write data into STDIN of the launched program (and maybe read from it's STDOUT ) I am not sure if this is a standard C function. I need the solution that should work under Linux. | You want to use popen . It gives you a unidirectional pipe with which you can access stdin and stdout of the program. popen is standard on modern unix and unix-like OS, of which Linux is one :-) Type man popen in a terminal to read more about it. EDIT Whether popen produces unidirectional or bidirectional pipes depends on the implementation. In Linux and OpenBSD , popen produces unidirectional pipes, which are read-only or write-only. On OS X , FreeBSD and NetBSD popen produces bidirectional pipes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6974/"
]
} |
70,850 | What advantage, if any, is provided by formatting C code as follows: while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); }if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); }unlock_file(lockdir); versus something more typical such as while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3);}if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1);}unlock_file(lockdir); I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks. Only advantage I can see is just to be different and leave your fingerprints on code that you've written. I notice vim formatting would have to be hand-rolled to handle the top case. | The top example is know as "Whitesmiths style". Wikipedia's entry on Indent Styles explains several styles along with their advantages and disadvantages. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/70850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974/"
]
} |
70,855 | Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes. The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas? | Multi-threading is possible in php Yes you can do multi-threading in PHP with pthreads From the PHP documentation : pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects. Warning : The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only. Simple Test #!/usr/bin/php<?phpclass AsyncOperation extends Thread { public function __construct($arg) { $this->arg = $arg; } public function run() { if ($this->arg) { $sleep = mt_rand(1, 10); printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep); sleep($sleep); printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg); } }}// Create a array$stack = array();//Initiate Multiple Threadforeach ( range("A", "D") as $i ) { $stack[] = new AsyncOperation($i);}// Start The Threadsforeach ( $stack as $t ) { $t->start();}?> First Run 12:00:06pm: A -start -sleeps 512:00:06pm: B -start -sleeps 312:00:06pm: C -start -sleeps 1012:00:06pm: D -start -sleeps 212:00:08pm: D -finish12:00:09pm: B -finish12:00:11pm: A -finish12:00:16pm: C -finish Second Run 12:01:36pm: A -start -sleeps 612:01:36pm: B -start -sleeps 112:01:36pm: C -start -sleeps 212:01:36pm: D -start -sleeps 112:01:37pm: B -finish12:01:37pm: D -finish12:01:38pm: C -finish12:01:42pm: A -finish Real World Example error_reporting(E_ALL);class AsyncWebRequest extends Thread { public $url; public $data; public function __construct($url) { $this->url = $url; } public function run() { if (($url = $this->url)) { /* * If a large amount of data is being requested, you might want to * fsockopen and read using usleep in between reads */ $this->data = file_get_contents($url); } else printf("Thread #%lu was not provided a URL\n", $this->getThreadId()); }}$t = microtime(true);$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));/* starting synchronization */if ($g->start()) { printf("Request took %f seconds to start ", microtime(true) - $t); while ( $g->isRunning() ) { echo "."; usleep(100); } if ($g->join()) { printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data)); } else printf(" and %f seconds to finish, request failed\n", microtime(true) - $t);} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/70855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11190/"
]
} |
70,909 | With Hibernate, can you create a composite ID where one of the columns you are mapping to the ID can have null values? This is to deal with a legacy table that has a unique key which can have null values but no primary key. I realise that I could just add a new primary key column to the table, but I'm wondering if there's any way to avoid doing this. | No. Primary keys can not be null. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
70,947 | I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA? | Yes. ThisWorkbook.RefreshAll Or, if your Excel version is old enough, Dim Sheet as WorkSheet, Pivot as PivotTableFor Each Sheet in ThisWorkbook.WorkSheets For Each Pivot in Sheet.PivotTables Pivot.RefreshTable Pivot.Update NextNext | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/70947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
]
} |
70,956 | Is there a good way to exclude certain pages from using a HTTP module? I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config: <system.web> <!-- ... --> <httpModules> <add name="SessionValidationModule" type="SessionValidationModule, SomeNamespace" /> </httpModules></system.web> To exclude the module from the page, I tried doing this (without success): <location path="ToBeExcluded"> <system.web> <!-- ... --> <httpModules> <remove name="SessionValidationModule" /> </httpModules> </system.web></location> Any thoughts? | You could use an HTTPHandler instead of an HTTPModule. Handlers let you specify a path when you declare them in Web.Config. <add verb="*" path="/validate/*.aspx" type="Handler,Assembly"/> If you must use an HTTPModule, you could just check the path of the request and if it's one to be excluded, bypass the validation. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308/"
]
} |
70,992 | Relating to my earlier question , I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this: select distinct o from Order o left join fetch o.orderLines Assuming a model with an Order class which has a set of OrderLines in it. My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an Order for each OrderLine . Am I doing the right thing? Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using FetchType.EAGER as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache? | Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed. I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48310/"
]
} |
71,022 | How do you return 1 value per row of the max of several columns: TableName [Number, Date1, Date2, Date3, Cost] I need to return something like this: [Number, Most_Recent_Date, Cost] Query? | Here is another nice solution for the Max functionality using T-SQL and SQL Server SELECT [Other Fields], (SELECT Max(v) FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]FROM [YourTableName] Values is the Table Value Constructor . "Specifies a set of row value expressions to be constructed into a table. The Transact-SQL table value constructor allows multiple rows of data to be specified in a single DML statement. The table value constructor can be specified either as the VALUES clause of an INSERT ... VALUES statement, or as a derived table in either the USING clause of the MERGE statement or the FROM clause." | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/71022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11703/"
]
} |
71,030 | I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like: mvn install -Dmaven.repository=http://example.com/maven2 The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle. | You can do this but you're probably better off doing it in the POM as others have said. On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though The example below specifies two remote repositories and a custom local repository. mvn package -Dmaven.repo.remote=http://www.ibiblio.org/maven/,http://myrepo -Dmaven.repo.local="c:\test\repo" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/71030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113/"
]
} |
71,036 | What do you do if members of your team are not cooperative during scrum meetings?They either provide a very high level definition of what they are currently working on, ("working on feature x"), or go into extremely irrelevant details, in spite of being well educated in SCRUM methodology .This causes the scrum meeting to be ineffective and boring. As a scrum master, what are your techniques to getting the best out of people during the meeting? Edited to add: What technique do you use to stop someone who is talking too much, without being offensive? What technique do you use to encourage someone to provide a more detailed answer? How do you react when you find yourself being the only one who listens, while other team members just sit there and maybe even fall asleep? | First of all... make sure folks are standing up... and not even leaning on the wall or a desk. At a high level, I would say that, whenever you face issues on the team, the best response is to ask the team for solutions. However, here are some of the techniques I've used for the issues you're facing. Talks too much have him/her stand on one leg have him/her hold the scrum "speaking" token in an outstretched hand while they speak. Add a flip chart to the scrum to list tabled issues... when someone gets longwinded on a topic that is not scrum-meeting-worthy, interrupt and say "Hey - great point. I'm not sure everyone needs to discuss this, how 'bout if we park this for a follow-up discussion?" A key to making this successful is to actually follow-up afterwards and get the side conversation scheduled. Alternatively, the speaker may just say "Not necessary... I'll be working with Joe this afternoon on this" or something like that, which accomplishes the goal of reducing the windedness without the need to schedule the follow-up. Need more detail . Is this for the scrum master's benefit or the team's? wait until afterwards to ask the individual more detailed questions. If you think the team also needs to know them, coach the team member by conveying (in your after-scrum questioning) that "this is the sort of thing that I think Joe Smith would be helped in hearing from you, what do you think?" Team doesn't listen . Ask them on an individual basis. "Sally, I noticed that you don't seem to be getting much out of the Scrum. How can we adjust it to make it valuable for you?". Post questions to others during the scrum. Like if Sally says "I integrated with Bob's code yesterday", ask Bob "how'd that go?" (I'd use this sparingly... to guard against scrums taking too long). I've found that sometimes team members tend towards old habits by looking at the scrum master or project manager when they speak. When this happens alot, I alter my gaze to look away, which almost forces the speaker to gain eye contact with other members of the team, which may help the other members of the team to pay attention. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11710/"
]
} |
71,057 | Does anyone know of a good code obsfucator for Perl? I'm being ask to look into the option of obsfucating code before releasing it to a client. I know obsfucated code can still be reverse engineered, but that's not our main concern. Some clients are making small changes to the source code that we give them and it's giving us nightmares when something goes wrong and we have to fix it, or when we release a patch that doesn't work with what they've changed. So the intention is just to make it so that it's difficult for them to make their own changes to the code(they're not supposed to be doing that anyway). | I've been down this road before and it's an absolute nightmare when you have to work on "obfuscated" code because it drives up costs tremendously trying to debug a problem on the client's server when you, the developer, can't read the code. You wind up with "deobfuscators", copying the "real code" to the client's server or any of a number of other issues which just become a real hassle to maintain. I understand where you're coming from, but it sounds like management has a problem and they're looking to you to implement a chosen solution rather than figuring out what the correct solution is. In this case, it sounds like it's really a licensing or contractual issue. Let 'em have the code open source, but make it a part of the license that any changes they submit have to come back to you and be approved. When you push out patches, check the md5 sums of all code and if it doesn't match what's expected, they're in license violation and will be charged accordingly (and it should be a far, far higher rate). (I remember one company which let us have the code open source, but made it clear that if we changed anything, we've "bought" the code for $25,000 and they were no longer responsible for any bug fixes or upgrades unless we bought a new license). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11708/"
]
} |
71,069 | Maven spews out far too many lines of output to my taste (I like the Unix way: no news is good news). I want to get rid of all [INFO] lines, but I couldn't find any mention of an argument or config settings that controls the verbosity of Maven. Is there no LOG4J-like way to set the log level? | You can try the -q switch . -q , --quiet Quiet output - only show errors | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/71069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483/"
]
} |
71,074 | I can make Firefox not display the ugly dotted focus outlines on links with this: a:focus { outline: none; } But how can I do this for <button> tags as well? When I do this: button:focus { outline: none; } the buttons still have the dotted focus outline when I click on them. (and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots) | button::-moz-focus-inner { border: 0;} | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/71074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
} |
71,077 | I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this? Can encryption be done as a part of the compression itself? | For compression, look at the System.IO.Compression namespace and for encryption look at System.Security.Cryptography . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
71,092 | What is the difference, what is the official terms, are any terms obsolete in ASP.NET 3.5? | UserControl : A custom control, ending in .ascx, that is composed of other web controls. Its almost like a small version of an aspx webpage. It consists of a UI (the ascx) and codebehind. Cannot be reused in other projects by referencing a DLL. WebControl : A control hosted on a webpage or in a UserControl. It consists of one or more classes, working in tandem, and is hosted on an aspx page or in a UserControl. WebControls don't have a UI "page" and must render their content directly. They can be reused in other applications by referencing their DLLs. RenderedControl : Does not exist. May be synonymous to WebControl. Might indicate the control is written directly to the HttpResponse rather than rendered to an aspx page. CompositeControl : Inbetween UserControls and WebControls. They code like UserControls, as they are composed of other controls. There is not any graphical UI for control compositing, and support for UI editing of CompositeControls must be coded by the control designer. Compositing is done in the codebehind. CompositeControls can be reused in other projects like WebControls. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/71092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
]
} |
71,108 | Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in Foo ** ) in C++? | Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns. #include <iostream>using namespace std;struct Foo { int a;};void CreateFoo(Foo** p) { *p = new Foo(); (*p)->a = 12;}int main(int argc, char* argv[]){ Foo* p = NULL; CreateFoo(&p); cout << p->a << endl; delete p; return 0;} This will print 12 But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output. #include <iostream>using namespace std;int main(int argc, char* argv[]){ const char* words[] = { "first", "second", NULL }; for (const char** p = words; *p != NULL; ++p) { cout << *p << endl; } return 0;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
]
} |
71,151 | Using the Python Documentation I found the HTML parser but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page). | Try: import HTMLParser In Python 3.0, the HTMLParser module has been renamed to html.parseryou can check about this here Python 3.0 import html.parser Python 2.2 and above import HTMLParser | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
71,180 | How can I find the last row that contains data in a specific column and on a specific sheet? | How about: Function GetLastRow(strSheet, strColumn) As Long Dim MyRange As Range Set MyRange = Worksheets(strSheet).Range(strColumn & "1") GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).RowEnd Function Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data: Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/71180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
]
} |
71,195 | I was thinking about obfuscating a commercial .Net application. But is it really worth the effort to select, buy and use such a tool? Are the obfuscated binaries really safe from reverse engineering? | You may not have to buy a tool - Visual Studio.NET comes with a community version of Dotfuscator. Other free obfuscation tools are listed here , and they may meet your needs. It's possible that the obfuscated binaries aren't safe from reverse engineering, just like it's possible that your bike lock might be breakable/pickable. However, it's often the case that a small inconvenience is enough to deter would be code/bicycle thieves. Also, if ever it comes time to assert your rights to a piece of code in court, having been seen to make an effort to protect it (by obfuscating it) may give you extra points. :-) You do have to consider the downsides, though - it can be more difficult to use reflection with obfuscated code, and if you're using something like log4net to generate parts of log lines based on the name of the class involved, these messages can become much more difficult to interpret. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9602/"
]
} |
71,203 | Our installer is written with Inno Setup and we are actually quite happy with it. Yet some customers keep asking for an MSI installer which they could more easily distribute via Active Directory. We have already gone to some lengths to make the installer deal really well with automated and unattended installations by extending Inno Setup's /LOADINF -mechanism with our own options. In order to satisfy the customers asking for MSI, I had been thinking about simply wrapping our regular installer inside an MSI, possibly created using WIX. The question is: can I maintain the high configurability which our current installer offers that way? How would I go about exposing the Inno Setup installer's options through the outer MSI in the unattended/mass installation scenario? Note that I haven't really gotten to the point of actually digging into MSI-creation and WIX myself yet. Right now I'm only interested in whether people who do know what they're talking about think this would be a feasible/sensible approach to invest our energy in in the first place... [EDIT:]Initially I thought I could do with the temp extraction and execution approach, i.e. the MSI would simply serve as a vessel for delivering the Inno installer to the target PC and executing it there in /VERYSILENT -mode. But I guess the customers who ask for the MSI also want to be able to uninstall or even modify the install from a central location and I guess that won't be possible in that scenario, would it? P.S.: We do have an old copy of WISE for MSI here as well but that experience was actually the reason why we started using Inno instead to begin with... | No, there's no way to do that while still keeping the functionality your customers are 'implicitly' asking for. The only 'wrapping' in MSI you can do is to extract it on installation and start your InnoSetup installer from the temporary location where you extracted to. MSI is a fundamentally different way of working: InnoSetup (& NSIS & most other installers) take a code-centric approach: you 'program' the 'steps' to install your data. MSI is a database and takes a 'data-centric' approach: you indicate what files should be installed and the MSI 'runtime' does the rest. This gives you versioning and exact control of what goes where. In short, to give your customers what they want (i.e., the ease of deployment that MSI brings with AD), you'll need 'proper' MSI's. Good luck with that, it's a major pain IMHO. But it does give good results once you master MSI & WiX. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9784/"
]
} |
71,254 | When viewing someone else's webpage containing an applet, how can I force Internet Explorer 6.0 to use a a particular JRE when I have several installed? | First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer . Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\ jre1.5.0_15 \bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe . Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer . To get your old version of Java back you need to reverse these steps. Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same). The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
71,257 | How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#. I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it. | Here's my suggestion: [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001), SUSPEND_RESUME = (0x0002), GET_CONTEXT = (0x0008), SET_CONTEXT = (0x0010), SET_INFORMATION = (0x0020), QUERY_INFORMATION = (0x0040), SET_THREAD_TOKEN = (0x0080), IMPERSONATE = (0x0100), DIRECT_IMPERSONATION = (0x0200) } [DllImport("kernel32.dll")] static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); [DllImport("kernel32.dll")] static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] static extern int ResumeThread(IntPtr hThread); [DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)] static extern bool CloseHandle(IntPtr handle);private static void SuspendProcess(int pid){ var process = Process.GetProcessById(pid); // throws exception if process does not exist foreach (ProcessThread pT in process.Threads) { IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { continue; } SuspendThread(pOpenThread); CloseHandle(pOpenThread); }}public static void ResumeProcess(int pid){ var process = Process.GetProcessById(pid); if (process.ProcessName == string.Empty) return; foreach (ProcessThread pT in process.Threads) { IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { continue; } var suspendCount = 0; do { suspendCount = ResumeThread(pOpenThread); } while (suspendCount > 0); CloseHandle(pOpenThread); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9632/"
]
} |
71,323 | I'm trying to replace each , in the current file by a new line: :%s/,/\n/g But it inserts what looks like a ^@ instead of an actual newline. The file is not in DOS mode or anything. What should I do? If you are curious, like me, check the question Why is \r a newline for Vim? as well. | Use \r instead of \n . Substituting by \n inserts a null character into the text. To get a newline, use \r . When searching for a newline, you’d still use \n , however. This asymmetry is due to the fact that \n and \r do slightly different things : \n matches an end of line (newline), whereas \r matches a carriage return. On the other hand, in substitutions \n inserts a null character whereas \r inserts a newline (more precisely, it’s treated as the input CR ). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). xxd shows a hexdump of the resulting file. echo bar > test(echo 'Before:'; xxd test) > output.txtvim test '+s/b/\n/' '+s/a/\r/' +wq(echo 'After:'; xxd test) >> output.txtmore output.txt Before:0000000: 6261 720a bar.After:0000000: 000a 720a ..r. In other words, \n has inserted the byte 0x00 into the text; \r has inserted the byte 0x0a. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/71323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
]
} |
71,328 | I have PHP configured so that magic quotes are on and register globals are off. I do my best to always call htmlentities() for anything I am outputing that is derived from user input. I also occasionally seach my database for common things used in xss attached such as... <script What else should I be doing and how can I make sure that the things I am trying to do are always done. | Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use |escape:'htmlall' modifier to convert all sensitive characters to HTML entities (I use own |e modifier which is alias to the above). My approach to input/output security is: store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements) escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/71328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4012/"
]
} |
71,336 | I'm not sure if many people know about this text-editor? jEdit was kinda big in 2004, but now, Notepad++ seems to have taken the lead(on Windows)Many of the plugins haven't been updated since 2003 and the overal layout and usage is confusing... I'm sure jEdit has many nifty features, but I'll be damned if I can find out where to find them and how to use them. Reading that manual is a fulltime job on it's own. | I've been using jEdit for a few years now, mainly on windows, but also on Ubuntu.I use it for: SQL, awk, batch files, html, xml, javascript...Just about everything except .NET stuff (for which I use Visual Studio). I love it. summary I use jEdit because it has the right balance for me of ease of setting up vs. features and customisability . For me, no other editor strikes quite as good a balance. cons It can be a bit hard to make it do the things you want. pros I love the plugins Being able to define my own syntax highlighting etc. is just what I want from a text editor. The manual is very good and quite readable. I strongly suggest reading it through to get an idea of what jEdit can do for you. (In fact, I suggest this for any software you use) It's cross-platform. I used it just on windows for a long time, but now I also use Ubuntu, and it works there: I can even copy the configuration files over from my windows machine, and everything works. Nice. other editors In the past I did take a look at Notepad++ , but that was a while ago, and it didn't have a nice way to define your own syntax highlighting, which is important for me. I also paid for Textmate and UltraEdit at different times (both very good), but in the end, jEdit comes out on top for me. I also used Eclipse for a year or so. It's fantastic, and it'll do anything you want, but you have to be really into Eclipse to get the most out of it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
]
} |
71,416 | I'm trying to do something like the following: enum E;void Foo(E e);enum E {A, B, C}; which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain? Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as enum E { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X} as project X is not something I want my users to know about. So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people. As for the compiler - it's GCC. | The reason the enum can't be forward declared is that, without knowing the values, the compiler can't know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can't know what storage size has been chosen – it could be a char , or an int , or something else. From Section 7.2.5 of the ISO C++ Standard: The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int . If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type. Since the caller to the function must know the sizes of the parameters to correctly set up the call stack, the number of enumerations in an enumeration list must be known before the function prototype. Update: In C++0X, a syntax for forward declaring enum types has been proposed and accepted. You can see the proposal at Forward declaration of enumerations (rev.3) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/71416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11437/"
]
} |
71,417 | From question How to replace a character for a newline in Vim? . You have to use \r when replacing text for a newline, like this :%s/%/\r/g But when replacing end of lines and newlines for a character, you can do it like: :%s/\n/%/g What section of the manual documents these behaviors, and what's the reasoning behind them? | From vim docs on patterns : \r matches <CR> \n matches an end-of-line - When matching in a string instead of buffer text a literal newline character is matched. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/71417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
]
} |
71,419 | I've heard many programmers, particularly Delphi programmers scorn the use of 'with'. I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting). Here's an example: procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);begin with ARect do FillRectS(Left, Top, Right, Bottom, Value);end; I like using with . What's wrong with me? | One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult. A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer. procedure TMyForm.ButtonClick(...)begin with OtherForm do begin Left := 10; Top := 20; CallThisFunction; end;end; Which Form's CallThisFunction will be called? Self (TMyForm) or OtherForm? You can't know without checking if OtherForm has a CallThisFunction method. And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it's private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn't use the with, but now it doesn't. Using multiple objects in the with multiplies the problems. See http://blog.marcocantu.com/blog/with_harmful.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11781/"
]
} |
71,423 | I want to disable the selection of certain rows in a datagridview. It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition) Thankx, | If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected. If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell. Here's an example: public class MyDataGridView : DataGridView{ protected override void SetSelectedRowCore(int rowIndex, bool selected) { if (selected && WantRowSelection(rowIndex)) { base.SetSelectedRowCore(rowIndex, selected); } } protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected) { if (selected && WantRowSelection(rowIndex)) { base.SetSelectedRowCore(rowIndex, selected); } } bool WantRowSelection(int rowIndex) { //return true if you want the row to be selectable, false otherwise }} If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4392/"
]
} |
71,429 | Background: I'm running a full-time job and a part-time job in the weekends, and both my employers have supplied a laptop for me to work on. Of course I also have my powerful workstation at home to work from, and sometimes when I'm at the office at my weekend job (it's in another city) I'm working from yet another workstation. Problem: That makes a full 4 PC's I'm maintaining (software versions, licences and settings) just to do my work, and believe me, my list of prefered software is way too big. I want to setup a Virtual Desktop on my VMware server, so I can work from the same installation and same session no matter which PC I'm working from. Now I don't have the time and money to go through a full test of each setup, so I'd like to hear your experiences on the subject. Question: Should I use a VMware virtual workstation with some remote logon software (like realVNC , teamviewer , logmein , whatever...) or should I invest in a full VDI system like Sun or VMware provide? Edit: I'm programming in Adobe Dreamweaver on Windows XP - but I run my servers on Debian and sometimes do quick edits in VIM too. First I intend to virtualize a WinXP with base installation, to see how it runs. | I am a consultant and tend to work in a variety of environments. I carry a Thinkpad running VMWare Server over Ubuntu64 with 4GB of RAM. I've got a 320GB secondary hard drive that I use just for VM's and have 25 or so different virtual machines that I boot up as the circumstances demand. They're a mix of Linux servers and workstations, Vista workstations and XP Workstations. I rarely use the VMWare server console. I access every one of them via one of the remote access methods. For Linux, I usually install FreeNX or NXServer for desktop access and just SSH for commandline. On Windows, I always use Remote Desktop (RDP), but, on XP, that only works on the "Pro" versions, not the "Home" versions. If all else fails, I install VNC and use that. VNC is at the bottom of my list because it really is a last resort. The only thing it's better than is not actually being able to use the machine. However, NX on Linux and RDP on Windows work WAY better than VNC. Other than little things like font smoothing and fancy desktop effects, the only big glitch would be if you are doing much with video or audio or DirectX-based stuff. Things like YouTube or other video do NOT like to work with any remote desktop protocol that I know of. As far as performance, using Linux as a host for VMWare provides really good management of system resources. The Windows-based VM's aren't able to just gobble up memory, but still get it when they need to. I do C# development all day in a virtual Vista workstation on Visual Studio 2008 and have absolutely no problems having 3-4 different solutions all open at once along with the normal stuff alongside over RDP on another machine, connected via wireless VPN. I can flip over to the host OS and it won't even be touching swap space at all. As far as I'm concerned, it's a great way to work. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4112/"
]
} |
71,440 | I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up? class MyControl : System.Web.UI.UserControl { // Attribute to prevent property from showing in VS Property Window? public bool SampleProperty { get; set; } // other stuff} | Use the following attribute ... using System.ComponentModel;[Browsable(false)]public bool SampleProperty { get; set; } In VB.net, this will be : <System.ComponentModel.Browsable(False)> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
]
} |
71,513 | The win32.perl.org web site provides references to several Perl distributions for MS Windows. For a long time I have been using ActivePerl from ActiveState but recently I switched to Strawberry Perl . IMHO The only advantage that Active Perl still has over Strawberry Perl is the fact that it comes with Perl Tk which means its easy to install Devel::ptkdb the graphical debugger. Other than that, I think Strawberry Perl has all the advantages. | Strawberry Perl is just getting better and better. One problem I've repeatedly had with ActiveState is that my modules sometimes fail to install because I need an upgrade to a core module, but they won't allow that. Thus, everybody who doesn't use Windows can use my code, but they can't do that with ActiveState's Perl. ActiveState also has a very dodgy build system which often fails to report exactly why a module failed to build. I got so tired of emailing and asking for this information that I eventually gave up. I want my code to run on Windows, but if ActiveState doesn't provide me with that information and doesn't give me any option for upgrading core modules, I just can't use it. Some of my modules have NO build failures on any operating system -- except those with ActiveState Perl. Support Strawberry Perl and just don't worry about ActiveState. If ActiveState has fixed their build system and their 'no upgrade to core modules' policy, it's worth revisiting. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/71513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11827/"
]
} |
71,625 | I have just found a static nested interface in our code-base. class Foo { public static interface Bar { /* snip */ } /* snip */} I have never seen this before. The original developer is out of reach. Therefore I have to ask SO: What are the semantics behind a static interface? What would change, if I remove the static ? Why would anyone do this? | The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code. Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!) It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example: public class Foo { public interface Bar { void callback(); } public static void registerCallback(Bar bar) {...}}// ...elsewhere...Foo.registerCallback(new Foo.Bar() { public void callback() {...}}); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/71625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
]
} |
71,659 | I start using the visual studio c++ express 2008 at home but there is no ATL in it. How can I add ATL to visual studio c++ express 2008? | ATL 7.1 is now part of the Windows Driver Kit . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
71,756 | If I remove all the ' characters from a SQL query, is there some other way to do a SQL injection attack on the database? How can it be done? Can anyone give me examples? | Yes, there is. An excerpt from Wikipedia "SELECT * FROM data WHERE id = " + a_variable + ";" It is clear from this statement that the author intended a_variable to be a number correlating to the "id" field. However, if it is in fact a string then the end user may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a_variable to 1;DROP TABLE users will drop (delete) the "users" table from the database, since the SQL would be rendered as follows: SELECT * FROM DATA WHERE id=1;DROP TABLE users; SQL injection is not a simple attack to fight. I would do very careful research if I were you. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
71,766 | In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class. In Java, I'd use: public class MyObject { private static final MySharedObject mySharedObjectInstance = new MySharedObject();} Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block. (You might have guessed... I know my Java but I'm rather new to Delphi...) Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.) What's the neatest way to do something like this in Delphi? | Here is how I'll do that using a class variable, a class procedure and an initialization block: unit MyObject;interfacetypeTMyObject = class private class var FLogger : TLogLogger; public class procedure SetLogger(value:TLogLogger); class procedure FreeLogger; end;implementationclass procedure TMyObject.SetLogger(value:TLogLogger);begin // sanity checks here FLogger := Value;end;class procedure TMyObject.FreeLogger;begin if assigned(FLogger) then FLogger.Free;end;initialization TMyObject.SetLogger(TLogLogger.Create);finalization TMyObject.FreeLogger;end. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961/"
]
} |
71,776 | I have 16,000 jpg's from a webcan screeb grabber that I let run for a year pointing into the back year. I want to find a way to grab every 4th image so that I can then put them into another directory so I can later turn them into a movie. Is there a simple bash script or other way under linux that I can do this. They are named like so...... frame-44558.jpg frame-44559.jpg frame-44560.jpg frame-44561.jpg Thanks from a newb needing help. Seems to have worked.Couple of errors in my origonal post. There were actually 280,000 images and the naming was./home/baldy/Desktop/webcamimages/webcam_2007-05-29_163405.jpg/home/baldy/Desktop/webcamimages/webcam_2007-05-29_163505.jpg/home/baldy/Desktop/webcamimages/webcam_2007-05-29_163605.jpg I ran.cp $(ls | awk '{nr++; if (nr % 10 == 0) print $0}') ../newdirectory/ Which appears to have copied the images. 70-900 per day from the looks of it. Now I'm running mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi I'll let you know how the movie works out. UPDATE: Movie did not work. Only has images from 2007 in it even though the directory has 2008 as well.webcam_2008-02-17_101403.jpg webcam_2008-03-27_192205.jpgwebcam_2008-02-17_102403.jpg webcam_2008-03-27_193205.jpgwebcam_2008-02-17_103403.jpg webcam_2008-03-27_194205.jpgwebcam_2008-02-17_104403.jpg webcam_2008-03-27_195205.jpg How can I modify my mencoder line so that it uses all the images? | One simple way is: $ touch a b c d e f g h i j k l m n o p q r s t u v w x y z$ mv $(ls | awk '{nr++; if (nr % 4 == 0) print $0}') destdir | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11950/"
]
} |
71,944 | I am using <input type="file" id="fileUpload" runat="server"> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions). Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded). | Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash. HTML: <input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/><input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" /> Javascript: var hash = { 'xls' : 1, 'xlsx' : 1,};function check_extension(filename,submitId) { var re = /\..+$/; var ext = filename.match(re); var submitEl = document.getElementById(submitId); if (hash[ext]) { submitEl.disabled = false; return true; } else { alert("Invalid filename, please select another file"); submitEl.disabled = true; return false; }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/71944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
]
} |
71,955 | I find I can do more with NHibernate, and even Castle than with the Linq to Entities, or linq to SQL. Am I crazy? | No you're not crazy. nHibernate is a full OR Mapper, Linq to SQL and Linq to Entities don't implement everything you'd expect from an OR mapper and targeted at a slightly different group of developers. But don't let that put you off linq though. Linq is still a pretty good idea.. Try Linq to nHibernate :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744/"
]
} |
71,985 | How can I copy a line 10 times easily in Emacs? I can't find a copy-line shortcut or function. I can use C-aC-spcC-eM-w to laboriously copy the line but how can I then paste it more than once? Any ideas before I go and write my own functions. | you can use a keyboard macro for that:- C-a C-k C-x ( C-y C-j C-x ) C-u 9 C-x e Explanation:- C-a : Go to start of line C-k : Kill line C-x ( : Start recording keyboard macro C-y : Yank killed line C-j : Move to next line C-x ) : Stop recording keyboard macro C-u 9 : Repeat 9 times C-x e : Execute keyboard macro | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/71985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9831/"
]
} |
72,010 | Given the following example, why do I have to explicitly use the statement b->A::DoSomething() rather than just b->DoSomething() ? Shouldn't the compiler's overload resolution figure out which method I'm talking about? I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.) class A{ public: int DoSomething() {return 0;};};class B : public A{ public: int DoSomething(int x) {return 1;};};int main(){ B* b = new B(); b->A::DoSomething(); //Why this? //b->DoSomething(); //Why not this? (Gives compiler error.) delete b; return 0;} | The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done afterwards . In your case this means that the compiler sees B::DoSomething . It then tries to match the argument list, which fails. One solution would be to pull down the overload from A into B 's scope: class B : public A {public: using A::DoSomething; // …} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12083/"
]
} |
72,090 | I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires. I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609 This is the full script that I'm trying to modify, changing: window.addEventListener ("load", doStuff, false); to window.addEventListener ("DOMContentLoaded", doStuff, false); | So I googled greasemonkey dom ready and the first result seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script straight away. I removed the window.addEventListener ("load", function() { and }, false); wrapping and it worked perfectly. It's much more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
]
} |
72,098 | When using MediaWiki's markup language, the only thing that I hate is creating numbered lists. The only way I know to create a list is to do something like this: #Item1#Item2 However, if I want to add spaces or some other text between those lines, the numbering gets lost. For example, the following will create text that has two number one items: #Item1Somestuff#Item2 Is there any way around this, or should I just use bullet points instead? I noticed just now that the stackoverflow system does not allow numbering like this, you have to do it all manually. | Like this: #Item1#:Somestuff#Item2 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
72,104 | I have heard using PDB files can help diagnose where a crash occurred. My basic understanding is that you give Visual studio the source file, the pdb file and the crash information (from Dr Watson?) Can someone please explain how it all works / what is involved?(Thank you!) | PDB files are generated when you build your project. They contain information relating to the built binaries which Visual Studio can interpret. When a program crashes and it generates a crash report, Visual Studio is able to take that report and link it back to the source code via the PDB file for the application. PDB files must be built from the same binary that generated the crash report! There are some issues that we have encountered over time. The machine that is debugging the crash report needs to have the source on the same path as the machine that built the binary. Release builds often optimize to the extent where you cannot view the state of object member variables If anyone knows how to defeat the former, I would be grateful for some input. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3590/"
]
} |
72,121 | Let me use the following example to explain my question: public string ExampleFunction(string Variable) { return something;}string WhatIsMyName = "Hello World";string Hello = ExampleFunction(WhatIsMyName); When I pass the variable WhatIsMyName to the ExampleFunction , I want to be able to get a string of the original variable's name. Perhaps something like: Variable.OriginalName.ToString() // == "WhatIsMyName" Is there any way to do this? | What you want isn't possible directly but you can use Expressions in C# 3.0: public void ExampleFunction(Expression<Func<string, string>> f) { Console.WriteLine((f.Body as MemberExpression).Member.Name);}ExampleFunction(x => WhatIsMyName); Note that this relies on unspecified behaviour and while it does work in Microsoft’s current C# and VB compilers, and in Mono’s C# compiler, there’s no guarantee that this won’t stop working in future versions. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
72,123 | Reading over the responses to this question Disadvantages of Test Driven Development? I got the impression there is alot of misunderstanding on what TDD is and how it should be conducted. It may prove useful to address these issues here. | I feel the accepted answer was one of the weakest ( Disadvantages of Test Driven Development? ), and the most up-modded answer smells of someone who might be writing over specified tests. Big time investment: for the simple case you lose about 20% of the actual implementation, but for complicated cases you lose much more. TDD is an investment. I've found that once I was fully into TDD, the time I lost is very very little, and what time I did lose was more than made up when it came to maintence time. For complex cases your test cases are harder to calculate, I'd suggest in cases like that to try and use automatic reference code that will run in parallel in the debug version / test run, instead of the unit test of simplest cases. If your test are becoming very complex, it might be time to review your design. TDD should lead you down the path smaller, less complex units of code working together Sometimes you the design is not clear at the start and evolves as you go along - this will force you to redo your test which will generate a big time lose. I would suggest postponing unit tests in this case until you have some grasp of the design in mind. This is the worst point of them all! TDD should really be "Test Driven Design ". TDD is about design, not testing. To fully realise the value of benefits of TDD, you have toy drive your design from your tests. So you should be redoing your production code to make your tests pass, not the other way round as this point suggests Now the currently most upmodded: Disadvantages of Test Driven Development? When you get to the point where you have a large number of tests, changing the system might require re-writing some or all of your tests, depending on which ones got invalidated by the changes. This could turn a relatively quick modification into a very time-consuming one. Like the accepted answers first point, this seems like over specification in the tests and a general lack of understanding of the TDD process. When making changes, start from your test. Change the test for what the new code should do, and make the change. If that change breaks other tests, then your tests are doing what their supposed to do, failing. Unit Tests, for me, are designed to fail, hence why the RED stage is first, and should never be missed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11979/"
]
} |
72,153 | How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got: <ItemGroup> <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" /></ItemGroup> At the moment, but this does not exclude anything! | Thanks for your help, managed to sort it as follows: <ItemGroup> <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude="$(LibrariesReleaseDir)\**\.svn\**" /></ItemGroup> Turns out the pattern matching basically runs on files, so you have to exclude everything BELOW the .svn directories ( .svn\\** ) for MSBuild to exclude the .svn directory itself. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/72153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
]
} |
72,166 | We have hundreds of websites which were developed in asp, .net and java and we are paying lot of money for an external agency to do a penetration testing for our sites to check for security loopholes. Are there any (good) software (paid or free) to do this? or.. are there any technical articles which can help me develop this tool? | There are a couple different directions you can go with automated testing tools for web applications. First, there are the commercial web scanners , of which HP WebInspect and Rational AppScan are the two most popular. These are "all-in-one", "fire-and-forget" tools that you download and install on an internal Windows desktop and then give a URL to spider your site, scan for well-known vulnerabilities (ie, the things that have hit Bugtraq), and probe for cross-site scripting and SQL injection vulnerabilities. Second, there are the source-code scanning tools , of which Coverity and Fortify are probably the two best known. These are tools you install on a developer's desktop to process your Java or C# source code and look for well-known patterns of insecure code, like poor input validation. Finally, there are the penetration test tools . By far the most popular web app penetration testing tool among security professionals is Burp Suite, which you can find at http://www.portswigger.net/proxy . Others include Spike Proxy and OWASP WebScarab. Again, you'll install this on an internal Windows desktop. It will run as an HTTP proxy, and you'll point your browser at it. You'll use your applications as a normal user would, while it records your actions. You can then go back to each individual page or HTTP action and probe it for security problems. In a complex environment, and especially if you're considering anything DIY, I strongly recommend the penetration testing tools . Here's why: Commercial web scanners provide a lot of "breadth", along with excellent reporting. However: They tend to miss things, because every application is different. They're expensive (WebInspect starts in the 10's of thousands). You're paying for stuff you don't need (like databases of known bad CGIs from the '90s). They're hard to customize. They can produce noisy results. Source code scanners are more thorough than web scanners. However: They're even more expensive than the web scanners. They require source code to operate. To be effective, they often require you to annotate your source code (for instance, to pick out input pathways). They have a tendency to produce false positives. Both commercial scanners and source code scanners have a bad habit of becoming shelfware. Worse, even if they work, their cost is comparable to getting 1 or 2 entire applications audited by a consultancy; if you trust your consultants, you're guaranteed to get better results from them than from the tools. Penetration testing tools have downsides too: They're much harder to use than fire-and-forget commercial scanners. They assume some expertise in web application vulnerabilities --- you have to know what you're looking for. They produce little or no formal reporting. On the other hand: They're much, much cheaper --- the best of the lot, Burp Suite, costs only 99EU, and has a free version. They're easy to customize and add to a testing workflow. They're much better at helping you "get to know" your applications from the inside. Here's something you'd do with a pen-test tool for a basic web application: Log into the application through the proxy Create a "hit list" of the major functional areas of the application, and exercise each once. Use the "spider" tool in your pen-test application to find all the pages and actions and handlers in the application. For each dynamic page and each HTML form the spider uncovers, use the "fuzzer" tool (Burp calls it an "intruder") to exercise every parameter with invalid inputs. Most fuzzers come with basic test strings that include: SQL metacharacters HTML/Javascript escapes and metacharacters Internationalized variants of these to evade input filters Well-known default form field names and values Well-known directory names, file names, and handler verbs Spend several hours filtering the resulting errors (a typical fuzz run for one form might generate 1000 of them) looking for suspicious responses. This is a labor-intensive, "bare-metal" approach. But when your company owns the actual applications, the bare-metal approach pays off, because you can use it to build regression test suites that will run like clockwork at each dev cycle for each app. This is a win for a bunch of reasons: Your security testing will take a predictable amount of time and resources per application, which allows you to budget and triage. Your team will get maximally accurate and thorough results, since your testing is going to be tuned to your applications. It's going to cost less than commercial scanners and less than consultants. Of course, if you go this route, you're basically turning yourself into a security consultant for your company. I don't think that's a bad thing; if you don't want that expertise, WebInspect or Fortify isn't going to help you much anyways. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/72166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
]
} |
72,167 | How do I find out which sound files the user has configured in the control panel? Example: I want to play the sound for "Device connected". Which API can be used to query the control panel sound settings? I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings. Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry. To play the "Device Conntected" sound: ::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC ); | PlaySound is the API. Also see Play System Sounds . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1810/"
]
} |
72,209 | Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palindrome.I have seen many programmers using recursion as a means to show off when a simple iteration algorithm can fit the bill.Does the compiler play a vital role in deciding what to use? | It is possible that recursion will be more expensive, depending on if the recursive function is tail recursive (the last line is recursive call). Tail recursion should be recognized by the compiler and optimized to its iterative counterpart (while maintaining the concise, clear implementation you have in your code). I would write the algorithm in the way that makes the most sense and is the clearest for the poor sucker (be it yourself or someone else) that has to maintain the code in a few months or years. If you run into performance issues, then profile your code, and then and only then look into optimizing by moving over to an iterative implementation. You may want to look into memoization and dynamic programming . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
} |
72,242 | The page Protecting Your Cookies: HttpOnly explains why making HttpOnly cookies is a good idea. How do I set this property in Ruby on Rails? | Set the 'http_only' option in the hash used to set a cookie e.g. cookies["user_name"] = { :value => "david", :httponly => true } or, in Rails 2: e.g. cookies["user_name"] = { :value => "david", :http_only => true } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
} |
72,264 | I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE. What are the steps to create such an executable? | Single Assembly Deployment of Managed and Unmanaged CodeSunday, February 4, 2007 .NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs. So here´s what I came up with for a solution: I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources.Then I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think. namespace MyLib{ public class MyClass { static MyClass() { ResourceExtractor.ExtractResourceToFile("MyLib.ManagedService.dll", "managedservice.dll"); ResourceExtractor.ExtractResourceToFile("MyLib.UnmanagedService.dll", "unmanagedservice.dll"); } ... In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code. The code to extract the DLLs into files of their own is simple: public static class ResourceExtractor{ public static void ExtractResourceToFile(string resourceName, string filename) { if (!System.IO.File.Exists(filename)) using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create)) { byte[] b = new byte[s.Length]; s.Read(b, 0, b.Length); fs.Write(b, 0, b.Length); } }} Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource. For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g. [DllImport("unmanagedservice.dll")] public extern static int Add(int a, int b); That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient. Enjoy! http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
]
} |
72,271 | What is the reason for the following warning in some C++ compilers? No newline at end of file Why should I have an empty line at the end of a source/header file? | Think of some of the problems that can occur if there is no newline. According to the ANSI standard the #include of a file at the beginning inserts the file exactly as it is to the front of the file and does not insert the new line after the #include <foo.h> after the contents of the file. So if you include a file with no newline at the end to the parser it will be viewed as if the last line of foo.h is on the same line as the first line of foo.cpp . What if the last line of foo.h was a comment without a new line? Now the first line of foo.cpp is commented out. These are just a couple of examples of the types of problems that can creep up. Just wanted to point any interested parties to James' answer below. While the above answer is still correct for C, the new C++ standard (C++11) has been changed so that this warning should no longer be issued if using C++ and a compiler conforming to C++11. From C++11 standard via James' post: A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file (C++11 §2.2/1). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
72,275 | Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking? | I don't think there's a better person to answer this than Eric Lippert (emphasis in the original): In C#, "volatile" means not only "make sure that the compiler and the jitter do not perform any code reordering or register caching optimizations on this variable". It also means "tell the processors to do whatever it is they need to do to ensure that I am reading the latest value, even if that means halting other processors and making them synchronize main memory with their caches". Actually, that last bit is a lie. The true semantics of volatile reads and writes are considerably more complex than I've outlined here; in fact they do not actually guarantee that every processor stops what it is doing and updates caches to/from main memory. Rather, they provide weaker guarantees about how memory accesses before and after reads and writes may be observed to be ordered with respect to each other . Certain operations such as creating a new thread, entering a lock, or using one of the Interlocked family of methods introduce stronger guarantees about observation of ordering. If you want more details, read sections 3.10 and 10.5.3 of the C# 4.0 specification. Frankly, I discourage you from ever making a volatile field . Volatile fields are a sign that you are doing something downright crazy: you're attempting to read and write the same value on two different threads without putting a lock in place. Locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given chunk of memory at a time, and so on. The number of situations in which a lock is too slow is very small, and the probability that you are going to get the code wrong because you don't understand the exact memory model is very large. I don't attempt to write any low-lock code except for the most trivial usages of Interlocked operations. I leave the usage of "volatile" to real experts. For further reading see: Understand the Impact of Low-Lock Techniques in Multithreaded Apps Sayonara volatile | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3389/"
]
} |
72,281 | Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated. Msg 10314, Level 16, State 11, Line 1An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error: System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)System.IO.FileLoadException: at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.Load(String assemblyString) | Ran the SQL commands below and the issue appears to be resolved. USE database_nameGOEXEC sp_changedbowner 'sa'ALTER DATABASE database_name SET TRUSTWORTHY ON | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3400/"
]
} |
72,298 | Visual Studio solutions contain two types of hidden user files. One is the solution .suo file which is a binary file. The other is the project .user file which is a text file. Exactly what data do these files contain? I've also been wondering whether I should add these files to source control (Subversion in my case). If I don't add these files and another developer checks out the solution, will Visual Studio automatically create new user files? | These files contain user preference configurations that are in general specific to your machine, so it's better not to put it in SCM. Also, VS will change it almost every time you execute it, so it will always be marked by the SCM as 'changed'.I don't include either, I'm in a project using VS for 2 years and had no problems doing that. The only minor annoyance is that the debug parameters (execution path, deployment target, etc.) are stored in one of those files (don't know which), so if you have a standard for them you won't be able to 'publish' it via SCM for other developers to have the entire development environment 'ready to use'. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/72298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203/"
]
} |
72,312 | PERL? Perl? perl? What's good style? I know the answer—I just wanted to make sure the question was out there and questioners were aware that there is a correct form. | The correct casing is "Perl" for the language and "perl" for the executable. Using "PERL" flags you as someone who isn't particularly familiar with the language or community. See also What's the difference between "perl" and "Perl"? in perlfaq1 . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423836/"
]
} |
72,381 | I'm trying to use the following code but it's returning the wrong day of month. Calendar cal = Calendar.getInstance();cal.setTime(sampleDay.getTime());cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);cal.set(Calendar.DAY_OF_MONTH, 0);return cal.getTime(); | Get the number of days for this month: Calendar cal = Calendar.getInstance();cal.setTime(sampleDay.getTime());int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); Set the Calendar to the last day of this month: Calendar cal = Calendar.getInstance();cal.setTime(sampleDay.getTime());cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
} |
72,393 | A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")# result is None` After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change: regex = ".*(a_regex_of_pure_awesomeness)" into regex = "a_regex_of_pure_awesomeness" Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny. | In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string. Python regex docs Matching vs searching | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
72,537 | In a SharePoint list I want an auto number column that as I add to the list gets incremented. How best can I go about this? | Sharepoint Lists automatically have an column with "ID" which auto increments. You simply need to select this column from the "modify view" screen to view it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/72537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12318/"
]
} |
72,541 | I have an ASP.NET web page that displays a variety of fields that need to be updated best on certain conditions, button clicks and so on. We've implemented AJAX, using the ASP.NET Update Panel to avoid visible postbacks. Originally there was only one area that needed this ability ... that soon expanded to other fields. Now my web page has multiple UpdatePanels. I am wondering if it would be best to just wrap the entire form in a single UpdatePanel, or keep the individual UpdatePanels. What are the best practices for using the ASP.NET UpdatePanel? | Multiple panels are much better. One of the main reasons for using UpdatePanels at all is to reduce the traffic and to only send the pieces that you need back and forth across the wire. By only using one update panel, you're pretty much doing a full post back every time, you're just using a little Javascript to update the page without a flicker. If there are pieces of the page that need to be updated together, there are ways to trigger other panels to update when one does.. but you should definitely be using multiple update panels. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/72541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
]
} |
72,552 | What does the volatile keyword do? In C++ what problem does it solve? In my case, I have never knowingly needed it. | volatile is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this: void waitForSemaphore(){ volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/ while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);} Without volatile , the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
]
} |
72,556 | I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid. Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing. | volatile is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this: void waitForSemaphore(){ volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/ while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);} Without volatile , the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12333/"
]
} |
72,562 | Is there a good way to find out which exceptions a procedure/function can raise in Delphi (including it's called procedures/functions)? In Java you always have to declare which exceptions that can be thrown, but this is not the case in Delphi, which could lead to unhandled exceptions. Are there any code analysis tools that detects unhandled exceptions? | (Edit: It is now obvious that the question referred only to design-time checking.) New answer: I cannot state whether there are any tools to check this for you. Pascal Analyzer, for one, does not. I can tell you, however, that in most Delphi applications, even if there was a tool to check this for you, you would get no results. Why? Because the main message loop in TApplication.Run() wraps all HandleMessage() calls in an exception handling block, which catches all exception types. Thus you will have implicit/default exception handling around 99.999% of code in most applications. And in most applications, this exception handling will be around 100% of your own code - the 0.001% of code which is not wrapped in exception handling will be the automatically generated code. If there was a tool available to check this for you, you would need to rewrite Application.run() such that it does not include exception handling. (Previous answer: The Application.OnException event handler can be assigned to catch all exceptions that aren't handled by other exception handlers. Whilst this is run-time, and thus perhaps not exactly what you are after (it sounds like you want to identify them at design time), it does allow you to trap any exception not handled elsewhere. In conjunction with tools such as the JCLDebug stuff in the Jedi Code Library , you could log a stack trace to find out where & why an exception occurred, which would allow for further investigation and adding specific exception handling or prevention around the guilty code... ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11300/"
]
} |
72,564 | I'm kind of interested in getting some feedback about this technique I picked up from somewhere. I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this. Basically the technique involves returning true for success, and something which equates to false for failure. Here's an example to show what I mean: define ('DUPLICATE_USERNAME', false);define ('DATABASE_ERROR', 0);define ('INSUFFICIENT_DETAILS', 0.0);define ('OK', true);function createUser($username) { // create the user and return the appropriate constant from the above} The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code: if (createUser('fred')) { // yay, it worked!} else { // aww, it didn't work.} If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with === $status = createUser('fred');if ($status) { // yay, it worked!} else if ($status === DUPLICATE_USERNAME) { // tell the user about it and get them to try again.} else { // aww, it didn't work. log it and show a generic error message? whatever.} The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false. The downside is that you can only have 7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null. If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an enum where they all equate to false is "ick" . So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing? | I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last error variable, consider redefining your function as: function createUser($username, &$error) Then you can use: if (createUser('fred', $error)) { echo 'success';}else { echo $error;} Inside createUser, just populate $error with any error you encounter and it'll be accessible outside of the function scope due to the reference. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
} |
72,616 | I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, not a source code file -- but embed that file in the executable file like a resource. (This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.) Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.) | You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, here for more information. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/72616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
]
} |
72,671 | I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command. However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this? E.g. batch file start "c:\path with spaces\app.exe" param1 "param with spaces" | Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this: start "" "c:\path with spaces\app.exe" param1 "param with spaces" You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/72671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
72,672 | Has anyone written an 'UnFormat' routine for Delphi? What I'm imagining is the inverse of SysUtils.Format and looks something like this UnFormat('a number %n and another %n',[float1, float2]); So you could unpack a string into a series of variables using format strings. I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me. | This is called scanf in C, I've made a Delphi look-a-like for this : function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;var InputOffset: Integer; FormatOffset: Integer; InputChar: Char; FormatChar: Char; function _GetInputChar: Char; begin if InputOffset <= Length(Input) then begin Result := Input[InputOffset]; Inc(InputOffset); end else Result := #0; end; function _PeekFormatChar: Char; begin if FormatOffset <= Length(Format) then Result := Format[FormatOffset] else Result := #0; end; function _GetFormatChar: Char; begin Result := _PeekFormatChar; if Result <> #0 then Inc(FormatOffset); end; function _ScanInputString(const Arg: Pointer = nil): string; var EndChar: Char; begin Result := ''; EndChar := _PeekFormatChar; InputChar := _GetInputChar; while (InputChar > ' ') and (InputChar <> EndChar) do begin Result := Result + InputChar; InputChar := _GetInputChar; end; if InputChar <> #0 then Dec(InputOffset); if Assigned(Arg) then PString(Arg)^ := Result; end; function _ScanInputInteger(const Arg: Pointer): Boolean; var Value: string; begin Value := _ScanInputString; Result := TryStrToInt(Value, {out} PInteger(Arg)^); end; procedure _Raise; begin raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]); end;begin Result := 0; InputOffset := 1; FormatOffset := 1; FormatChar := _GetFormatChar; while FormatChar <> #0 do begin if FormatChar <> '%' then begin InputChar := _GetInputChar; if (InputChar = #0) or (FormatChar <> InputChar) then Exit; end else begin FormatChar := _GetFormatChar; case FormatChar of '%': if _GetInputChar <> '%' then Exit; 's': begin _ScanInputString(Args[Result]); Inc(Result); end; 'd', 'u': begin if not _ScanInputInteger(Args[Result]) then Exit; Inc(Result); end; else _Raise; end; end; FormatChar := _GetFormatChar; end;end; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12376/"
]
} |
72,677 | Imagine I have String in C#: "I Don’t see ya.." I want to remove (replace to nothing or etc.) these "’" symbols. How do I do this? | That 'junk' looks a lot like someone interpreted UTF-8 data as ISO 8859-1 or Windows-1252, probably repeatedly. ’ is the sequence C3 A2, E2 82 AC, E2 84 A2. UTF-8 C3 A2 = U+00E2 = â UTF-8 E2 82 AC = U+20AC = € UTF-8 E2 84 A2 = U+2122 = ™ We then do it again: in Windows 1252 this sequence is E2 80 99, so the character should have been U+2019, RIGHT SINGLE QUOTATION MARK (’) You could make multiple passes with byte arrays, Encoding.UTF8 and Encoding.GetEncoding(1252) to correctly turn the junk back into what was originally entered. You will need to check your processing to find the two places that UTF-8 data was incorrectly interpreted as Windows-1252. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369/"
]
} |
72,682 | Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes. Now you have a method, and you want to return a value. You also want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this: class FunctionResult<T>{ public T payload; public int result;} And then declare your functions like this: FunctionResult<string> MyFunction(){ FunctionResult<string> result; //... return result;} One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it? | I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters). There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary. This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
72,696 | I have some code like this: If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then DoSomething()End If I don't care about the case. Should I use OrdinalIgnoreCase , InvariantCultureIgnoreCase , or CurrentCultureIgnoreCase ? | Newer .Net Docs now has a table to help you decide which is best to use in your situation. From MSDN's " New Recommendations for Using Strings in Microsoft .NET 2.0 " Summary: Code owners previously using the InvariantCulture for string comparison, casing, and sorting should strongly consider using a new set of String overloads in Microsoft .NET 2.0. Specifically, data that is designed to be culture-agnostic and linguistically irrelevant should begin specifying overloads using either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase members of the new StringComparison enumeration. These enforce a byte-by-byte comparison similar to strcmp that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7072/"
]
} |
72,768 | I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this? | The credit/debit card number is referred to as a PAN , or Primary Account Number . The first six digits of the PAN are taken from the IIN , or Issuer Identification Number , belonging to the issuing bank (IINs were previously known as BIN — Bank Identification Numbers — so you may see references to that terminology in some documents). These six digits are subject to an international standard, ISO/IEC 7812 , and can be used to determine the type of card from the number. Unfortunately the actual ISO/IEC 7812 database is not publicly available, however, there are unofficial lists, both commercial and free, including on Wikipedia . Anyway, to detect the type from the number, you can use a regular expression like the ones below: Credit for original expressions Visa: ^4[0-9]{6,}$ Visa card numbers start with a 4. MasterCard: ^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$ Before 2016, MasterCard numbers start with the numbers 51 through 55, but this will only detect MasterCard credit cards ; there are other cards issued using the MasterCard system that do not fall into this IIN range. In 2016, they will add numbers in the range (222100-272099). American Express: ^3[47][0-9]{5,}$ American Express card numbers start with 34 or 37. Diners Club: ^3(?:0[0-5]|[68][0-9])[0-9]{4,}$ Diners Club card numbers begin with 300 through 305, 36 or 38. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard and should be processed like a MasterCard. Discover: ^6(?:011|5[0-9]{2})[0-9]{3,}$ Discover card numbers begin with 6011 or 65. JCB: ^(?:2131|1800|35[0-9]{3})[0-9]{3,}$ JCB cards begin with 2131, 1800 or 35. Unfortunately, there are a number of card types processed with the MasterCard system that do not live in MasterCard’s IIN range (numbers starting 51...55); the most important case is that of Maestro cards, many of which have been issued from other banks’ IIN ranges and so are located all over the number space. As a result, it may be best to assume that any card that is not of some other type you accept must be a MasterCard . Important : card numbers do vary in length; for instance, Visa has in the past issued cards with 13 digit PANs and cards with 16 digit PANs. Visa’s documentation currently indicates that it may issue or may have issued numbers with between 12 and 19 digits. Therefore, you should not check the length of the card number, other than to verify that it has at least 7 digits (for a complete IIN plus one check digit, which should match the value predicted by the Luhn algorithm ). One further hint: before processing a cardholder PAN, strip any whitespace and punctuation characters from the input . Why? Because it’s typically much easier to enter the digits in groups, similar to how they’re displayed on the front of an actual credit card, i.e. 4444 4444 4444 4444 is much easier to enter correctly than 4444444444444444 There’s really no benefit in chastising the user because they’ve entered characters you don't expect here. This also implies making sure that your entry fields have room for at least 24 characters, otherwise users who enter spaces will run out of room. I’d recommend that you make the field wide enough to display 32 characters and allow up to 64; that gives plenty of headroom for expansion. Here's an image that gives a little more insight: UPDATE (2016): Mastercard is to implement new BIN ranges starting Ach Payment . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/72768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12382/"
]
} |
72,799 | If you had a differential of either venturing into Delphi land or Qt land which would you choose? I know they are not totally comparable. I for one have Windows development experience with Builder C++ (almost Delphi) and MFC (almost Qt), with a bit more time working with Builder C++. Please take out the cross platform ability of Qt in your analysis. I'm hoping for replies of people who have worked with both and how he or she would compare the framework, environment, etc.? Thank you in advance for your replies. | If you are talking UI frameworks, then you should be comparing Qt with the VCL, not the IDE (Delphi in this case). I know I'm being a stickler, but Delphi is the IDE, Object-Pascal is the language, and VCL is the graphical framework. That being said, I don't think there is anything that even comes close to matching the power and simplicity of the VCL. Qt is great, but it is no VCL. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11994/"
]
} |
72,831 | Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own? | TextInfo.ToTitleCase() capitalizes the first character in each token of a string. If there is no need to maintain Acronym Uppercasing, then you should include ToLower() . string s = "JOHN DOE";s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());// Produces "John Doe" If CurrentCulture is unavailable, use: string s = "JOHN DOE";s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower()); See the MSDN Link for a detailed description. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/72831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9938/"
]
} |
72,852 | Imagine this directory structure: app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py I'm coding mod1 , and I need to import something from mod2 . How should I do it? I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package". I googled around but found only " sys.path manipulation" hacks. Isn't there a clean way? Edit: all my __init__.py 's are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages ( sub1 , subX , etc.). Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B) | Everyone seems to want to tell you what you should be doing rather than just answering the question. The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter. From PEP 328 : Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change. Update : According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/72852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
]
} |
72,899 | How do I sort a list of dictionaries by a specific key's value? Given: [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}] When sorted by name , it should become: [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}] | The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) Alternatively, you can use operator.itemgetter instead of defining the function yourself from operator import itemgetternewlist = sorted(list_to_be_sorted, key=itemgetter('name')) For completeness, add reverse=True to sort in descending order newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True) | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/72899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12398/"
]
} |
72,945 | Using Django's built in models, how would one create a triple-join between three models. For example: Users, Roles, and Events are the models. Users have many Roles, and Roles many Users. (ManyToMany) Events have many Users, and Users many Events. (ManyToMany) But for any given Event, any User may have only one Role. How can this be represented in the model? | zacherates writes: I'd model Role as an association class between Users and Roles (...) I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: ManyToMany relation with extra fields . Example: class User(models.Model): name = models.CharField(max_length=128)class Event(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(User, through='Role') def __unicode__(self): return self.nameclass Role(models.Model): person = models.ForeignKey(User) group = models.ForeignKey(Event) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/72945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8507/"
]
} |
73,022 | What is the difference between CodeFile ="file.ascx.cs" and CodeBehind ="file.ascx.cs" in the declaration of a ASP.NET user control? Is one newer or recommended? Or do they have specific usage? | CodeBehind : Needs to be compiled (ASP.NET 1.1 model). The compiled binary is placed in the bin folder of the website. You need to do a compile in Visual Studio before you deploy. It's a good model when you don't want the source code to be viewable as plain text. For example when delivering to a customer to whom you don't have an obligation to provide code. CodeFile : You provide the source file with the solution for deployment. ASP.NET 2.0 runtime compiles the code when needed. The compiled files are at Microsoft.NET[.NET version]\Temporary ASP.NET Files. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/73022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
]
} |
73,032 | I'd really like to handle this without monkey-patching but I haven't been able to find another option yet. I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example: ordered_list = [[1, 2], [1, 1], [2, 1]] Any suggestions? Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like: ordered_list = [[1, "b"], [1, "a"], [2, "a"]] | How about: ordered_list = [[1, "b"], [1, "a"], [2, "a"]]ordered_list.sort! do |a,b| [a[0],b[1]] <=> [b[0], a[1]]end | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/73032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3230/"
]
} |
73,063 | In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window. Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them? | This answer does not work for Visual Studio 2015 or later. A more recent answer can be found here . You can do this fairly easily with a Visual Studio macro. Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module... Paste the following in the source editor: Imports SystemImports System.IOImports System.Text.RegularExpressionsImports EnvDTEImports EnvDTE80Imports EnvDTE90Imports System.DiagnosticsPublic Module CustomMacros Sub BreakpointFindResults() Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1) Dim selection As TextSelection selection = findResultsWindow.Selection selection.SelectAll() Dim findResultsReader As New StringReader(selection.Text) Dim findResult As String = findResultsReader.ReadLine() Dim findResultRegex As New Regex("(?<Path>.*?)\((?<LineNumber>\d+)\):") While Not findResult Is Nothing Dim findResultMatch As Match = findResultRegex.Match(findResult) If findResultMatch.Success Then Dim path As String = findResultMatch.Groups.Item("Path").Value Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item("LineNumber").Value) Try DTE.Debugger.Breakpoints.Add("", path, lineNumber) Catch ex As Exception ' breakpoints can't be added everywhere End Try End If findResult = findResultsReader.ReadLine() End While End SubEnd Module This example uses the results in the "Find Results 1" window; you might want to create an individual shortcut for each result window. You can create a keyboard shortcut by going to Tools|Options... and selecting Keyboard under the Environment section in the navigation on the left. Select your macro and assign any shortcut you like. You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the Macros section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/73063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
]
} |
73,087 | Is there a standard X / Gnome program that will display the X,Y width and depth in pixels of a window that I select? Something similar to the way an xterm shows you the width and depth of the window (in lines) as you resize it. I'm running on Red Hat Enterprise Linux 4.4. Thanks! | Yes, you're looking for the program 'xwininfo'. Run it in another terminal and then click on the window you want info about and it will give it to you. Hope this helps! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/73087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648/"
]
} |
73,110 | For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit. This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?) Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction. @nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils. @André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness. | Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you. using System;using System.Drawing;using System.Windows.Forms;public class MyTextBox : TextBox { private bool mScrollbars; public MyTextBox() { this.Multiline = true; this.ReadOnly = true; } private void checkForScrollbars() { bool scroll = false; int cnt = this.Lines.Length; if (cnt > 1) { int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y; if (pos0 >= 32768) pos0 -= 65536; int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y; if (pos1 >= 32768) pos1 -= 65536; int h = pos1 - pos0; scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding } if (scroll != mScrollbars) { mScrollbars = scroll; this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None; } } protected override void OnTextChanged(EventArgs e) { checkForScrollbars(); base.OnTextChanged(e); } protected override void OnClientSizeChanged(EventArgs e) { checkForScrollbars(); base.OnClientSizeChanged(e); }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/73110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
]
} |
73,134 | I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus: STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize]; Later on however the memory is freed using a delete call: delete pStruct; Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use malloc and free instead? | Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example. More importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor. Of course, if you know where pStruct came from why not just cast it on delete to match the allocation: delete [] (BYTE*) pStruct; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/73134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.