source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
136,035
It is discouraged to simply catch System.Exception . Instead, only the "known" exceptions should be caught. Now, this sometimes leads to unnecessary repetitive code, for example: try{ WebId = new Guid(queryString["web"]);}catch (FormatException){ WebId = Guid.Empty;}catch (OverflowException){ WebId = Guid.Empty;} I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once? The given example is rather simple, as it's only a GUID . But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object . However, if there is an unexpected exception, I still want to throw that higher.
Catch System.Exception and switch on the types catch (Exception ex) { if (ex is FormatException || ex is OverflowException) { WebId = Guid.Empty; return; } throw;}
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/136035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
136,052
I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook. I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting? Thanks
I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior: Every message starts with continuation off. Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed. Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off. Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?) Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters. Lines that start or end with a tab turn continuation off. Lines that start with 2 or more spaces turn continuation off. Lines that end with 3 or more spaces turn continuation off. Please note that I tried all of this with Outlook 2007. YMMV. So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/136052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3098/" ] }
136,067
I am working on a web app that uses Perl and I need to look into speeding up portions of the app. I thought I'd start profiling the particular calls for the portion I wish to investigate. I've done some searching on profiling Perl code, but unfortunately most of what I find says that I should run my perl code with -d:DProf myapp from the command line. That doesn't quite work for me since my code is within a web app. I did find a way to get the profiling to work with apache, but unfortunately, the "most used" modules that came back from the profiler were all CPAN modules -- Class::xyz, etc etc etc. Not terribly helpful. Does anyone know of a good way besides me injecting "timer" code into the methods I wish to profile to target just these methods? I've thought of writing a test script and profiling that but due to the nature of the code I'm working on that would require a bit more work than I'm hoping to have to do.
Have you tried Devel::NYTProf (much better than Devel::DProf), which can work under Apache? Which webserver are you using? Is this a vanilla CGI script, a mod_perl thing, or something else? If you're doing database stuff, the DBI::Profile can benchmark your queries, which is work happening in another program. The real trick, however, is to organize the code so that you can do the full spectrum of testing and profiling without having to put it all together at the end to find out something is slow. That won't help you much in the short term to fight fires, but it does prevent things from becoming fires in the long run. There are also various ways to fake the webserver environment and so on, but that's a different question. :)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22390/" ] }
136,069
I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?
The command-line Python, IMO, definitely comes first. Get that to work, since that's the core of what you're doing. The issue is that using a web framework's ORM from a command line application isn't obvious. Django provides specific instructions for using their ORM from a command-line app. Those are annoying at first, but I think they're a life-saver in the long run. I use it heavily for giant uploads of customer-supplied files. Don't use bare CGI. It's not impossible, but too many things can go wrong, and they've all been solved by the frameworks. Why reinvent something? Just use someone else's code. Frameworks involve learning, but no real "overhead". They're not slow. They're code you don't have to write or debug. Learn some Python. Do the Django tutorial. Start to build a web app. a. Start a Django project. Build a small application in that project. b. Build your new model using the Django ORM. Create a Django unit test for the model. Be sure that it works. You'll be able to use the default admin pages and do a lot of playing around. Just don't build the entire web site yet. Get your command-line app to work using Django ORM. Essentially, you have to finesse the settings file for this app to work nicely. See the settings/configuration section. Once you've got your command line and the default admin running, you can finishthe web app. Here's the golden rule of frameworks: It's code you don't have to write, debug or maintain. Use them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203/" ] }
136,097
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod ?
Maybe a bit of example code will help: Notice the difference in the call signatures of foo , class_foo and static_foo : class A(object): def foo(self, x): print(f"executing foo({self}, {x})") @classmethod def class_foo(cls, x): print(f"executing class_foo({cls}, {x})") @staticmethod def static_foo(x): print(f"executing static_foo({x})")a = A() Below is the usual way an object instance calls a method. The object instance, a , is implicitly passed as the first argument. a.foo(1)# executing foo(<__main__.A object at 0xb7dbef0c>, 1) With classmethods , the class of the object instance is implicitly passed as the first argument instead of self . a.class_foo(1)# executing class_foo(<class '__main__.A'>, 1) You can also call class_foo using the class. In fact, if you define something to bea classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine: A.class_foo(1)# executing class_foo(<class '__main__.A'>, 1) One use people have found for class methods is to create inheritable alternative constructors . With staticmethods , neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class: a.static_foo(1)# executing static_foo(1)A.static_foo('hi')# executing static_foo(hi) Staticmethods are used to group functions which have some logical connection with a class to the class. foo is just a function, but when you call a.foo you don't just get the function,you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument. a is bound to foo . That is what is meant by the term "bound" below: print(a.foo)# <bound method A.foo of <__main__.A object at 0xb7d52f0c>> With a.class_foo , a is not bound to class_foo , rather the class A is bound to class_foo . print(a.class_foo)# <bound method type.class_foo of <class '__main__.A'>> Here, with a staticmethod, even though it is a method, a.static_foo just returnsa good 'ole function with no arguments bound. static_foo expects 1 argument, and a.static_foo expects 1 argument too. print(a.static_foo)# <function static_foo at 0xb7d479cc> And of course the same thing happens when you call static_foo with the class A instead. print(A.static_foo)# <function static_foo at 0xb7d479cc>
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/136097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ] }
136,168
I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom. So I need a tail() method that can read n lines from the bottom and support an offset. This is hat I came up with: def tail(f, n, offset=0): """Reads a n lines from f with an offset of offset lines.""" avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 Is this a reasonable approach? What is the recommended way to tail log files with offsets?
Assumes a unix-like system on Python 2 you can do: import osdef tail(f, n, offset=0): stdin,stdout = os.popen2("tail -n "+n+offset+" "+f) stdin.close() lines = stdout.readlines(); stdout.close() return lines[:,-offset] For python 3 you may do: import subprocessdef tail(f, n, offset=0): proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE) lines = proc.stdout.readlines() return lines[:, -offset]
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19990/" ] }
136,178
I'm running git-diff on a file, but the change is at the end of a long line. If I use cursor keys to move right, it loses colour-coding—and worse the lines don't line up—making it harder to track the change. Is there a way to prevent that problem or to simply make the lines wrap instead? I'm running Git 1.5.5 via mingw32.
The display of the output of git diff is handled by whatever pager you are using. Commonly, under Linux, less would be used. You can tell git to use a different pager by setting the GIT_PAGER environment variable. If you don't mind about paging (for example, your terminal allows you to scroll back) you might try explicitly setting GIT_PAGER to empty to stop it using a pager. Under Linux: $ GIT_PAGER='' git diff Without a pager, the lines will wrap. If your terminal doesn't support coloured output, you can also turn this off using either the --no-color argument, or putting an entry in the color section of your git config file. $ GIT_PAGER='' git diff --no-color
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/136178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ] }
136,204
Not really getting the point of the map function. Can anyone explain with examples its use? Are there any performance benefits to using this instead of a loop or is it just sugar?
Any time you want to generate a list based another list: # Double all elements of a listmy @double = map { $_ * 2 } (1,2,3,4,5);# @double = (2,4,6,8,10); Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute: # @user_objects is a list of objects having a unique_id() methodmy %users = map { $_->unique_id() => $_ } @user_objects;# %users = ( $id => $obj, $id => $obj, ...); It's a really general purpose tool, you have to just start using it to find good uses in your applications. Some might prefer verbose looping code for readability purposes, but personally, I find map more readable.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
136,278
For example, I rarely need: using System.Text; but it's always there by default. I assume the application will use more memory if your code contains unnecessary using directives . But is there anything else I should be aware of? Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files? Edit: Note that this question is not about the unrelated concept called a using statement , designed to help one manage resources by ensuring that when an object goes out of scope, its IDisposable.Dispose method is called. See Uses of "using" in C# .
It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded. Mainly, it's just to clean up for personal preference.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/136278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ] }
136,308
We recently started using maven for dependency management. Our team uses eclipse as it's IDE. Is there an easy way to get eclipse to refresh the maven dependencies without running mvn eclipse:eclipse? The dependencies are up to date in the local maven repository, but eclipse doesn't pick up the changes until we use the eclipse:eclipse command. This regenerates a lot of eclipse configuration files.
Have you tried using the m2eclipse plugin? I use it with eclipse and it maintains the eclipse .classpath when I add dependencies. It'll also check for updated dependencies.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ] }
136,337
Where did the idea of design patterns come from, who decided what is and isn't a pattern and gave them their names? Is there an official organisation that defines them, or do they exist through some community consensus?
I think there's a basic "life cycle of a design pattern" Author writes about design pattern in a book. Book becomes well read, possibly best seller Design pattern enters public conscious, gains mindshare. Design pattern gets used. It works well. design pattern gets more mindshare Design pattern becomes panacea, gets over-used. Different Author writes "Design Pattern Considered Harmful" Design pattern becomes Anti Pattern Different Author becomes famous, writes book full of new design patterns...
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7122/" ] }
136,362
Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness. Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try: mvn compile inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path. If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land. I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.
Maybe you are referencing the other project via Eclipse configure-> build path only. This works as long as you use Eclipse to build your project. Try running first mvn install in project Bar (in order to put Bar in your Maven repository), and then add the dependency to Foo's pom.xml. That should work!.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8178/" ] }
136,419
I need to determine the current year in Java as an integer. I could just use java.util.Date() , but it is deprecated.
For Java 8 onwards: int year = Year.now().getValue(); For older version of Java: int year = Calendar.getInstance().get(Calendar.YEAR);
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/136419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ] }
136,435
How to allow TextBlock 's text to be selectable? I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?
Use a TextBox with these settings instead to make it read only and to look like a TextBlock control. <TextBox Background="Transparent" BorderThickness="0" Text="{Binding Text, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" />
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/136435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1133/" ] }
136,436
I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'. I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up? Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for. Thanks.
Use a TextBox with these settings instead to make it read only and to look like a TextBlock control. <TextBox Background="Transparent" BorderThickness="0" Text="{Binding Text, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" />
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/136436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424554/" ] }
136,443
We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block: public PageSizer(string href, int index){ HRef = href; PageIndex = index;} Copy and pasted from IE7, ends up like this: public PageSizer(string href, int index){ HRef = href; PageIndex = index; } Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this: <pre><code>public PageSizer(string href, int index){ HRef = href; PageIndex = index;}</code></pre> So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way? Update: this specifically has to do with <pre> <code> blocks that are being modified at runtime via JavaScript. The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.
It seems that this is a known bug for IE6 and prettify.js has a workaround for it. Specifically it replaces the BR tags with '\r\n'. By modifying the check to allow for IE6 or 7 then the cut-and-paste will work correctly from IE7, but it will render with a newline followed by a space . By checking for IE7 and providing just a '\r' instead of a '\r\n' it will continue to cut-and-paste and render correctly. Add this code to prettify.js: function _pr_isIE7() { var isIE7 = navigator && navigator.userAgent && /\bMSIE 7\./.test(navigator.userAgent); _pr_isIE7 = function () { return isIE7; }; return isIE7;} and then modify the prettyPrint function as follows: function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6();+ var isIE7 = _pr_isIE7(); ... - if (isIE6 && cs.tagName === 'PRE') {+ if ((isIE6 || isIE7) && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br');+ var newline;+ if (isIE6) {+ newline = '\r\n';+ } else {+ newline = '\r';+ } for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild(- document.createTextNode('\r\n'), lineBreak);+ document.createTextNode(newline), lineBreak); } You can see a working example here . Note: I haven't tested the original workaround in IE6, so I'm guessing it renders without the space caused by the '\n' that is seen in IE7, otherwise the fix is simpler.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/136443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ] }
136,458
How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used? It would also be nice if the back button would reload the original URL. I am trying to record JavaScript state in the URL.
If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload. The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event , or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content. If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well. One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/136458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ] }
136,474
I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution: Vector itemsVector = getItems();Collections.shuffle(itemsVector);itemsVector.setSize(5); While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is Vector itemsVector = getItems();Random rand = new Random(System.currentTimeMillis()); // would make this static to the class List subsetList = new ArrayList(5);for (int i = 0; i < 5; i++) { // be sure to use Vector.remove() or you may get the same item twice subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));} Any suggestions on better ways to draw out a random subset from a Collection?
Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a useful saving when N << M. Knuth also discusses these algorithms - I believe that would be Vol 3 "Sorting and Searching", but my set is packed pending a move of house so I can't formally check that.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459/" ] }
136,500
I have a string in a node and I'd like to split the string on '?' and return the last item in the array. For example, in the block below: <a> <xsl:attribute name="href"> /newpage.aspx?<xsl:value-of select="someNode"/> </xsl:attribute> Link text</a> I'd like to split the someNode value. Edit: Here's the VB.Net that I use to load the Xsl for my Asp.Net page: Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl")Dim myXsltSettings As New XsltSettings()Dim myXMLResolver As New XmlUrlResolver()myXsltSettings.EnableScript = TruemyXsltSettings.EnableDocumentFunction = TruemyXslDoc = New XslCompiledTransform(False)myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver)Dim myStringBuilder As New StringBuilder()Dim myXmlWriter As XmlWriter = NothingDim myXmlWriterSettings As New XmlWriterSettings()myXmlWriterSettings.ConformanceLevel = ConformanceLevel.AutomyXmlWriterSettings.Indent = TruemyXmlWriterSettings.OmitXmlDeclaration = TruemyXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings)myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter)Return myStringBuilder.ToString() Update: here's an example of splitting XML on a particular node
Use a recursive method: <xsl:template name="output-tokens"> <xsl:param name="list" /> <xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" /> <xsl:variable name="first" select="substring-before($newlist, ' ')" /> <xsl:variable name="remaining" select="substring-after($newlist, ' ')" /> <id> <xsl:value-of select="$first" /> </id> <xsl:if test="$remaining"> <xsl:call-template name="output-tokens"> <xsl:with-param name="list" select="$remaining" /> </xsl:call-template> </xsl:if></xsl:template>
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ] }
136,505
I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits. Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs?
The regex for uuid is: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} If you want to enforce the full string to match this regex, you will sometimes (your matcher API may have a method) need to surround above expression with ^...$ , that is ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/136505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ] }
136,548
In C++ you can initialize a variable in an if statement, like so: if (CThing* pThing = GetThing()){} Why would one consider this bad or good style? What are the benefits and disadvantages? Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this: if (CThing* pThing = GetThing() && pThing->IsReallySomeThing()){} If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why. Question borrowed from here, similar topic but PHP.
The important thing is that a declaration in C++ is not an expression. bool a = (CThing* pThing = GetThing()); // not legit!! You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration. if(A *a = new A){ // this is legit and a is scoped here} How can we know whether a is defined between one term and another in an expression? if((A *a = new A) && a->test()){ // was a really declared before a->test?} Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit: if (CThing* pThing = GetThing()){ if(pThing->IsReallySomeThing()) { }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/136548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ] }
136,554
I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt. Ideas? #!/usr/bin/expect --spawn $env(SHELL)match_max 100000set timeout 2send "echo This will print timed out\r"expect { timeout { puts "timed out at step 1" } "foo " { puts "it said foo at step 1"}}puts "Starting test two\r"send "echo This will not print timed out\r"expect -re { timeout { puts "timed out at step 2" ; exit } "foo " { puts "it said foo at step 2"}}
The important thing is that a declaration in C++ is not an expression. bool a = (CThing* pThing = GetThing()); // not legit!! You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration. if(A *a = new A){ // this is legit and a is scoped here} How can we know whether a is defined between one term and another in an expression? if((A *a = new A) && a->test()){ // was a really declared before a->test?} Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit: if (CThing* pThing = GetThing()){ if(pThing->IsReallySomeThing()) { }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/136554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10888/" ] }
136,615
How can I programmatically determine if I have access to a server (TCP) with a given IP address and port using C#?
Assuming you mean through a TCP socket: IPAddress IP;if(IPAddress.TryParse("127.0.0.1",out IP)){ Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try{ s.Connect(IPs[0], port); } catch(Exception ex){ // something went wrong }} For more information: http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
136,617
How do I programmatically force an onchange event on an input? I've tried something like this: var code = ele.getAttribute('onchange');eval(code); But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.
Create an Event object and pass it to the dispatchEvent method of the element: var element = document.getElementById('just_an_example');var event = new Event('change');element.dispatchEvent(event); This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element. By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do. If you want the event to bubble, you need to pass a second argument to the Event constructor: var event = new Event('change', { bubbles: true }); Information about browser compability: dispatchEvent() Event()
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/136617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ] }
136,638
How can I compare the content of two (or more) large .resx files? With hundreds of Name/Value pairs in each file, it'd be very helpful to view a combined version. I'm especially interested in Name/Value pairs which are present in the neutral culture but are not also specified in a culture-specific version.
There is a great freeware tool to edit resx files where you can see multiple languages at once and clearly see what is missing or extra - Zeta Resource Editor
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/136638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360388/" ] }
136,703
I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++. Equivalent of this if you know Cocoa: NSString *string = [NSString stringWithContentsOfFile:file];
We can do it but it's a long line : #include<fstream>#include<iostream>#include<iterator>#include<string>using namespace std;int main(){ // The one-liner string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>()); // Check result cout << fileContents;} Edited : use "istreambuf_iterator" instead of "istream_iterator"
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ] }
136,734
Is it possible to make it appear to a system that a key was pressed, for example I need to make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python. A better way to put it, I need to emulate a key press, I.E. not capture a key press. More Info (as requested):I am running windows XP and need to send the keys to another application.
Install the pywin32 extensions. Then you can do the following: import win32com.client as comcltwsh= comclt.Dispatch("WScript.Shell")wsh.AppActivate("Notepad") # select another applicationwsh.SendKeys("a") # send the keys you want Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here , perhaps. EDIT: Sending F11 import win32com.client as comctlwsh = comctl.Dispatch("WScript.Shell")# Google Chrome window titlewsh.AppActivate("icanhazip.com")wsh.SendKeys("{F11}")
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
136,771
How can I drop sql server agent jobs, if (and only if) it exists? This is a well functioning script for stored procedures . How can I do the same to sql server agent jobs? if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[storedproc]GOCREATE PROCEDURE [dbo].[storedproc] ...
Try something like this: DECLARE @jobId binary(16)SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')IF (@jobId IS NOT NULL)BEGIN EXEC msdb.dbo.sp_delete_job @jobIdENDDECLARE @ReturnCode intEXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job' Best to read the docs on all the parameters required for 'sp_add_job' and 'sp_delete_job'
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/136771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ] }
136,782
I have a datetime column in MySQL. How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
If you're looking for a way to normalize a date into MySQL format, use the following $phpdate = strtotime( $mysqldate );$mysqldate = date( 'Y-m-d H:i:s', $phpdate ); The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp. The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format. ( Editor Note : This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/136782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70/" ] }
136,793
I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name): people = []info = 'a' # must fill variable with something, otherwise loop won't executewhile not info.empty? info = gets.chomp people += [Person.new(info)] if not info.empty?end This code would look much nicer in a do ... while loop: people = []do info = gets.chomp people += [Person.new(info)] if not info.empty?while not info.empty? In this code I don't have to assign info to some random string. Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?
CAUTION : The begin <code> end while <condition> is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop , e.g. loop do # some code here break if <condition>end Here's an email exchange in 23 Nov 2005 where Matz states: |> Don't use it please. I'm regretting this feature, and I'd like to|> remove it in the future if it's possible.||I'm surprised. What do you regret about it?Because it's hard for users to tell begin <code> end while <cond>works differently from <code> while <cond> RosettaCode wiki has a similar story: During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/136793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ] }
136,836
What is the slickest way to initialize an array of dynamic size in C# that you know of? This is the best I could come up with private bool[] GetPageNumbersToLink(IPagedResult result){ if (result.TotalPages <= 9) return new bool[result.TotalPages + 1].Select(b => true).ToArray(); ...
use Enumerable.Repeat Enumerable.Repeat(true, result.TotalPages + 1).ToArray()
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/136836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ] }
136,837
A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials. One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP. The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent. Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps?
I've implemented this by maintaining a hashtable of currently logged in users, the key was the username, the value was their last activity time. When logging in, you just check this hashtable for the key, and if it exists, reject the login. When the user does anything, you update the hashtable with the time (This is easy if you make it part of the core page framework). If the time in the hashtable is greater than 20 minutes of inactivity, you remove them. You can do this every time the hashtable is checked, so even if you only had one user, and the tried to login several hours later, during that initial check, it would remove them from the hashtable for being idle. Some examples in C# (Untested): public Dictionary<String,DateTime> UserDictionary{ get { if (HttpContext.Current.Cache["UserDictionary"] != null) { return HttpContext.Current.Cache["UserDictionary"] as Dictionary<String,DateTime>; } return new Dictionary<String,DateTime>(); } set { HttpContext.Current.Cache["UserDictionary"] = value; }}public bool IsUserAlreadyLoggedIn(string userName){ removeIdleUsers(); return UserDictionary.ContainsKey(userName);}public void UpdateUser(string userName){ UserDictionary[userName] = DateTime.Now; removeIdleUsers();}private void removeIdleUsers(){ for (int i = 0; i < UserDictionary.Length; i++) { if (user[i].Value < DateTime.Now.AddMinutes(-20)) user.RemoveAt(i); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
136,880
So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions: It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change another function somewhere else. Is this something that just gets easier with experience? Are the benefits of using const really enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it? I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.
This is the definitive article on "const correctness": https://isocpp.org/wiki/faq/const-correctness . In a nutshell, using const is good practice because... It protects you from accidentally changing variables that aren't intended be changed, It protects you from making accidental variable assignments, and The compiler can optimize it. For instance, you are protected from if( x = y ) // whoops, meant if( x == y ) At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good. You are correct in that it can be difficult to use const-correctness consistently, but the end code is more concise and safer to program with. When you do a lot of C++ development, the benefits of this quickly manifest.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/136880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ] }
136,899
In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error? If so, in what circumstances would you use this? Code examples are welcome. Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use @fopen($file); and then check afterwards... but you can get rid of the @ by doing if (file_exists($file)){ fopen($file);}else{ die('File not found');} or similar. I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?
Note: Firstly, I realise 99% of PHP developers use the error suppression operator (I used to be one of them), so I'm expecting any PHP dev who sees this to disagree. In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error? Short answer: No! Longer more correct answer: I don't know as I don't know everything, but so far I haven't come across a situation where it was a good solution. Why it's bad: In what I think is about 7 years using PHP now I've seen endless debugging agony caused by the error suppression operator and have never come across a situation where it was unavoidable. The problem is that the piece of code you are suppressing errors for, may currently only cause the error you are seeing; however when you change the code which the suppressed line relies on, or the environment in which it runs, then there is every chance that the line will attempt to output a completely different error from the one you were trying to ignore. Then how do you track down an error that isn't outputting? Welcome to debugging hell! It took me many years to realise how much time I was wasting every couple of months because of suppressed errors. Most often (but not exclusively) this was after installing a third party script/app/library which was error free in the developers environment, but not mine because of a php or server configuration difference or missing dependency which would have normally output an error immediately alerting to what the issue was, but not when the dev adds the magic @. The alternatives (depending on situation and desired result): Handle the actual error that you are aware of, so that if a piece of code is going to cause a certain error then it isn't run in that particular situation. But I think you get this part and you were just worried about end users seeing errors, which is what I will now address. For regular errors you can set up an error handler so that they are output in the way you wish when it's you viewing the page, but hidden from end users and logged so that you know what errors your users are triggering. For fatal errors set display_errors to off (your error handler still gets triggered) in your php.ini and enable error logging. If you have a development server as well as a live server (which I recommend) then this step isn't necessary on your development server, so you can still debug these fatal errors without having to resort to looking at the error log file. There's even a trick using the shutdown function to send a great deal of fatal errors to your error handler. In summary: Please avoid it. There may be a good reason for it, but I'm yet to see one, so until that day it's my opinion that the (@) Error suppression operator is evil. You can read my comment on the Error Control Operators page in the PHP manual if you want more info.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ] }
136,937
Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the hashchange event: window.addEventListener("hashchange", function(e) { // ...}) If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/136937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ] }
136,946
What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)? For example, when should one use enum {BUFFER = 1234}; over #define BUFFER 1234
enum defines a syntactical element. #define is a pre-preprocessor directive, executed before the compiler sees the code, and therefore is not a language element of C itself. Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a #define made by another. This can be hard to track down.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21539/" ] }
136,948
I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7. The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is "C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ EIPortal_DEV_2_0_5_4[1].expd" This unfortunately does not resolve to the physical file when calling FileExists() or when attempting to create a TFileStream object. The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of "Content.IE5\ALBKHO3Q" whose absolute path would be expressed as "C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd" Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing. Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of "application/x-expeditors" . The registration of the ".expd" / "application/x-expeditors" mime-type looks like this. [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd] @="ExpeditorsInstaller""Content Type"="application/x-expeditors"[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller]"EditFlags"=hex:00,00,01,00[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell][HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open]@=""[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command]@="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\""[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors]"Extension"=".expd" I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix "[n]" may be the unique key. I have tried wininet method GetUrlCacheEntryInfo but that requires the URL, not the virtual path handed over by IE. My hope is that there is a Shell function that given a virtual path will hand back the physical path.
enum defines a syntactical element. #define is a pre-preprocessor directive, executed before the compiler sees the code, and therefore is not a language element of C itself. Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a #define made by another. This can be hard to track down.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13183/" ] }
136,975
Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler. In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed. It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once. Is that possible? EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough.
From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a += or a -= . So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is null - if so, then no event handler has been added. If not, then maybe and you can loop through the values in Delegate.GetInvocationList . If one is equal to the delegate that you want to add as event handler, then you know it's there. public bool IsEventHandlerRegistered(Delegate prospectiveHandler){ if ( this.EventHandler != null ) { foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() ) { if ( existingHandler == prospectiveHandler ) { return true; } } } return false;} And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore -= and += , as suggested by @Lou Franco. However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/136975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ] }
137,006
Is there any way to redefine a class or some of its methods without using typical inheritance? For example: class third_party_library { function buggy_function() { return 'bad result'; } function other_functions(){ return 'blah'; }} What can I do to replace buggy_function() ? Obviously this is what I would like to do class third_party_library redefines third_party_library{ function buggy_function() { return 'good result'; } function other_functions(){ return 'blah'; }} This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method. I've found this library that says it can do it, but I'm wary as it's 4 years old. EDIT: I should have clarified that I cannot rename the class from third_party_library to magical_third_party_library or anything else because of framework limitations. For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a "partial class."
It's called monkey patching . But, PHP doesn't have native support for it. Though, as others have also pointed out, the runkit library is available for adding support to the language and is the successor to classkit . And, though it seemed to have been abandoned by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a new home and maintainer . I still can't say I'm a fan of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug. Still, runkit_method_redefine appears to be what you're looking for, and an example of its use can be found in /tests/runkit_method_redefine.phpt in the repository: runkit_method_redefine('third_party_library', 'buggy_function', '', 'return \'good result\'');
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ] }
137,011
I have a lot of nice MATLAB code that runs too slowly and would be a pain to write over in C. The MATLAB compiler for C does not seem to help much, if at all. Should it be speeding execution up more? Am I screwed?
I'll echo what dwj said: if your MATLAB code is slow, this is probably because it is not sufficiently vectorized. If you're doing explicit loops when you could be doing operations on whole arrays, that's the culprit. This applies equally to all array-oriented dynamic languages: Perl Data Language, Numeric Python, MATLAB/Octave, etc. It's even true to some extent in compiled C and FORTRAN compiled code: specially-designed vectorization libraries generally use carefully hand-coded inner loops and SIMD instructions (e.g. MMX, SSE, AltiVec).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
137,021
What is the best way to take a given PHP object and serialize it as XML? I am looking at simple_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.
take a look at PEAR's XML_Serializer package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc. Should do the trick
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ] }
137,038
How does one do this? If I want to analyze how something is getting compiled, how would I get the emitted assembly code?
Use the -S option to gcc (or g++ ), optionally with -fverbose-asm which works well at the default -O0 to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at. gcc -S helloworld.c This will run the preprocessor (cpp) over helloworld.c , perform the initial compilation and then stop before the assembler is run. For useful compiler options to use in that case, see How to remove "noise" from GCC/clang assembly output? (or just look at your code on Matt Godbolt's online Compiler Explorer which filters out directives and stuff, and has highlighting to match up source lines with asm using debug information.) By default, this will output the file helloworld.s . The output file can be still be set by using the -o option, including -o - to write to standard output for pipe into less . gcc -S -o my_asm_output.s helloworld.c Of course, this only works if you have the original source.An alternative if you only have the resultant object file is to use objdump , by setting the --disassemble option (or -d for the abbreviated form). objdump -S --disassemble helloworld > helloworld.dump -S interleaves source lines with normal disassembly output, so this option works best if debugging option is enabled for the object file ( -g at compilation time) and the file hasn't been stripped. Running file helloworld will give you some indication as to the level of detail that you will get by using objdump . Other useful objdump options include -rwC (to show symbol relocations, disable line-wrapping of long machine code, and demangle C++ names). And if you don't like AT&T syntax for x86, -Mintel . See the man page . So for example, objdump -drwC -Mintel -S foo.o | less . -r is very important with a .o that only has 00 00 00 00 placeholders for symbol references, as opposed to a linked executable.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/137038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ] }
137,043
When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this: <table> <tr><td>blah</td></tr></table> ...into this: <table> <tr> <td> blah </td> </tr></table>
You can do sgml-pretty-print and then indent-for-tab on the same region/buffer, provided you are in html-mode or nxml-mode. sgml-pretty-print adds new lines to proper places and indent-for-tab adds nice indentation. Together they lead to properly formatted html/xml.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ] }
137,054
How can I validate that my ASPNET AJAX installation is correct. I have Visual Studio 2008 and had never previously installed any AJAX version. My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior. I tried installing AJAX from MSDN followed by an IISRESET yet still it is still not working properly. What can I check to diagnose the problem? Update: When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler: http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&t=633564733834698722http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&t=ffffffff867086f6http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&t=ffffffff867086f6 but when I run within IIS i only get this single request : http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&t=ffffffff867086f6 Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests.
You can do sgml-pretty-print and then indent-for-tab on the same region/buffer, provided you are in html-mode or nxml-mode. sgml-pretty-print adds new lines to proper places and indent-for-tab adds nice indentation. Together they lead to properly formatted html/xml.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ] }
137,102
What's the best tool for viewing and editing a merge in Git? I'd like to get a 3-way merge view, with "mine", "theirs" and "ancestor" in separate panels, and a fourth "output" panel. Also, instructions for invoking said tool would be great. (I still haven't figure out how to start kdiff3 in such a way that it doesn't give me an error.) My OS is Ubuntu.
Meld is a free, open-source, and cross-platform (UNIX/Linux, OSX, Windows) diff/merge tool. Here's how to install it on: Ubuntu Mac Windows : "The recommended version of Meld for Windows is the most recent release, available as an MSI from https://meldmerge.org "
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/137102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21482/" ] }
137,114
Whats the best way to round in VBA Access? My current method utilizes the Excel method Excel.WorksheetFunction.Round(... But I am looking for a means that does not rely on Excel.
Be careful, the VBA Round function uses Banker's rounding, where it rounds .5 to an even number, like so: Round (12.55, 1) would return 12.6 (rounds up) Round (12.65, 1) would return 12.6 (rounds down) Round (12.75, 1) would return 12.8 (rounds up) Whereas the Excel Worksheet Function Round, always rounds .5 up. I've done some tests and it looks like .5 up rounding (symmetric rounding) is also used by cell formatting, and also for Column Width rounding (when using the General Number format). The 'Precision as displayed' flag doesn't appear to do any rounding itself, it just uses the rounded result of the cell format. I tried to implement the SymArith function from Microsoft in VBA for my rounding, but found that Fix has an error when you try to give it a number like 58.55; the function giving a result of 58.5 instead of 58.6. I then finally discovered that you can use the Excel Worksheet Round function, like so: Application.Round(58.55, 1) This will allow you to do normal rounding in VBA, though it may not be as quick as some custom function. I realize that this has come full circle from the question, but wanted to include it for completeness.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ] }
137,147
For example int f(int a) { ... return a > 10;} is that considered acceptable (not legal, I mean is it ``good code''), or should it always be in a conditional, like this int f(int a) { ... if (a > 10) return 1; else return 0;}
This is absolutely acceptable! In fact, Joel mentioned this on the latest stackoverflow podcast. He said it was the one thing he's had to show almost every programmer that starts at Fog Creek.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
137,182
How do I launch Windows' RegEdit with certain path located, like " HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0 ", so I don't have to do the clicking? What's the command line argument to do this? Or is there a place to find the explanation of RegEdit's switches?
There's a program called RegJump , by Mark Russinovich, that does just what you want. It'll launch regedit and move it to the key you want from the command line. RegJump uses (or at least used to) use the same regedit window on each invoke, so if you want multiple regedit sessions open, you'll still have to do things the old fashioned way for all but the one RegJump has adopted. A minor caveat, but one to keep note of, anyway.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18561/" ] }
137,212
If you want a cryptographically strong random numbers in Java, you use SecureRandom . Unfortunately, SecureRandom can be very slow. If it uses /dev/random on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty? Has anyone used Uncommon Maths as a solution to this problem? Can anybody confirm that this performance problem has been solved in JDK 6?
If you want true random data, then unfortunately you have to wait for it. This includes the seed for a SecureRandom PRNG. Uncommon Maths can't gather true random data any faster than SecureRandom , although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than /dev/random where that's available. If you want a PRNG, do something like this: SecureRandom.getInstance("SHA1PRNG"); What strings are supported depends on the SecureRandom SPI provider, but you can enumerate them using Security.getProviders() and Provider.getService() . Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy. The exception is that if you don't call setSeed() before getting data, then the PRNG will seed itself once the first time you call next() or nextBytes() . It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/137212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3150/" ] }
137,219
I am looking for the way to mount NTFS hard disk on FreeBSD 6.2 in read/write mode. searching google, I found that NTFS-3G can be a help. Using NTFS-3G, there is no problem when I try to mount/unmount NTFS manually: mount: ntfs-3g /dev/ad1s1 /home/admin/data -o uid=1002, or umount: umount /home/admin/data But I have a problem when try to mount ntfs hard disk automatically at boot time. I have tried: adding fstab: /dev/ad1s1 /home/admin/data ntfs-3g uid=1002 0 0 make a script, that automatically mount ntfs partition at start up, on /usr/local/etc/rc.d/ directory. But it is still failed.The script works well when it is executed manually. Does anyone know an alternative method/ solution to have read/write access NTFS on FreeBSD 6.2? Thanks.
If you want true random data, then unfortunately you have to wait for it. This includes the seed for a SecureRandom PRNG. Uncommon Maths can't gather true random data any faster than SecureRandom , although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than /dev/random where that's available. If you want a PRNG, do something like this: SecureRandom.getInstance("SHA1PRNG"); What strings are supported depends on the SecureRandom SPI provider, but you can enumerate them using Security.getProviders() and Provider.getService() . Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy. The exception is that if you don't call setSeed() before getting data, then the PRNG will seed itself once the first time you call next() or nextBytes() . It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/137219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
137,226
What are the patterns you use to determine the frequent queries? How do you select the optimization factors? What are the types of changes one can make?
This is a nice question, if rather broad (and none the worse for that). If I understand you, then you're asking how to attack the problem of optimisation starting from scratch. The first question to ask is: " is there a performance problem? " If there is no problem, then you're done. This is often the case. Nice. On the other hand... Determine Frequent Queries Logging will get you your frequent queries. If you're using some kind of data access layer, then it might be simple to add code to log all queries. It is also a good idea to log when the query was executed and how long each query takes. This can give you an idea of where the problems are. Also, ask the users which bits annoy them. If a slow response doesn't annoy the user, then it doesn't matter. Select the optimization factors? (I may be misunderstanding this part of the question)You're looking for any patterns in the queries / response times. These will typically be queries over large tables or queries which join many tables in a single query. ... but if you log response times, you can be guided by those. Types of changes one can make? You're specifically asking about optimising tables. Here are some of the things you can look for: Denormalisation . This brings several tables together into one wider table, so in stead of your query joining several tables together, you can just read one table. This is a very common and powerful technique. NB. I advise keeping the original normalised tables and building the denormalised table in addition - this way, you're not throwing anything away. How you keep it up to date is another question. You might use triggers on the underlying tables, or run a refresh process periodically. Normalisation . This is not often considered to be an optimisation process, but it is in 2 cases: updates. Normalisation makes updates much faster because each update is the smallest it can be (you are updating the smallest - in terms of columns and rows - possible table. This is almost the very definition of normalisation. Querying a denormalised table to get information which exists on a much smaller (fewer rows) table may be causing a problem. In this case, store the normalised table as well as the denormalised one (see above). Horizontal partitionning . This means making tables smaller by putting some rows in another, identical table. A common use case is to have all of this month's rows in table ThisMonthSales , and all older rows in table OldSales , where both tables have an identical schema. If most queries are for recent data, this strategy can mean that 99% of all queries are only looking at 1% of the data - a huge performance win. Vertical partitionning . This is Chopping fields off a table and putting them in a new table which is joinned back to the main table by the primary key. This can be useful for very wide tables (e.g. with dozens of fields), and may possibly help if tables are sparsely populated. Indeces . I'm not sure if your quesion covers these, but there are plenty of other answers on SO concerning the use of indeces. A good way to find a case for an index is: find a slow query. look at the query plan and find a table scan. Index fields on that table so as to remove the table scan. I can write more on this if required - leave a comment. You might also like my post on this .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65724/" ] }
137,227
How can I list all the types that are declared by a module in Ruby?
Use the constants method defined in the Module module. From the Ruby documentation: Module.constants => array Returns an array of the names of all constants defined in the system. This list includes the names of all modules and classes. p Module.constants.sort[1..5] produces: ["ARGV", "ArgumentError", "Array", "Bignum", "Binding"] You can call constants on any module or class you would like. p Class.constants
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
137,258
Here's a common code pattern I have to work with: class foo {public: void InitMap(); void InvokeMethodsInMap(); static void abcMethod(); static void defMethod();private: typedef std::map<const char*, pMethod> TMyMap; TMyMap m_MyMap;}voidfoo::InitMap(){ m_MyMap["abc"] = &foo::abcMethod; m_MyMap["def"] = &foo::defMethod;}voidfoo::InvokeMethodsInMap(){ for (TMyMap::const_iterator it = m_MyMap.begin(); it != m_MyMap.end(); it++) { (*it->second)(it->first); }} However, I have found that the order that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order. I thought that by using begin() in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed. This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build). Can anyone explain this strange behaviour?
Don't use const char* as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a std::string as the key type, instead. std::map is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some criteria (by default, < comparison between keys).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ] }
137,282
http://en.wikipedia.org/wiki/Diamond_problem I know what it means, but what steps can I take to avoid it?
A practical example: class A {};class B : public A {};class C : public A {};class D : public B, public C {}; Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable. To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue: class A {};class B : virtual public A {};class C : virtual public A {};class D : public B, public C {};
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ] }
137,313
I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns. I wrote a small Perl script to do this: #!/usr/bin/perldie("need max length\n") unless $#ARGV == 0;while (<STDIN>){ $_ = substr($_, 0, $ARGV[0]); chomp($_); print "$_\n";} But I have a feeling that this functionality is probably built into some other tools (sed?) That I just don't know enough about to use for this task. So my question sort of a reverse question: how do I truncate a line of stdin Without writing a program to do it?
Pipe output to: cut -b 1-LIMIT Where LIMIT is the desired line width.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ] }
137,314
I've got a CAkePHP 1.2 site. I've got three related Models/tables:A Comment has exactly one Touch, a Touch has exactly one Touchtype. In each model, I have a belongs to, so I haveComments belongs to Touch, Touch belongs to Touchtype. I'm trying to get a list of comments that includes information about the touch stored in the touchtype table. $this->Comment->find(...) I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help.
Pipe output to: cut -b 1-LIMIT Where LIMIT is the desired line width.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43/" ] }
137,326
How do you embed a SWF file in an HTML page?
The best approach to embed a SWF into an HTML page is to use SWFObject . It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content. It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page. An example from the documentation: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>SWFObject dynamic embed - step 3</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script type="text/javascript" src="swfobject.js"></script> <script type="text/javascript"> swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0"); </script> </head> <body> <div id="myContent"> <p>Alternative content</p> </div> </body></html> A good tool to use along with this is the SWFObject HTML and JavaScript generator . It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters. It Is highly recommended and very simple to use.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/137326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ] }
137,336
PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature. Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument. Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible. How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages? Also, how can you do all this while accounting for inheritance in Php? Consider: <?phpclass InterfaceClass{#...}class UsesInterfaceClass{ function SetObject(&$obj) { // What do I put here to make sure that $obj either // is of type InterfaceObject or inherits from it }}?> Then a user of this code implements the interface with their own concrete class: <?phpclass ConcreteClass extends InterfaceClass{}?> I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?
Actually for classes you can provide type hinting in PHP (5+). <?php class UsesBaseClass { function SetObject(InterfaceObject $obj) { } } ?> This will also work correctly with inheritance as you would expect it to. As an aside, don't put the word 'object' in your class names...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ] }
137,340
The question posed came about during a 2nd Year Comp Science lecture while discussing the impossibility of generating numbers in a deterministic computational device. This was the only suggestion which didn't depend on non-commodity-class hardware. Subsequently nobody would put their reputation on the line to argue definitively for or against it. Anyone care to make a stand for or against. If so, how about a mention as to a possible implementation?
No. A malicious machine on your network could use ARP spoofing (or a number of other techniques) to intercept your pings and reply to them after certain periods. They would then not only know what your random numbers are, but they would also control them. Of course there's still the question of how deterministic your local network is, so it might not be as easy as all that in practice. But since you get no benefit from pinging random IPs on the internet, you might just as well draw entropy from ethernet traffic. Drawing entropy from devices attached to your machine is a well-studied principle, and the pros and cons of various kinds of devices and methods of measuring can be e.g. stolen from the implementation of /dev/random. [ Edit : as a general principle, when working in the fundamentals of security (and the only practical needs for significant quantities of truly random data are security-related) you MUST assume that a fantastically well-resourced, determined attacker will do everything in their power to break your system. For practical security, you can assume that nobody wants your PGP key that badly, and settle for a trade-off of security against cost. But when inventing algorithms and techniques, you need to give them the strongest security guarantees that they could ever possibly face. Since I can believe that someone, somewhere, might want someone else's private key badly enough to build this bit of kit to defeat your proposal, I can't accept it as an advance over current best practice. AFAIK /dev/random follows fairly close to best practice for generating truly random data on a cheap home PC] [ Another edit : it has suggested in comments that (1) it is true of any TRNG that the physical process could be influenced, and (2) that security concerns don't apply here anyway. The answer to (1) is that it's possible on any real hardware to do so much better than ping response times, and gather more entropy faster, that this proposal is a non-solution. In CS terms, it is obvious that you can't generate random numbers on a deterministic machine, which is what provoked the question. But then in CS terms, a machine with an external input stream is non-deterministic by definition, so if we're talking about ping then we aren't talking about deterministic machines. So it makes sense to look at the real inputs that real machines have, and consider them as sources of randomness. No matter what your machine, raw ping times are not high on the list of sources available, so they can be ruled out before worrying about how good the better ones are. Assuming that a network is not subverted is a much bigger (and unnecessary) assumption than assuming that your own hardware is not subverted. The answer to (2) is philosophical. If you don't mind your random numbers having the property that they can be chosen at whim instead of by chance, then this proposal is OK. But that's not what I understand by the term 'random'. Just because something is inconsistent doesn't mean it's necessarily random. Finally, to address the implementation details of the proposal as requested: assuming you accept ping times as random, you still can't use the unprocessed ping times as RNG output. You don't know their probability distribution, and they certainly aren't uniformly distributed (which is normally what people want from an RNG). So, you need to decide how many bits of entropy per ping you are willing to rely on. Entropy is a precisely-defined mathematical property of a random variable which can reasonably be considered a measure of how 'random' it actually is. In practice, you find a lower bound you're happy with. Then hash together a number of inputs, and convert that into a number of bits of output less than or equal to the total relied-upon entropy of the inputs. 'Total' doesn't necessarily mean sum: if the inputs are statistically independent then it is the sum, but this is unlikely to be the case for pings, so part of your entropy estimate will be to account for correlation. The sophisticated big sister of this hashing operation is called an 'entropy collector', and all good OSes have one. If you're using the data to seed a PRNG, though, and the PRNG can use arbitrarily large seed input, then you don't have to hash because it will do that for you. You still have to estimate entropy if you want to know how 'random' your seed value was - you can use the best PRNG in the world, but its entropy is still limited by the entropy of the seed.]
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
137,359
I produce a report as an CSV file.When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly. For example, if the CSV file contains ...,005,... Then Excel shows it as 5.Is there a way to override this and display 005? I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it. I use Excel 2003.
There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help. My preference is the first option. Option 1 – Change the data in the file You could change the data in the .csv file as follows ..., =”005” ,...This will be displayed in Excel as ..., 005 ,... Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting Option 2 – Format the data If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format 000 Option 3 – Change the file extension to .dif (Data interchange format) Change the file extension and use the file import wizard to control the formats.Files with a .dif extension are automatically opened by Excel when double clicked on. Step by step: Change the file extension from .csv to .dif Double click on the file to open it in Excel. The 'File Import Wizard' will be launched. Set the 'File type' to 'Delimited' and click on the 'Next' button. Under Delimiters, tick 'Comma' and click on the 'Next' button. Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'. Click on the finish button, the file will be opened by Excel with the formats that you have specified.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/137359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10557/" ] }
137,398
I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance: SELECT Column1, Column2, Column3+Column4 AS [Added Values]FROM Table where Column3 or Column4 may be null. In this case, I want null to be considered zero (so 4 + null = 4, null + null = 0 ). Any suggestions as to how to accomplish this?
Since ISNULL in Access is a boolean function (one parameter), use it like this: SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]FROM Table
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14902/" ] }
137,399
Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed. I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it. Just wondering what people's views on this are?
It's simply a very minimal test, and should be documented as such. It only verifies that it doesn't explode when run. The worst part about tests like this is that they present a false sense of security. Your code coverage will go up, but it's illusory. Very bad odor.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ] }
137,400
Looking at the processmodel element in the Web.Config there are two attributes. maxWorkerThreads="25" maxIoThreads="25" What is the difference between worker threads and I/O threads?
Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data. I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for "long" periods of time (hundreds of milliseconds). They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel. A single I/O thread may be managing multiple completion ports to maintain throughput. Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of "Thread". ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used. Worker threads are threads upon which regular "work" or just plain code/processing happens. Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput. [Edit]: I also found this link which is particularly relevant to this question: http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19490/" ] }
137,448
Take the following snippet: List<int> distances = new List<int>(); Was the redundancy intended by the language designers? If so, why?
The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following: A variable named distances of type List<int> . An object on the heap of type List<int> . Consider the following: Person[] coworkers = new Employee[20]; Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
137,449
I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled. <div class="app_setting"> <label">Name</label> <input type="text" name="name"/></div>.app_setting:hover { cursor:move;} Any ideas how to get the hover to apply also to the child elements?
.app_setting *:hover { cursor:move }
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14971/" ] }
137,454
Considering "private" is the default access modifier for class Members, why is the keyword even needed?
It's for you (and future maintainers), not the compiler.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
137,487
I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities. What is the difference, specifically in PHP? Does it have something to do with === ?
It's language specific, but in PHP : Null means " nothing ". The var has not been initialized. False means " not true in a boolean context ". Used to explicitly show you are dealing with logical issues. 0 is an int . Nothing to do with the rest above, used for mathematics. Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context , which (in PHP) is False . If you test it with == , it's testing the boolean value, so you will get equality. If you test it with === , it will test the type, and you will get inequality. So why are they useful ? Well, look at the strrpos() function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string ! <?php// pitfall :if (strrpos("Hello World", "Hello")) { // never exectuted}// smart move :if (strrpos("Hello World", "Hello") !== False) { // that works !}?> And of course, if you deal with states: You want to make a difference between DebugMode = False (set to off), DebugMode = True (set to on) and DebugMode = Null (not set at all, will lead to hard debugging ;-)).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/137487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ] }
137,521
My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class: invoice.address_id = 1invoice.address = some_address Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling attr_protected :address_id is most likely not the solution since based on the documentation it only prevents mass assignments. Thanks!
You want attr_readonly .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082/" ] }
137,523
I'd like to learn assembler. However, there are very few resources for doing assembler with OS X. Is there anyone out there who has programmed in assembly on a Mac? Where did you learn? And, is there any reason I shouldn't be doing assembly? Do I risk (significantly) crashing my computer irreparably?
If you're using a PowerPC Mac, look into gcc inline assembler. Otherwise, look into nasm. I can't give any decent references to PPC ASM (they're few and far between), but I suggest the following things to learn x86 asm: The book Reversing by Eldad Eilam Compile simple C source with gcc -S and read the assembly generated Use Sandpile Join #openrce on irc.freenode.net and use OpenRCE Also, if you're not in kernel mode then there's no chance of screwing anything up, really, and even if you are in kernel mode it's hard to really destroy anything. Edit: Also, get gcc and such from XCode not Macports or somesuch. You're in for a world of malformed Mach-O files if you don't. Not fun to diagnose file format issues when you're just starting asm hacking.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ] }
137,526
On some systems it is UTF-8, on others latin-1. How do you set this? Is it something in php.ini? (I know you can set the encoding/charset for a given page by setting HTTP headers, but this is not what I am looking for.) Alex
If you're using a PowerPC Mac, look into gcc inline assembler. Otherwise, look into nasm. I can't give any decent references to PPC ASM (they're few and far between), but I suggest the following things to learn x86 asm: The book Reversing by Eldad Eilam Compile simple C source with gcc -S and read the assembly generated Use Sandpile Join #openrce on irc.freenode.net and use OpenRCE Also, if you're not in kernel mode then there's no chance of screwing anything up, really, and even if you are in kernel mode it's hard to really destroy anything. Edit: Also, get gcc and such from XCode not Macports or somesuch. You're in for a world of malformed Mach-O files if you don't. Not fun to diagnose file format issues when you're just starting asm hacking.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ] }
137,544
Is there such a thing as an x86 assembler that I can call through C#? I want to be able to pass x86 instructions as a string and get a byte array back. If one doesn't exist, how can I make my own? To be clear - I don't want to call assembly code from C# - I just want to be able to assemble code from instructions and get the machine code in a byte array. I'll be injecting this code (which will be generated on the fly) to inject into another process altogether.
As part of some early prototyping I did on a personal project, I wrote quite a bit of code to do something like this. It doesn't take strings -- x86 opcodes are methods on an X86Writer class. Its not documented at all, and has nowhere near complete coverage, but if it would be of interest, I would be willing to open-source it under the New BSD license. UPDATE: Ok, I've created that project -- Managed.X86
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16942/" ] }
137,550
I've heard many times that all programming is really a subset of math. Some suggest that OO, at its roots, is mathematically based, but I don't get the connection, aside from some obvious examples: using induction to prove a recursive algorithm, formal correctness proofs, functional languages, lambda calculus, asymptotic complexity, DFAs, NFAs, Turing Machines, and theoretical computation in general, and the fact that everything on the box is binary. I know math is very important to programming, but I struggle with this "subset" view. In what ways is programming a subset of math? I'm looking for an explanation that might have relevance to enterprise/OO development, if there is a strong enough connection, that is.
Overall, remember that mathematics is a formal codification of logic, which is also what we do in software. The list of topics in your question is loaded with mathematical problems. We are able to do programming on a fairly high level of abstraction , so the raw mathematics may not be staring you in the face. For example, you mentioned DFAs.. you can use a regular expression in your programs without knowing any math, but you'll find more of a need for mathematics when you want to design a good regular expression engine. I think you've hit on an interesting point. Programming is an art and a science. There are a lot of "tools of the trade", and you don't necessarily sit down and do a lot of high-level mathematics in order to simply write a program. In fact, when you're programming, you many not really being doing much mathematics or computer science. It's when we start to solve difficult problems in computer science that mathematics shows up. The deeper you go, the more it will flesh itself out.. often in lower levels of abstraction. There are also some realms of programming that you don't necessarily have to work in, but they involve more math. For example, while you can certainly learn a language and write some apps without any formal mathematics, you won't get very far in algorithm analysis without some applied math.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10759/" ] }
137,629
How do you render primitives as wireframes in OpenGL?
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); to switch on, glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); to go back to normal. Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/137629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
137,657
Is there something like InstallShield that I can use for free?
WiX Very powerful and flexible . Can produce MSI packages (Microsoft deployment format of choice) Almost no documentation Very steep learning curve. XML-based. Recommended for very complex installators. Inno Setup Cannot produce MSI packages. Its scripting part looks like INI files structure. Uses Pascal Script based language for extra flexibility. NSIS Cannot produce MSI packages. Fully scripted, very powerful but at cost of high learning curve. Recommened if WiX is too much and Inno Setup not enough. AdvancedInstaller Basic version is free. Can produce MSI packages. Very good user-interface, almost no learning curve to get things done. XML-based (but schema is not very user-friendly, doesn't really matter as you would use GUI editor anyway) The best option if you have only basic installer requirements and don't have time to learn something new. IzPack Cross-platform Maven integration Customizable actions Well documented Opensource
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/137657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
137,659
Do you know any easy or simple way to make a map object (from the STL library) persistent (i.e. write it to a file) so that you can recover its state later when the program in run later ?? Thanks for your help
I believe the Boost Serialization library is capable of serializing std::map, but the standard library itself provides no means. Serialization is a great library with a lot of features and is easy to use and to extend to your own types.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876/" ] }
137,660
In a J2EE application (like one running in WebSphere), when I use System.out.println() , my text goes to standard out, which is mapped to a file by the WebSphere admin console. In an ASP.NET application (like one running in IIS), where does the output of Console.WriteLine() go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here? I'm not asking if I should log there (I use log4net), but where does the output go? My best info came from this discussion where they say Console.SetOut() can change the TextWriter , but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code.
If you use System.Diagnostics.Debug.WriteLine(...) instead of Console.WriteLine() , then you can see the results in the Output window of Visual Studio.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/137660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22514/" ] }
137,661
In C#, I can do this: class Program{ static void Main(string[] args) { List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } }}public class Animal{ public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); }}public class Dog : Animal{ public override string MakeNoise() { return "Woof!"; }}public class Cat : Animal{ public override string MakeNoise() { return "Meow!"; }} Obviously, the output is (Slightly paraphrased): Woof Dog is Sleeping Meow Cat is Sleeping Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?
edit: added more code for your updated question disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct. The exact same way, with classes and overridden methods: class Animal def MakeNoise return "" end def Sleep print self.class.name + " is sleeping.\n" endendclass Dog < Animal def MakeNoise return "Woof!" endendclass Cat < Animal def MakeNoise return "Meow!" endendanimals = [Dog.new, Cat.new]animals.each {|a| print a.MakeNoise + "\n" a.Sleep}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ] }
137,688
There are a lot of new features that came with the .Net Framework 3.5. Most of the posts and info on the subject list stuff about new 3.5 features and C# 3 changes at the same time. But C# 3 can be used without .Net 3.5. Does anyone know of a good post describing the changes to the language? (Besides the boring, explicit official specs at MSDN that is.)
Update: I can certainly understand. Eric Lippert has some more indepth posts.. Check them out . I liked the series of posts by scottgu on the new language features..Some more info here as well http://www.danielmoth.com/Blog/2007/11/top-10-things-to-know-about-visual.html esp the section on language features.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291/" ] }
137,773
In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs: ./authpam: /lib/libpam.so.0: no version information available (required by authpam) The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning. I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :( Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem? Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc?
The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning. You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers. Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.) Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.) You last option will be compiling with a library with a different minor version number, using a custom linking script: http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
137,775
I've wanted this for fluent interfaces. See, for example this Channel9 discussion. Would probably require also adding indexed properties. What are your thoughts? Would the advantages outweigh the "language clutter"?
Since properties are just syntactic sugar for methods, I don't see why C# should have extension methods without extension properties.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22528/" ] }
137,783
Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.
There is no (exactly correct) solution which will run in a constant amount of time, since 1/7 is an infinite decimal in base 5. One simple solution would be to use rejection sampling, e.g.: int i;do{ i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25} while(i > 21);// i is now uniformly random between 1 and 21return i % 7 + 1; // result is now uniformly random between 1 and 7 This has an expected runtime of 25/21 = 1.19 iterations of the loop, but there is an infinitesimally small probability of looping forever.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/137783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22535/" ] }
137,784
I have a report in SSRS 2005 that's based on a query that's similar to this one: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC'AND col2 LIKE '%XYZ%' I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!
Charles almost had the correct answer. It should be: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked = 0 OR col2 LIKE '%XYZ%') This is a classic "pattern" in SQL for conditional predicates. If @checked = 0 , then it will return all rows matching the remainder of the predicate ( col1 = 'ABC' ). SQL Server won't even process the second half of the OR . If @checked = 1 then it will evaluate the second part of the OR and return rows matching col1 = 'ABC' AND col2 LIKE '%XYZ%' If you have multiple conditional predicates they can be chained together using this method (while the IF and CASE methods would quickly become unmanageable). For example: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked1 = 0 OR col2 LIKE '%XYZ%') AND (@checked2 = 0 OR col3 LIKE '%MNO%') Don't use dynamic SQL, don't use IF or CASE.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11507/" ] }
137,803
Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.
If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer. SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1 The newId() will generate a new GUID for you that you can use as your automatically generated id column.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396/" ] }
137,812
As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the committee website . All sorts of new features are being added, the biggest being concepts and lambdas. There is a very comprehensive Wikipedia article with many of the new features. GCC 4.3 and later implement some C++0x features . As far as new features go, I really like type traits (and the appropriate concepts), but my definite leader is variadic templates. Until 0x, long template lists have involved Boost Preprocessor usually, and are very unpleasant to write. This makes things a lot easier and allows C++0x templates to be treated like a perfectly functional language using variadic templates. I've already written some very cool code with them already, and I can't wait to use them more often! So what features are you most eagerly anticipating?
auto keyword for variable type inferencing
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16855/" ] }
137,817
I'm interested in building a PC for a car that will boot off of a USB flash drive. I'm planning on using Windows PE 2.0 for it with the GUI being written in C# or VB.NET. Obviously, for this to work, I'd need to have .NET 2.0 or later installed. Understanding that .NET is not included by default, is there a way to package .NET 2.0 with Windows PE 2.0 in such a way as to allow my GUI application to work?
auto keyword for variable type inferencing
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
137,840
We have an existing WCF service that makes use of wsDualHttpBinding to enable callbacks to the client. I am considering moving it to netTcpBinding for better performance, but I'm quite wary of moving away from the IIS-hosted service (a "comfort zone" we currently enjoy) into having our own Windows service to host it. I was hoping we could still host this on IIS 7 but Win2K8 won't be reality for us for some time. What things should I watch out for when creating our own Windows service to host our WCF service? Things like lifetime management and request throttling are features that come free with IIS hosting so I'd also like to know how we can effectively host our service on our own without the convenience of having IIS do the hard work for us. Thanks! :)
So as you cannot host using WAS there are a couple of things to realise. If the service crashes it doesn't restart by default (although you can change this in service properties) IIS will recycle the application pool if it hangs or grows too big; you must do this yourself if you want the same sort of reliability. You must create an account for the service to run under, or use one of the default services. Resit the temptation to run the service as SYSTEM or under an administrator account; if you want to use a built in account use NETWORK SERVICE. It becomes harder to debug in situ. Consider using a error logger such as log4net Having said that I deployed a WCF/Windows service combination for a customer 9 months ago; it's heavily used and hasn't died once. You can request throttle in a Windows service, it's part of the WCF configuration. Note the defaults are very low, it is likely you will have to increase these.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/137840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6441/" ] }
137,845
How do I determine whether an object is a member of a collection in VBA? Specifically, I need to find out whether a table definition is a member of the TableDefs collection.
Your best bet is to iterate over the members of the collection and see if any match what you are looking for. Trust me I have had to do this many times. The second solution (which is much worse) is to catch the "Item not in collection" error and then set a flag to say the item does not exist.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/137845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ] }
137,868
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are. Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked. What are your thoughts on this and what do you follow?
I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of final modifiers anywhere, but when you think about it... Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing. At first, it kind of looks awkward to see a lot of final keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on (you can take it from me ;-) I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something final I'll do it.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/137868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15321/" ] }
137,933
We are writing a complex rich desktop application and need to offer flexibility in reporting formats so we thought we would just expose our object model to a scripting langauge. Time was when that meant VBA (which is still an option), but the managed code derivative VSTA (I think) seems to have withered on the vine. What is now the best choice for an embedded scripting language on Windows .NET?
Personally, I'd use C# as the scripting language. The .NET framework (and Mono, thanks Matthew Scharley) actually includes the compilers for each of the .NET languages in the framework itself. Basically, there's 2 parts to the implementation of this system. Allow the user to compile the codeThis is relatively easy, and can be done in only a few lines of code (though you might want to add an error dialog, which would probably be a couple dozen more lines of code, depending on how usable you want it to be). Create and use classes contained within the compiled assemblyThis is a little more difficult than the previous step (requires a tiny bit of reflection). Basically, you should just treat the compiled assembly as a "plug-in" for the program. There are quite a few tutorials on various ways you can create a plug-in system in C# (Google is your friend). I've implemented a "quick" application to demonstrate how you can implement this system (includes 2 working scripts!). This is the complete code for the application, just create a new one and paste the code in the "program.cs" file.At this point I must apologize for the large chunk of code I'm about to paste (I didn't intend for it to be so large, but got a little carried away with my commenting) using System;using System.Windows.Forms;using System.Reflection;using System.CodeDom.Compiler;namespace ScriptingInterface{ public interface IScriptType1 { string RunScript(int value); }}namespace ScriptingExample{ static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { // Lets compile some code (I'm lazy, so I'll just hardcode it all, i'm sure you can work out how to read from a file/text box instead Assembly compiledScript = CompileCode( "namespace SimpleScripts" + "{" + " public class MyScriptMul5 : ScriptingInterface.IScriptType1" + " {" + " public string RunScript(int value)" + " {" + " return this.ToString() + \" just ran! Result: \" + (value*5).ToString();" + " }" + " }" + " public class MyScriptNegate : ScriptingInterface.IScriptType1" + " {" + " public string RunScript(int value)" + " {" + " return this.ToString() + \" just ran! Result: \" + (-value).ToString();" + " }" + " }" + "}"); if (compiledScript != null) { RunScript(compiledScript); } } static Assembly CompileCode(string code) { // Create a code provider // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones) // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?) Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider(); // Setup our options CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net) options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best! // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows // thus they can only do the things you want them to. // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it) // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to // the "script" options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); // Compile our code CompilerResults result; result = csProvider.CompileAssemblyFromSource(options, code); if (result.Errors.HasErrors) { // TODO: report back to the user that the script has errored return null; } if (result.Errors.HasWarnings) { // TODO: tell the user about the warnings, might want to prompt them if they want to continue // runnning the "script" } return result.CompiledAssembly; } static void RunScript(Assembly script) { // Now that we have a compiled script, lets run them foreach (Type type in script.GetExportedTypes()) { foreach (Type iface in type.GetInterfaces()) { if (iface == typeof(ScriptingInterface.IScriptType1)) { // yay, we found a script interface, lets create it and run it! // Get the constructor for the current type // you can also specify what creation parameter types you want to pass to it, // so you could possibly pass in data it might need, or a class that it can use to query the host application ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes); if (constructor != null && constructor.IsPublic) { // lets be friendly and only do things legitimitely by only using valid constructors // we specified that we wanted a constructor that doesn't take parameters, so don't pass parameters ScriptingInterface.IScriptType1 scriptObject = constructor.Invoke(null) as ScriptingInterface.IScriptType1; if (scriptObject != null) { //Lets run our script and display its results MessageBox.Show(scriptObject.RunScript(50)); } else { // hmmm, for some reason it didn't create the object // this shouldn't happen, as we have been doing checks all along, but we should // inform the user something bad has happened, and possibly request them to send // you the script so you can debug this problem } } else { // and even more friendly and explain that there was no valid constructor // found and thats why this script object wasn't run } } } } } }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/137933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ] }
137,975
The singleton pattern is a fully paid up member of the GoF 's patterns book , but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory classes , and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful. Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why? Please support your answers with " facts, references, or specific expertise "
Paraphrased from Brian Button: They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell . They violate the single responsibility principle : by virtue of the fact that they control their own creation and lifecycle. They inherently cause code to be tightly coupled . This makes faking them out under test rather difficult in many cases. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/137975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ] }
138,040
I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs?
In the RC resource file if the dialog has this style similar to this it will be fixed size: IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU If the dialog has this style it will be sizeable: IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME With these sizable frame options the dialog will be re-sizeable but you will still need to do a lot of work handling the WM_SIZE message to manage the sizing an positioning of the controls within the dialog.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
Here is what I was looking for: static int FreeTcpPort(){ TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port;}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ] }
138,045
Is there something like Python's getattr() in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.
There is also Type.InvokeMember . public static class ReflectionExt{ public static object GetAttr(this object obj, string name) { Type type = obj.GetType(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty; return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null); }} Which could be used like: object value = ReflectionExt.GetAttr(obj, "PropertyName"); or (as an extension method): object value = obj.GetAttr("PropertyName");
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22562/" ] }
138,056
In other words, a block of code like this: (setq initial-major-mode (lambda () (text-mode) (font-lock-mode) )) ... would come out looking like something like this: If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it?
I think you are looking for something like mwe-color-box.el
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ] }
138,096
I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame. Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this. I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. ( http://dnrtv.com/default.aspx?showID=115 ).
the Frame class exposes a method named "Navigate" that takes the content you want to show in your frame as parameter.try calling myFrame.Navigate(myPageObject); this should work
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ] }
138,097
I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid. Is there another way to obtain the PID?
If you have procfs installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case). Thus, with Java, you can do: String pid = new File("/proc/self").getCanonicalFile().getName(); In JRuby, you can use the same solution: pid = java.io.File.new("/proc/self").canonical_file.name Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, Jerub , gregh , and Topdeck )
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ] }
138,099
GWT's serializer has limited java.io.Serializable support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example this FAQ entry says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist. The generated list contains a number of types that are part of the standard library, such as java.lang.String and java.util.HashMap . I get an error when trying to serialize java.sql.Date , which implements the Serializable interface, but is not on the whitelist. How can I add this type to the list?
Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg: public String getStringForDates(ArrayList<java.util.Date> dates); Will result in ArrayList and Date both being included on the whitelist. It gets trickier if you try and use java.lang.Object instead of specific types: public Object getObjectForString(String str); Because the compiler doesn't know what to whitelist. In that case if the objects are not referenced anywhere in your service interface, you have to mark them explicitly with the IsSerializable interface, otherwise it won't let you pass them through the RPC mechanism.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3562/" ] }
138,116
Let's say I click a button on a web page to initiate a submit request. Then I suddenly realize that some data I have provided is wrong and that if it gets submitted, then I will face unwanted consequences (something like a shopping request where I may be forced to pay up for this incorrect request). So I frantically click the Stop button not just once but many times (just in case). What happens in such a scenario? Does the browser just cancel the request without informing the server? If in case it does inform the server, does the server just kill the process or does it also do some rolling back of all actions done as part of this request? I code in Java. Does Java have any special feature that we can use to detect STOP requests and rollback whatever we did as part of this transaction?
A Web Page load from a browser is usually a 4 step process (not considering redirections): Browser sends HTTP Request, when the Server is available Server executes code (for dynamic pages) Server sends the HTTP Response (usually HTML) Browser renders HTML, and asks for other files (images, css, ...) The browser reaction to "Stop" depends on the step your request is at that time: If your server is slow or overloaded, and you hit "Stop" during step 1, nothing happens. The browser doesn't send the request. Most of the times, however, "Stop" will be hit on steps 2, 3 and 4, and in those steps your code is already executed, the browser simply stops waiting for the response (2), or receiving the response (3), or rendering the response (4). The HTTP call itself is always a 2 steps action (Request/Response), and there is no automatic way to rollback the execution from the client
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
138,144
What essential things (functions, aliases, start up scripts) do you have in your profile?
I often find myself needing needing some basic agregates to count/sum some things., I've defined these functions and use them often, they work really nicely at the end of a pipeline : ## useful agregate#function count{ BEGIN { $x = 0 } PROCESS { $x += 1 } END { $x }}function product{ BEGIN { $x = 1 } PROCESS { $x *= $_ } END { $x }}function sum{ BEGIN { $x = 0 } PROCESS { $x += $_ } END { $x }}function average{ BEGIN { $max = 0; $curr = 0 } PROCESS { $max += $_; $curr += 1 } END { $max / $curr }} To be able to get time and path with colors in my prompt : function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) }function prompt{ # Write the time write-host "[" -noNewLine write-host $(Get-Time) -foreground yellow -noNewLine write-host "] " -noNewLine # Write the path write-host $($(Get-Location).Path.replace($home,"~").replace("\","/")) -foreground green -noNewLine write-host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine return "> "} The following functions are stolen from a blog and modified to fit my taste, but ls with colors is very nice : # LS.MSH # Colorized LS function replacement # /\/\o\/\/ 2006 # http://mow001.blogspot.com function LL{ param ($dir = ".", $all = $false) $origFg = $host.ui.rawui.foregroundColor if ( $all ) { $toList = ls -force $dir } else { $toList = ls $dir } foreach ($Item in $toList) { Switch ($Item.Extension) { ".Exe" {$host.ui.rawui.foregroundColor = "Yellow"} ".cmd" {$host.ui.rawui.foregroundColor = "Red"} ".msh" {$host.ui.rawui.foregroundColor = "Red"} ".vbs" {$host.ui.rawui.foregroundColor = "Red"} Default {$host.ui.rawui.foregroundColor = $origFg} } if ($item.Mode.StartsWith("d")) {$host.ui.rawui.foregroundColor = "Green"} $item } $host.ui.rawui.foregroundColor = $origFg }function lla{ param ( $dir=".") ll $dir $true}function la { ls -force } And some shortcuts to avoid really repetitive filtering tasks : # behave like a grep command# but work on objects, used# to be still be allowed to use grepfilter match( $reg ){ if ($_.tostring() -match $reg) { $_ }}# behave like a grep -v command# but work on objectsfilter exclude( $reg ){ if (-not ($_.tostring() -match $reg)) { $_ }}# behave like match but use only -likefilter like( $glob ){ if ($_.toString() -like $glob) { $_ }}filter unlike( $glob ){ if (-not ($_.tostring() -like $glob)) { $_ }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20911/" ] }
138,153
Are there any ncurses libraries in C/C++ for Windows that emulate ncurses in native resizable Win32 windows ( not in console mode)?
There's an ongoing effort for a PDCurses port: http://www.mail-archive.com/[email protected]/msg00129.html http://www.projectpluto.com/win32a.htm
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6619/" ] }